content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def translate_line_test(string):
"""
Translates raw log line into sequence of integer representations for word tokens with sos and eos tokens.
:param string: Raw log line from auth_h.txt
:return: (list) Sequence of integer representations for word tokens with sos and eos tokens.
"""
data = strin... | 5,600 |
def preprocess_signal(signal, sample_rate):
"""
Preprocess a signal for input into a model
Inputs:
signal: Numpy 1D array containing waveform to process
sample_rate: Sampling rate of the input signal
Returns:
spectrogram: STFT of the signal after resampling to 10kHz and adding
... | 5,601 |
def unsubscribe_confirmations(message, futures):
"""Intercepts unsubscribe messages and check for
Future objets with a matching subscribe details.
Parameters
----------
message : str
The unaltered response message returned by bitfinex.
futures : dict
A dict of intercept_id's and... | 5,602 |
def get_frameheight():
"""return fixed height for extra panel
"""
return 120 | 5,603 |
def default_heart_beat_interval() -> int:
"""
:return: in seconds
"""
return 60 | 5,604 |
def email_valid(email):
"""test for valid email address
>>> email_valid('test@testco.com')
True
>>> email_valid('test@@testco.com')
False
>>> email_valid('test@testco')
False
"""
if email == '':
return True
email_re = re.compile(
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]... | 5,605 |
def main():
"""Make a jazz noise here"""
# -------------------------------------------------------------------------------------------------------------------------------
args = get_args()
pic = args.picture
outFile = args.output
# ---------------------------------------------------------------... | 5,606 |
def test_daily_mean_integers():
"""Test that mean function works for an array of positive integers."""
from inflammation.models import daily_mean
test_array = np.array([[1, 2],
[3, 4],
[5, 6]])
# Need to use Numpy testing functions to compare arrays
... | 5,607 |
def mysql(filename=None, **conf):
"""
mysql连接方法
examples:
:type(env) == dict
with mysql(**env) as cur:
cur.execute('select * from message.sms_log
where mobile=175001234567 group by send_time DESC limit 1;')
... | 5,608 |
def get_node_data(workspace: str, graph: str, table: str, node: str) -> Any:
"""Return the attributes associated with a node."""
return Workspace(workspace).graph(graph).node_attributes(table, node) | 5,609 |
def siso_optional(fn, h_opt, scope=None, name=None):
"""Substitution module that determines to include or not the search
space returned by `fn`.
The hyperparameter takes boolean values (or equivalent integer zero and one
values). If the hyperparameter takes the value ``False``, the input is simply
... | 5,610 |
def tree_to_stream(entries, write):
"""Write the give list of entries into a stream using its write method
:param entries: **sorted** list of tuples with (binsha, mode, name)
:param write: write method which takes a data string"""
ord_zero = ord('0')
bit_mask = 7 # 3 bits set
for bin... | 5,611 |
def saconv3x3_block(in_channels,
out_channels,
stride=1,
pad=1,
**kwargs):
"""
3x3 version of the Split-Attention convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_cha... | 5,612 |
def add_hook(**_kwargs):
"""Creates and adds the import hook in sys.meta_path"""
hook = import_hook.create_hook(
transform_source=transform_source,
hook_name=__name__,
extensions=[".pyfr"],
)
return hook | 5,613 |
def mul(n1, n2):
"""
multiply two numbers
"""
return n1 * n2 | 5,614 |
def pytorch_normalze(img):
"""
https://github.com/pytorch/vision/issues/223
return appr -1~1 RGB
"""
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
img = normalize(torch.from_numpy(img))
return img.numpy() | 5,615 |
def get_nic_capacity(driver_info, ilo_fw):
"""Gets the FRU data to see if it is NIC data
Gets the FRU data in loop from 0-255 FRU Ids
and check if the returned data is NIC data. Couldn't
find any easy way to detect if it is NIC data. We should't be
hardcoding the FRU Id.
:param driver_info: Co... | 5,616 |
def test_jones_num_funcs():
""" Test utility functions to convert between jones polarization strings and numbers """
jnums = [-8, -7, -6, -5, -4, -3, -2, -1]
jstr = ['Jyx', 'Jxy', 'Jyy', 'Jxx', 'Jlr', 'Jrl', 'Jll', 'Jrr']
nt.assert_equal(jnums, uvutils.jstr2num(jstr))
nt.assert_equal(jstr, uvutils.... | 5,617 |
def app (arguments:Dict) -> None:
"""top-level of the polynomial solving app.
"""
root = os.path.dirname('/')
paths = {
'tasks': root,
'current_link': os.path.join(root, 'current'),
'solutions': os.path.join(root, 'current/json/solutions.jsonl'),
'pixels': os.path.join(root, 'current/json/pixels.jsonl'),
... | 5,618 |
def ctypes_header_file_create(dataset, output_dir, custom_includes=None):
"""Creates the C types header file in the specified output directory"""
output_path = os.path.join(output_dir, _header_name_get(dataset))
contents = ctypes_header_render(dataset, custom_includes)
templates.file_write_all_data(out... | 5,619 |
def fold_given_batch_norms(model, layer_pairs: List[PairType]):
"""
Fold a given set of batch_norm layers into conv layers
:param model: Model
:param layer_pairs: Pairs of conv and batch_norm layers to use for folding
:return: None
"""
# Assuming that the entire model in on one device
... | 5,620 |
def isValidInifileKeyName(key):
""" Check that this key name is valid to be used in inifiles, and to be used as a python property name on a q or i object """
return re.match("^[\w_]+$", key) | 5,621 |
def installed_pkgs():
"""
Return the list of installed packages on the machine
Returns:
list: List of installed packages
CLI Example:
.. code-block:: bash
salt '*' macpackage.installed_pkgs
"""
cmd = "pkgutil --pkgs"
return __salt__["cmd.run"](cmd).split("\n") | 5,622 |
def extract_feature(audio, sr=44100):
"""
extract feature like below:
sig:
rmse:
silence:
harmonic:
pitch:
audio: audio file or audio list
return feature_list: np of [n_samples, n_features]
"""
feature_list = []
y = []
if isinstance(audio, str):
y, _ = libros... | 5,623 |
def run_with_config(sync, config):
"""
Execute the cartography.sync.Sync.run method with parameters built from the given configuration object.
This function will create a Neo4j driver object from the given Neo4j configuration options (URI, auth, etc.) and
will choose a sensible update tag if one is not... | 5,624 |
def BuildPartialUpdate(clear, remove_keys, set_entries, field_mask_prefix,
entry_cls, env_builder):
"""Builds the field mask and patch environment for an environment update.
Follows the environments update semantic which applies operations
in an effective order of clear -> remove -> set.
... | 5,625 |
def readJSON(
json_path: FilePath, file_text: str = "", conf_file_name: str = ""
) -> object:
"""Reads the JSON from the given file and saves it to a class object with
the JSON elements as attributes.
If an error occurs, the program is exited with an error message!
The JSON must have an element `fi... | 5,626 |
def add_test(name, func, submenu=None, runall=True, runsub=None):
"""Add a new test to the test menu.
Set submenu to a string to put the test in a submenu with that name. Set
runall=False to exclude the test from the top-level "Run all tests"; runall
defaults to True. Set runsub=False to exclude the ... | 5,627 |
def create_schema_usb():
"""Create schema usb."""
return vol.Schema(CONFIG_SCHEMA_USB) | 5,628 |
def _build_field_queries(filters):
"""
Builds field queries.
Same as _build_field_query but expects a dict of field/values and returns a list of queries.
"""
return [
_build_field_query(field, value)
for field, value in filters.items()
] | 5,629 |
def bycode(ent, group):
"""
Get the data with the given group code from an entity.
Arguments:
ent: An iterable of (group, data) tuples.
group: Group code that you want to retrieve.
Returns:
The data for the given group code. Can be a list of items if the group
code occu... | 5,630 |
def change_output_dir(model_name, old_dat, new_dat):
"""
Change the name of an output directory.
Parameters
----------
model_name : string
String of model name.
old_dat : string
String with current output date of model run (to be replaced).
new_dat : string
String ... | 5,631 |
def cmd_web(argv, args):
"""
Usage:
localstack web <subcommand> [options]
Commands:
web start Start the Web dashboard
Options:
--port=<> Network port for running the Web server (default: 8080)
"""
print_version()
if len(argv) <= 1 or argv[1] != 'start':
argv = ['web',... | 5,632 |
def subtract_bg(inputs, out_names=None, x_order=None, y_order=None,
reprocess=None):
"""
Model the instrumental background or scattered light level as a function
of position in the input files (based on the counts within specified
nominally-unilluminated regions) and subtract the result ... | 5,633 |
def update_permissions() -> None:
"""
更新权限角色数据
"""
for role_name, permissions in mapping.items():
role = get_or_create(Role, role_name)
permissions = get_or_create_from_lst(Permission, *permissions)
role.add_permissions(permissions) | 5,634 |
def get_midi_programs(midi: MidiFile) -> List[Tuple[int, bool]]:
""" Returns the list of programs of the tracks of a MIDI, deeping the
same order. It returns it as a list of tuples (program, is_drum).
:param midi: the MIDI object to extract tracks programs
:return: the list of track programs, as a list... | 5,635 |
def is_depth_wise_conv(module):
"""Determine Conv2d."""
if hasattr(module, "groups"):
return module.groups != 1 and module.in_channels == module.out_channels
elif hasattr(module, "group"):
return module.group != 1 and module.in_channels == module.out_channels | 5,636 |
def list_all_routed():
"""
List all the notifications that have been routed to any repository, limited by the parameters supplied
in the URL.
See the API documentation for more details.
:return: a list of notifications appropriate to the parameters
"""
return _list_request() | 5,637 |
def sliding_window(img1, img2, patch_size=(100,302), istep=50):#, jstep=1, scale=1.0):
"""
get patches and thier upper left corner coordinates
The size of the sliding window is currently fixed.
patch_size: sliding_window's size'
istep: Row stride
"""
Ni, Nj = (int(s) for s in patch_size)
for i in range(... | 5,638 |
def read(file_name):
"""Read in the supplied file name from the root directory.
Args:
file_name (str): the name of the file
Returns: the content of the file
"""
this_dir = os.path.dirname(__file__)
file_path = os.path.join(this_dir, file_name)
with open(file_path) as f:
retur... | 5,639 |
def run_command(message, command_name, params, command=None):
"""登録したコマンドに対して各種操作を行う
:param message: slackbot.dispatcher.Message
:param str command: 登録済のコマンド名
:param str params: 操作内容 + 語録
"""
# コマンドが登録済みの場合、登録済みコマンドの方で
# 応答をハンドルしている為ここではリターンする
if command_name in command_patterns(message... | 5,640 |
def prepare_stdin(
method: str, basis: str, keywords: Dict[str, Any], charge: int, mult: int, geoopt: Optional[str] = ""
) -> str:
"""Prepares a str that can be sent to define to produce the desired
input for Turbomole."""
# Load data from keywords
unrestricted = keywords.get("unrestricted", False)... | 5,641 |
def Lstart(gridname='BLANK', tag='BLANK', ex_name='BLANK'):
"""
This adds more run-specific entries to Ldir.
"""
# put top level information from input into a dict
Ldir['gridname'] = gridname
Ldir['tag'] = tag
Ldir['ex_name'] = ex_name
# and add a few more things
Ldir['gtag'] = gridn... | 5,642 |
def summation(n, term):
"""Return the sum of numbers 1 through n (including n) wíth term applied to each number.
Implement using recursion!
>>> summation(5, lambda x: x * x * x) # 1^3 + 2^3 + 3^3 + 4^3 + 5^3
225
>>> summation(9, lambda x: x + 1) # 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
54
>>> s... | 5,643 |
def rfe_w2(x, y, p, classifier):
"""RFE algorithm, where the ranking criteria is w^2,
described in [Guyon02]_. `classifier` must be an linear classifier
with learn() and w() methods.
.. [Guyon02] I Guyon, J Weston, S Barnhill and V Vapnik. Gene Selection for Cancer Classification using Support... | 5,644 |
def compress_timeline(timeline: List, salt: bytes) -> List:
"""
Compress the verbose Twitter feed into a small one. Just keep the useful elements.
The images are downloaded per-request.
Args:
timeline (List): The Twitter timeline.
salt (bytes): The salt to apply on the filename.
Re... | 5,645 |
def validate_non_empty_img_list(item_list):
"""[summary]
Args:
item_list ([type]): [description]
Raises:
EmptyImageDatasetError: [description]
"""
if item_list:
pass
else:
raise EmptyImageDatasetError(item_list) | 5,646 |
def createFinalCompactedData(compacted_data,elevations):
"""
This function creates a dataframe that combines the RGB data and the elevations data
into a dataframe that can be used for analysis
Parameters
----------
compacted_data : list of compacted data returned from condensePixels.
... | 5,647 |
def get_sorted_nodes_edges(bpmn_graph):
"""
Assure an ordering as-constant-as-possible
Parameters
--------------
bpmn_graph
BPMN graph
Returns
--------------
nodes
List of nodes of the BPMN graph
edges
List of edges of the BPMN graph
"""
graph = bpmn... | 5,648 |
def treat_the_ducks(animals):
"""
treat the ducks finds all the ducks in the list of given animals and:
1. gives them proper exercise - walking and quacking
2. feeds them with appropriate duck food
"""
for animal in animals:
print()
print(animal_type_name(animal), ':')
... | 5,649 |
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Samsung TV platform."""
known_devices = hass.data.get(KNOWN_DEVICES_KEY)
if known_devices is None:
known_devices = set()
hass.data[KNOWN_DEVICES_KEY] = known_devices
uuid = None
# Is this a manual co... | 5,650 |
def test_work_order_specialcharacter_data_single_index_indata(setup_config):
"""Testing work order request with all
special characters in index of indata """
# input file name
request = 'work_order_tests/input' \
'/work_order_specialcharacter_data_single_index_indata.json'
work_order_... | 5,651 |
def output_nums(
queue_double_nums: queue.Queue[int],
p_double_nums_done: threading.Event) -> None:
""" output nums """
one_last_time = False
while True:
try:
num = queue_double_nums.get(timeout=0.1)
print("output nums: " + str(num))
except queue.Empty:
... | 5,652 |
def list_commits(
access_key: str,
url: str,
owner: str,
dataset: str,
*,
revision: Optional[str] = None,
offset: Optional[int] = None,
limit: Optional[int] = None,
) -> Dict[str, Any]:
"""Execute the OpenAPI `GET /v2/datasets/{owner}/{dataset}/commits`.
Arguments:
acces... | 5,653 |
def dijkstra(graph, start, end=None):
"""
Find shortest paths from the start vertex to all
vertices nearer than or equal to the end.
The input graph G is assumed to have the following
representation: A vertex can be any object that can
be used as an index into a dictionary. G is a
dictiona... | 5,654 |
def get_owner_from_path(path):
"""Get the username of the owner of the given file"""
if "pwd" in sys.modules:
# On unix
return pwd.getpwuid(os.stat(path).st_uid).pw_name
# On Windows
f = win32security.GetFileSecurity(path, win32security.OWNER_SECURITY_INFORMATION)
username, _, _ = ... | 5,655 |
def tournament_selection(pop, size):
""" tournament selection
individual eliminate one another until desired breeding size is reached
"""
participants = [ind for ind in pop.population]
breeding = []
# could implement different rounds here
# but I think that's almost the same as calling tour... | 5,656 |
def save_state_temp(state_temp_df, output_data):
"""
Save United States' state temperature dimension table dataframe to parquet files in S3.
Arguments:
state_temp_df - State temperature dataframe
output_data - Location of parquet files output data
Returns:
None
"""... | 5,657 |
def bond_number(r_max, sigma, rho_l, g):
""" calculates the Bond number for the largest droplet according to
Cha, H.; Vahabi, H.; Wu, A.; Chavan, S.; Kim, M.-K.; Sett, S.; Bosch, S. A.; Wang, W.; Kota, A. K.; Miljkovic, N.
Dropwise Condensation on Solid Hydrophilic Surfaces. Science Advances 2020, 6 (2),... | 5,658 |
def test_parent_table_type(input_field, table_type):
"""Test ``parent_table_type`` property."""
assert input_field.parent_table_type == table_type | 5,659 |
def validate_singularity(descript_dict, sub_params, params, name):
"""If Singularity is enabled in a group, there should be at least one user wrapper for that group
@param descript_dict: dictionaries with user files
@param sub_params: attributes in the group section of the XML file
@param params: attri... | 5,660 |
def spatial_conv(inputs,
conv_type,
kernel,
filters,
stride,
is_training,
activation_fn='relu',
data_format='channels_last'):
"""Performs 1x1 conv followed by 2d or depthwise conv.
Args:
input... | 5,661 |
async def timeron(websocket, battleID):
"""Start the timer on a Metronome Battle.
"""
return await websocket.send(f'{battleID}|/timer on') | 5,662 |
def to_unit_vector(this_vector):
""" Convert a numpy vector to a unit vector
Arguments:
this_vector: a (3,) numpy array
Returns:
new_vector: a (3,) array with the same direction but unit length
"""
norm = numpy.linalg.norm(this_vector)
assert norm > 0.0, "vector norm must be gr... | 5,663 |
def simulate_SA_faults(model, path, N, criterion):
""" Load the model"""
checkpoint = torch.load(path)
model.load_state_dict(checkpoint['model_state_dict'])
print('Best acc ', checkpoint['test_accuracy']) # assumes model saves checkpoint accuracy
print("Evaluating Stuck-At Faults:-----------------... | 5,664 |
def decode(msg):
""" Convert data per pubsub protocol / data format
Args:
msg: The msg from Google Cloud
Returns:
data: The msg data as a string
"""
if 'data' in msg:
data = base64.b64decode(msg['data']).decode('utf-8')
return data | 5,665 |
def pivot_longer_by_humidity_and_temperature(df: pd.DataFrame) -> pd.DataFrame:
"""
Reshapes the dataframe by collapsing all of the temperature and humidity
columns into an temperature, humidity, and location column
Parameters
----------
df : pd.DataFrame
The cleaned and renamed datafra... | 5,666 |
def add_counter_text(img, box_shape, people_in):
"""
Add person counter text on the image
Args:
img (np.array): Image
box_shape (tuple): (width, height) of the counter box
people_in (int): Number representing the amount of
people inside the space
Returns:
(n... | 5,667 |
def create_override(override):
"""Takes override arguments as dictionary and applies them to copy of current context"""
override_context = bpy.context.copy()
for key, value in override.items():
override_context[key] = value
return override_context | 5,668 |
def get_result_file(request):
"""Return the content of the transformed code.
"""
resdir = get_resultdir(request)
workdir = os.path.basename(request.session['workdir']) # sanitized
name = os.path.basename(request.matchdict.get('name', 'result-%s.txt' % workdir))
ext = os.path.splitext(nam... | 5,669 |
def load_or_make_json(file, *, default=None):
"""Loads a JSON file, or makes it if it does not exist."""
if default is None:
default = {}
return __load_or_make(file, default, json.load, json.dump) | 5,670 |
def plot_predictions(image, df, color=None, thickness=1):
"""Plot a set of boxes on an image
By default this function does not show, but only plots an axis
Label column must be numeric!
Image must be BGR color order!
Args:
image: a numpy array in *BGR* color order! Channel order is channels ... | 5,671 |
def apply_changes(new_orders):
"""
Updates API items based on the parameter.
:param new_orders: dictionary mapping item IDs to ordering numbers.
"""
__api.items.reorder(items=[{'id': id, 'child_order': order} for id, order in new_orders.items()]) | 5,672 |
def stationary_points(f, symbol, domain=S.Reals):
"""
Returns the stationary points of a function (where derivative of the
function is 0) in the given domain.
Parameters
==========
f : Expr
The concerned function.
symbol : Symbol
The variable for which the stationary points... | 5,673 |
def _create_table(data_list, headers):
""" Create a table for given data list and headers.
Args:
data_list(list): list of dicts, which keys have to cover headers
headers(list): list of headers for the table
Returns:
new_table(tabulate): created table, re... | 5,674 |
def test_get_dns_name_and_fall_back_ip_address_cannot_be_resolved(mocker, capsys):
"""
When the fallback to mount target ip address is enabled, the mount target ip address is retrieved but cannot be connected
"""
config = _get_mock_config()
mount_efs.BOTOCORE_PRESENT = True
check_fallback_enable... | 5,675 |
def set_text(view, text, scroll=False):
"""Replaces the entire content of view with the text specified.
`scroll` parameter specifies whether the view should be scrolled to the end.
"""
with Edit(view) as edit:
edit.erase(Region(0, view.size()))
edit.insert(0, text)
if scroll:
... | 5,676 |
def vagrant_upload(args):
"""Replaces an input file in the VM.
"""
target = Path(args.target[0])
files = args.file
unpacked_info = read_dict(target)
input_files = unpacked_info.setdefault('input_files', {})
use_chroot = unpacked_info['use_chroot']
try:
SSHUploader(target, input_... | 5,677 |
def _validate_attribute_id(this_attributes, this_id, xml_ids, enforce_consistency, name):
""" Validate attribute id.
"""
# the given id is None and we don't have setup attributes
# -> increase current max id for the attribute by 1
if this_id is None and this_attributes is None:
this_id = ma... | 5,678 |
def Arrows2D(startPoints, endPoints=None,
shaftLength=0.8,
shaftWidth=0.09,
headLength=None,
headWidth=0.2,
fill=True,
c=None,
cmap=None,
alpha=1):
"""
Build 2D arrows between two lists of points `startPoints... | 5,679 |
def filter_characters(results: list) -> str:
"""Filters unwanted and duplicate characters.
Args:
results: List of top 1 results from inference.
Returns:
Final output string to present to user.
"""
text = ""
for i in range(len(results)):
if results[i] == "$":
... | 5,680 |
def add_label_noise(y: torch.Tensor, p_flip: float):
"""Flips binary labels with some probability `p_flip`."""
n_select = int(p_flip * y.shape[0])
flip_ix = choice([i for i in range(y.shape[0])], size=n_select)
y[flip_ix] = 1 - y[flip_ix] | 5,681 |
def seq_alignment_files(file1, file2, outputfile=""):
"""This command takes 2 fasta files as input, each file contains a single sequence. It reads the 2 sequences from
files and get all their alignments along with the score. The -o is an optional parameter if we need the output to
be written on a file inste... | 5,682 |
def test_present_set_target():
"""
test alias.present set target
"""
name = "saltdude"
target = "dude@saltstack.com"
ret = {
"comment": "Set email alias {} -> {}".format(name, target),
"changes": {"alias": name},
"name": name,
"result": True,
}
has_target... | 5,683 |
def main(Block: type[_Block], n: int, difficulty: int) -> list[tuple[float, int]]:
"""Test can hash a block"""
times_and_tries = []
for i in range(n):
block = Block(rand_block_hash(), [t], difficulty=difficulty)
# print(f"starting {i}... ", end="", flush=True)
with time_it() as timer... | 5,684 |
def test_model_id(model_id):
"""
Check model has same model_id as referred
"""
model = get_model(model_id)
assert model
real_model_id = get_model_id(model)
assert real_model_id == model_id | 5,685 |
def main():
"""Main processing."""
usage = '%prog [options]'
parser = OptionParser(usage=usage, version=VERSION)
parser.add_option(
'--man',
action='store_true', dest='man', default=False,
help='Display manual page-like help and exit.',
)
parser.add_option(
'-m'... | 5,686 |
def is_castable_to_float(value: Union[SupportsFloat, str, bytes, bytearray]) -> bool:
"""
prüft ob das objekt in float umgewandelt werden kann
Argumente : o_object : der Wert der zu prüfen ist
Returns : True|False
Exceptions : keine
>>> is_castable_to_float(1)
True
>>> is_castab... | 5,687 |
def list_unique(hasDupes):
"""Return the sorted unique values from a list"""
# order preserving
from operator import itemgetter
d = dict((x, i) for i, x in enumerate(hasDupes))
return [k for k, _ in sorted(d.items(), key=itemgetter(1))] | 5,688 |
def filter_by_networks(object_list, networks):
"""Returns a copy of object_list with all objects that are not in the
network removed.
Parameters
----------
object_list: list
List of datamodel objects.
networks: string or list
Network or list of networks to check for.
Return... | 5,689 |
def get_all_data(year=year, expiry=1, fielding=False, chadwick=False):
"""Grab all data and write core files."""
"""Options for fielding data and bio data for rookies/master."""
name_url_pairs = url_maker(year=year, fielding=fielding)
# if debugging warn about the webviews
if module_log.isEnabledFor... | 5,690 |
def score_per_year_by_country(country):
"""Returns the Global Terrorism Index (GTI) per year of the given country."""
cur = get_db().execute('''SELECT iyear, (
1*COUNT(*)
+ 3*SUM(nkill)
+ 0.5*SUM(nwound)
+ 2*SUM(case propextent when 1.0 then 1 else 0 end)
+ 2*SUM(case propextent when 2.0 the... | 5,691 |
def line_2d_to_3d(line, zs=0, zdir='z'):
"""Convert a 2D line to 3D."""
line.__class__ = Line3D
line.set_3d_properties(zs, zdir) | 5,692 |
def build(options, is_training):
"""Builds a model based on the options.
Args:
options: A model_pb2.Model instance.
Returns:
A model instance.
Raises:
ValueError: If the model proto is invalid or cannot find a registered entry.
"""
if not isinstance(options, model_pb2.Model):
raise ValueE... | 5,693 |
def string_to_rdkit(frmt: str, string: str, **kwargs) -> RDKitMol:
"""
Convert string representation of molecule to RDKitMol.
Args:
frmt: Format of string.
string: String representation of molecule.
**kwargs: Other keyword arguments for conversion function.
Returns:
RDK... | 5,694 |
def test_compare_ccm_block_toeplitz_pi_grads(lorenz_dataset):
"""Test whether calculating the grad of PI from cross cov mats with and without
the block-Toeplitz algorithm gives the same value."""
_, d, _, ccms, _ = lorenz_dataset
assert_allclose(calc_pi_from_cross_cov_mats(ccms),
cal... | 5,695 |
def scatterplot():
"""
Graphs a scatterplot of computed values at every r value in range [2.9, 4] with an iteration of 0.001
Sets r value at 2.9
"""
xs = []
ys = []
r = 2.9
for r in np.arange(2.9, 4, 0.001):
temp_mystery = MysterySequence(r, 0.5, 300)
temp_ys = temp_myst... | 5,696 |
def eh_bcm_debug_show(dut, af='both', table_type='all', ifname_type=None):
"""
Error handling debug API
Author : Prudvi Mangadu (prudvi.mangadu@broadcom.com)
:param dut:
:param af:
:param table_type:
:return:
"""
st.banner("Error handling DEBUG Calls - START")
if af == 'ipv4' or ... | 5,697 |
def clean_datetime_remove_ms(atime):
"""
将时间对象的 毫秒 全部清零
:param atime:
:return:
"""
return datetime(atime.year, atime.month, atime.day, atime.hour, atime.minute, atime.second) | 5,698 |
def perDay(modified):
"""Auxiliary in provenance filtering: chunk the trails into daily bits."""
chunks = {}
for m in modified:
chunks.setdefault(dt.date(m[1]), []).append(m)
return [chunks[date] for date in sorted(chunks)] | 5,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.