content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def splinter_session_scoped_browser():
"""Make it test scoped."""
return False | 30,100 |
def sample_mask(source, freq_vocab, threshold=1e-3, min_freq=0, seed=None, name=None):
"""Generates random mask for downsampling high frequency items.
Args:
source: string `Tensor` of any shape, items to be sampled.
freq_vocab: `Counter` with frequencies vocabulary.
threshold: `float`, ... | 30,101 |
def _xList(l):
"""
"""
if l is None:
return []
return l | 30,102 |
def test_grid_length(grid):
"""
Grid:
[
["a", "b", "c"],
["m", "o", "y"]
]
"""
assert len(grid) == 2 | 30,103 |
def main() -> None:
"""
Standard main function.
"""
print(fetch_url("https://python.org"))
print("")
print(fetch_url("https://python.org"))
time.sleep(11)
print(fetch_url("https://python.org")) | 30,104 |
def IABN2Float(module: nn.Module) -> nn.Module:
"""If `module` is IABN don't use half precision."""
if isinstance(module, InplaceAbn):
module.float()
for child in module.children():
IABN2Float(child)
return module | 30,105 |
def check_heartbeat() -> None:
"""
Check the agent's heartbeat by verifying heartbeat file has been recently modified
"""
current_timestamp = pendulum.now().timestamp()
last_modified_timestamp = path.getmtime("{}/heartbeat".format(AGENT_DIRECTORY))
# If file has not been modified in the last 40... | 30,106 |
def start_of_day(val):
"""
Return a new datetime.datetime object with values that represent
a start of a day.
:param val: Date to ...
:type val: datetime.datetime | datetime.date
:rtype: datetime.datetime
"""
if type(val) == date:
val = datetime.fromordinal(val.toordinal())
r... | 30,107 |
def test_init_asana(asana):
"""Tests Asana initialization.
"""
assert asana
asana.client.options['client_name'] = 'brewbot'
me = asana.client.users.me()
assert me['workspaces'][0]['name'] == 'lakeannebrewhouse.com' | 30,108 |
def setup():
""" Setup """
size(100,100) | 30,109 |
def pending_mediated_transfer(app_chain, token_network_identifier, amount, identifier):
""" Nice to read shortcut to make a LockedTransfer where the secret is _not_ revealed.
While the secret is not revealed all apps will be synchronized, meaning
they are all going to receive the LockedTransfer message.
... | 30,110 |
def get_comments(post, sort_mode='hot', max_depth=5, max_breadth=5):
"""
Retrieves comments for a post.
:param post: The unique id of a Post from which Comments will be returned.
:type post: `str` or :ref:`Post`
:param str sort_mode: The order that the Posts will be sorted by. Options are: "top... | 30,111 |
def neighbor_json(json):
"""Read neighbor game from json"""
utils.check(
json['type'].split('.', 1)[0] == 'neighbor', 'incorrect type')
return _NeighborDeviationGame(
gamereader.loadj(json['model']),
num_neighbors=json.get('neighbors', json.get('devs', None))) | 30,112 |
def get_b16_config():
"""Returns the ViT-B/16 configuration."""
config = ml_collections.ConfigDict()
config.name = 'ViT-B_16'
config.half_precision = True
config.encoder = ml_collections.ConfigDict()
config.encoder.patches = ml_collections.ConfigDict({'size': (16, 16)})
config.encoder.hidden_size = 768
... | 30,113 |
def build_container_hierarchy(dct):
"""Create a hierarchy of Containers based on the contents of a nested dict.
There will always be a single top level scoping Container regardless of the
contents of dct.
"""
top = Container()
for key,val in dct.items():
if isinstance(val, dict): # it's ... | 30,114 |
def occ_frac(stop_rec_range, bin_size_minutes, edge_bins=1):
"""
Computes fractional occupancy in inbin and outbin.
Parameters
----------
stop_rec_range: list consisting of [intime, outtime]
bin_size_minutes: bin size in minutes
edge_bins: 1=fractional, 2=whole bin
Returns
-------
... | 30,115 |
def geomprogr_mesh(N=None, a=0, L=None, Delta0=None, ratio=None):
"""Compute a sequence of values according to a geometric progression.
Different options are possible with the input number of intervals in the
sequence N, the length of the first interval Delta0, the total length L
and the ratio of the so... | 30,116 |
def list_subclasses(package, base_class):
"""
Dynamically import all modules in a package and scan for all subclasses of a base class.
`package`: the package to import
`base_class`: the base class to scan for subclasses
return: a dictionary of possible subclasses with class name as key and class typ... | 30,117 |
def maxima_in_range(r, g_r, r_min, r_max):
"""Find the maxima in a range of r, g_r values"""
idx = np.where(np.logical_and(np.greater_equal(r, r_min), np.greater_equal(r_max, r)))
g_r_slice = g_r[idx]
g_r_max = g_r_slice[g_r_slice.argmax()]
idx_max, _ = find_nearest(g_r, g_r_max)
return r[idx_ma... | 30,118 |
def shared_fit_preprocessing(fit_class):
"""
Shared preprocessing to get X, y, class_order, and row_weights.
Used by _materialize method for both python and R fitting.
:param fit_class: PythonFit or RFit class
:return:
X: pd.DataFrame of features to use in fit
y: pd.Series of target... | 30,119 |
def webhook():
"""
Triggers on each GET and POST request. Handles GET and POST requests using this function.
:return: Return status code acknowledge for the GET and POST request
"""
if request.method == 'POST':
data = request.get_json(force=True)
log(json.dumps(data)) # you may not... | 30,120 |
def extract_winner(state: 'TicTacToeState') -> str:
"""
Return the winner of the game, or announce if the game resulted in a
tie.
"""
winner = 'No one'
tictactoe = TicTacToeGame(True)
tictactoe.current_state = state
if tictactoe.is_winner('O'):
winner = 'O'
elif tictactoe.is_... | 30,121 |
def _prensor_value_fetch(prensor_tree: prensor.Prensor):
"""Fetch function for PrensorValue. See the document in session_lib."""
# pylint: disable=protected-access
type_spec = prensor_tree._type_spec
components = type_spec._to_components(prensor_tree)
def _construct_prensor_value(component_values):
return... | 30,122 |
def test_can_parse_a_unary_array_from_single_step():
"""
It should extract a single ordinary step correctly into an array of steps
"""
steps = parse_steps(I_HAVE_TASTY_BEVERAGES)
assert len(steps) == 1
assert isinstance(steps[0], Step)
assert steps[0].sentence == first_line_of(I_HAVE_TASTY_... | 30,123 |
def start_workers_with_fabric():
""" testing spinning up workers using fabric """
tmp_file = open(settings.AUTOSCALE_TMP_FILE, 'w')
tmp_file.write('running')
tmp_file.close()
subprocess.call("/usr/local/bin/fab \
-f /opt/codebase/auto-scale/fabfile.py \
create... | 30,124 |
def test_glob_list(mock_glob):
"""Multiple paths ok."""
context = Context({
'ok1': 'ov1',
'glob': ['./arb/x', './arb/y', './arb/z']})
mock_glob.return_value = [
'./f1.1',
'./f2.1',
'./f2.2',
'./f2.3',
]
with patch_logger('pypyr.steps.glob', logging.I... | 30,125 |
def request_validation_error(error):
"""Handles Value Errors from bad data"""
message = str(error)
app.logger.error(message)
return {
'status_code': status.HTTP_400_BAD_REQUEST,
'error': 'Bad Request',
'message': message
}, status.HTTP_400_BAD_REQUEST | 30,126 |
def all(request):
"""Handle places list page."""
places = Place.objects.all()
context = {'places': places}
return render(request, 'rental/list_place.html', context) | 30,127 |
def get_key_by_value(dictionary, search_value):
"""
searchs a value in a dicionary and returns the key of the first occurrence
:param dictionary: dictionary to search in
:param search_value: value to search for
"""
for key, value in dictionary.iteritems():
if value == search_value:
... | 30,128 |
def _subtract_ten(x):
"""Subtracts 10 from x using control flow ops.
This function is equivalent to "x - 10" but uses a tf.while_loop, in order
to test the use of functions that involve control flow ops.
Args:
x: A tensor of integral type.
Returns:
A tensor representing x - 10.
"""
def stop_con... | 30,129 |
def load_fortune_file(f: str) -> list:
"""
load fortunes from a file and return it as list
"""
saved = []
try:
with open(f, 'r') as datfile:
text = datfile.read()
for line in text.split('%'):
if len(line.strip()) > 0:
saved.append(l... | 30,130 |
def maskStats(wins, last_win, mask, maxLen):
"""
return a three-element list with the first element being the total proportion of the window that is masked,
the second element being a list of masked positions that are relative to the windown start=0 and the window end = window length,
and the third bein... | 30,131 |
def dsoftmax(Z):
"""Given a (m,n) matrix, returns a (m,n,n) jacobian matrix"""
m,n=np.shape(Z)
softZ=(softmax(Z))
prodtensor=np.einsum("ij,ik->ijk",softZ,softZ)
diagtensor=np.einsum('ij,jk->ijk', softZ, np.eye(n, n))
return diagtensor-prodtensor | 30,132 |
async def vbd_unplug(cluster_id: str, vbd_uuid: str):
"""Unplug from VBD"""
try:
session = create_session(
_id=cluster_id, get_xen_clusters=Settings.get_xen_clusters()
)
vbd: VBD = VBD.get_by_uuid(session=session, uuid=vbd_uuid)
if vbd is not None:
ret = ... | 30,133 |
def scrape_sentence(file_path: str):
"""Scrape list of sentence in txtfile, separated by newline."""
root_dump = Sentence.ROOT
root_dump.mkdir(parents=True, exist_ok=True)
scraper(Sentence, _load_words(file_path), root_dump) | 30,134 |
def write_file_latest(data: List[Any], file_path: str) -> None:
"""writes the most recent file as -latest.md"""
logging.debug("writing file -latest: %s", file_path)
table = tabulate(data, headers="keys", showindex="always", tablefmt="github")
last_char_index = file_path.rfind("/")
latest_file_path =... | 30,135 |
def read_ignore_patterns(f: BinaryIO) -> Iterable[bytes]:
"""Read a git ignore file.
Args:
f: File-like object to read from
Returns: List of patterns
"""
for line in f:
line = line.rstrip(b"\r\n")
# Ignore blank lines, they're used for readability.
if not line:
... | 30,136 |
def calculate_age(created, now):
"""
Pprepare a Docker CLI-like output of image age.
After researching `datetime`, `dateutil` and other libraries
I decided to do this manually to get as close as possible to
Docker CLI output.
`created` and `now` are both datetime.datetime objects.
"""
a... | 30,137 |
def Maxout(x, num_unit):
"""
Maxout as in the paper `Maxout Networks <http://arxiv.org/abs/1302.4389>`_.
Args:
x (tf.Tensor): a NHWC or NC tensor. Channel has to be known.
num_unit (int): a int. Must be divisible by C.
Returns:
tf.Tensor: of shape NHW(C/num_unit) named ``output... | 30,138 |
def is_youtube_url(url: str) -> bool:
"""Checks if a string is a youtube url
Args:
url (str): youtube url
Returns:
bool: true of false
"""
match = re.match(r"^(https?\:\/\/)?(www\.youtube\.com|youtu\.be)\/.+$", url)
return bool(match) | 30,139 |
def time_nanosleep():
""" Delay for a number of seconds and nanoseconds"""
return NotImplementedError() | 30,140 |
def get_regions(positions, genome_file, base=0, count=7):
"""Return a list of regions surrounding a position.
Will loop through each chromosome and search all positions in that
chromosome in one batch. Lookup is serial per chromosome.
Args:
positions (dict): Dictionary of {chrom->positons}
... | 30,141 |
def test_evaluate_sets_all_inputs_clean(clear_default_graph):
"""After the evaluation, the inputs are considered clean."""
node = SquareNode()
node.inputs['in1'].value = 2
node.inputs['compound_in']['0'].value = 0
assert node.is_dirty
node.evaluate()
assert not node.is_dirty | 30,142 |
def set_pin_connection(
conn, write_cur, pin_graph_node_pkey, forward, graph_node_pkey, tracks
):
""" Sets pin connection box location canonical location.
Tracks that are a part of the pinfeed also get this location.
"""
cur = conn.cursor()
cur2 = conn.cursor()
cur.execute(
"""... | 30,143 |
def render_series_fragment(site_config):
"""
Adds "other posts in this series" fragment to series posts.
"""
series_fragment = open("_includes/posts_in_series.html", "r").read()
for post_object in site_config["series_posts"]:
print("Generating 'Other posts in this series' fragment for " + p... | 30,144 |
def create_barplot_orthologues_by_species(df, path, title, colormap, genes, species):
"""
The function creates a bar plot using seaborn.
:param df: pandas.DataFrame object
:param path: The CSV file path.
:param title: Title for the plot.
:param colormap: Colormap
:param genes: Ordered list o... | 30,145 |
def import_tracks(postgres_pwd):
"""
Imports tracks and labels tables to Postgres database
"""
if os.path.exists('config/tracks.csv') and os.path.exists('config/labels/labels.csv'):
print('Importing tables to Postgres database..')
time.sleep(2)
connection_error = False
t... | 30,146 |
def get_class_by_name(name):
"""Gets a class object by its name, e.g. sklearn.linear_model.LogisticRegression"""
if name.startswith('cid.analytics'):
# We changed package names in March 2017. This preserves compatibility with old models.
name = name.replace('cid.analytics', 'analytics.core')
... | 30,147 |
def numero_22():
"""numero_22"""
check50.run("python3 numeros_introescos.py").stdin("11031103\n11031130", prompt=False).stdout("11031103\n11031104\n11031105\n11031106\n11031107\n11031108\n11031109\n11031110\n11031111\n11031112\n11031113\n11031114\n11031115\n11031116\n11031117\n11031118\n11031119\n11031120\n1103... | 30,148 |
def parse_additive(token):
"""
Parse token type - Additive
"""
track(token, False)
if hasattr(token, '_fields'):
for f in token._fields:
track(f, False)
if is_tainted(getattr(token, f)):
common.logger.debug("TAINTED: " + str(token))
else:
if list_checker(token, f):
common.logger.debug("TAIN... | 30,149 |
def _single_optimize(
direction,
criterion,
criterion_kwargs,
params,
algorithm,
constraints,
algo_options,
derivative,
derivative_kwargs,
criterion_and_derivative,
criterion_and_derivative_kwargs,
numdiff_options,
logging,
log_options,
error_handling,
err... | 30,150 |
def item_len(item):
"""return length of the string format of item"""
return len(str(item)) | 30,151 |
def main():
"""
main
"""
with open('input.txt') as fp:
data = sorted([int(line.strip()) for line in fp.readlines()])
data.insert(0, 0)
print('part 1 answer:', part1(data)) | 30,152 |
def get_progress_logger():
"""Returns the swift progress logger"""
return progress_logger | 30,153 |
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None):
"""Retry calling the decorated function using an exponential backoff.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
:param Exceptio... | 30,154 |
def instantiate_me(spec2d_files, spectrograph, **kwargs):
"""
Instantiate the CoAdd2d subclass appropriate for the provided
spectrograph.
The class must be subclassed from Reduce. See :class:`Reduce` for
the description of the valid keyword arguments.
Args:
spectrograph
(:... | 30,155 |
def quoteattr(s, table=ESCAPE_ATTR_TABLE):
"""Escape and quote an attribute value.
"""
for c, r in table:
if c in s:
s = s.replace(c, r)
return '"%s"' % s | 30,156 |
def is_numeric(array):
"""Return False if any value in the array or list is not numeric
Note boolean values are taken as numeric"""
for i in array:
try:
float(i)
except ValueError:
return False
else:
return True | 30,157 |
def reductions_right(collection, callback=None, accumulator=None):
"""This method is like :func:`reductions` except that it iterates over
elements of a `collection` from right to left.
Args:
collection (list|dict): Collection to iterate over.
callback (mixed): Callback applied per iteration... | 30,158 |
def pelt_settling_time(margin=1, init=0, final=PELT_SCALE, window=PELT_WINDOW, half_life=PELT_HALF_LIFE, scale=PELT_SCALE):
"""
Compute an approximation of the PELT settling time.
:param margin: How close to the final value we want to get, in PELT units.
:type margin_pct: float
:param init: Initia... | 30,159 |
def affichage_graphiques(v, a, t, EpSim, EkSim):
"""plot and shows physics of the track, such as :
velocity, acceleation, potential energy, and kinetic energy, all according to time"""
# affichage de la vitesse, et de l'accélération en fonction du temps
# print("\n", v, "\n\n\n", a)
energy_to... | 30,160 |
def get_file_content(url, comes_from=None):
"""Gets the content of a file; it may be a filename, file: URL, or
http: URL. Returns (location, content). Content is unicode."""
match = _scheme_re.search(url)
if match:
scheme = match.group(1).lower()
if (scheme == 'file' and comes_from
... | 30,161 |
def InstancesOverlap(instanceList,instance):
"""Returns True if instance contains a vertex that is contained in an instance of the given instanceList."""
for instance2 in instanceList:
if InstanceOverlap(instance,instance2):
return True
return False | 30,162 |
def git_push(ctx):
"""
Push new version and corresponding tag to origin
:return:
"""
# get current version
new_version = version.__version__
values = list(map(lambda x: int(x), new_version.split('.')))
# Push to origin new version and corresponding tag:
# * commit new version
#... | 30,163 |
def extract_relative_directory(archive, member_path, dest_dir):
""" Extracts all members from the archive that match the path specified
Will strip the specified path from the member before copying to the
destination
"""
if not member_path.endswith('/'):
member_path += '/'
offset... | 30,164 |
def pprint(strings) -> None:
"""
Pretty prints string arrays
:param strings: An array of strings
:type strings: list[str]
:return: None
:rtype: None
"""
for i in range(len(strings)):
print(strings[i]) | 30,165 |
def calc_qm_lea(p_zone_ref, temp_zone, temp_ext, u_wind_site, dict_props_nat_vent):
"""
Calculation of leakage infiltration and exfiltration air mass flow as a function of zone indoor reference pressure
:param p_zone_ref: zone reference pressure (Pa)
:param temp_zone: air temperature in ventilation zon... | 30,166 |
def test_collect_missing_module():
"""Assert error is raised for missing modules."""
handler = get_handler(theme="material")
with pytest.raises(CollectionError):
handler.collect("aaaaaaaa", {}) | 30,167 |
def adjust_learning_rate(learning_rate, weight_decay, optimizer, epoch, lr_steps):
"""Sets the learning rate to the initial LR decayed by 10 every 20 or 30 epochs"""
decay = 0.1 ** (sum(epoch >= np.array(lr_steps)))
lr = learning_rate * decay
for param_group in optimizer.param_groups:
param_grou... | 30,168 |
def folder2Outline( folder, node, filter=None):
"""Create an outline from a folder.
For each file or folder create a node with properties.
For folders recursively create children.
"""
defaults = NSUserDefaults.standardUserDefaults()
ignoredot = False
try:
ignoredot = bool(d... | 30,169 |
def update_hits_at_k(
hits_at_k_values: Dict[int, List[float]],
rank_of_positive_subject_based: int,
rank_of_positive_object_based: int
) -> None:
"""Update the Hits@K dictionary for two values."""
for k, values in hits_at_k_values.items():
if rank_of_positive_subject_based < k:
... | 30,170 |
def kill():
""" Kill / stop module execution """
global STOP
STOP = True
util.printit("\n\n\n\n\n\n\n") | 30,171 |
def start_monitor():
"""Define and start scheduled monitoring service."""
monitor_enabled = config_json[env]['MONITOR_ENABLED']
monitor_trigger_interval_s = int( config_json[env]['MONITOR_TRIGGER_INTERVAL_S'] )
# IF SCHEDULE IS ENABLED IN CONFIG:
if monitor_enabled == "1":
print("\nSpace W... | 30,172 |
def exit_missing_credentials():
"""
Exit the application with missing credentials error.
"""
logging.error('>> Please enter the credentials to the config.ini first!')
exit() | 30,173 |
def http_400_view(request):
"""Test view for 400"""
raise SuspiciousOperation | 30,174 |
def set_topics():
"""
Adds topics to repositories in the open-contracting-extensions organization.
- ocds-extension
- ocds-core-extension
- ocds-community-extension
- ocds-profile
- european-union
- public-private-partnerships
"""
format_string = 'https://raw.githubusercon... | 30,175 |
def test_logger(monkeypatch):
"""Test logger function returns valid loggers."""
_my_logger = tolog.logger("tolkein")
assert isinstance(_my_logger, logging.Logger)
assert _my_logger.name == "tolkein"
assert _my_logger.level == logging.INFO
monkeypatch.setenv("DEBUG", "true")
_debug_logger = t... | 30,176 |
async def ban(bon):
""" For .ban command, bans the replied/tagged person """
# Here laying the sanity check
chat = await bon.get_chat()
admin = chat.admin_rights
creator = chat.creator
# Well
if not (admin or creator):
return await bon.edit(NO_ADMIN)
user, reason = await get_us... | 30,177 |
def read_offset(rt_info):
"""
获取所有分区的offset
:param rt_info: rt的详细信息
:return: offset_msgs 和 offset_info
"""
rt_id = rt_info[RESULT_TABLE_ID]
task_config = get_task_base_conf_by_name(f"{HDFS}-table_{rt_id}")
if not task_config:
return {}
try:
partition_num = task_confi... | 30,178 |
def _CalculateElementMaxNCharge(mol,AtomicNum=6):
"""
#################################################################
**Internal used only**
Most negative charge on atom with atomic number equal to n
#################################################################
"""
Hmol=Chem.AddHs... | 30,179 |
def get_task_metrics_dir(
model="spatiotemporal_mean", submodel=None, gt_id="contest_tmp2m", horizon="34w",
target_dates=None
):
"""Returns the directory in which evaluation metrics for a given submodel
or model are stored
Args:
model: string model name
submodel: string submodel name ... | 30,180 |
def check_stability(lambda0, W, mu, tau, dt_max):
"""Check if the model is stable for given parameter estimates."""
N, _ = W.shape
model = NetworkPoisson(N=N, dt_max=dt_max)
model.lamb = lambda0
model.W = W
model.mu = mu
model.tau = tau
return model.check_stability(return_value=True) | 30,181 |
def pid2id(pid):
"""convert pid to slurm jobid"""
with open('/proc/%s/cgroup' % pid) as f:
for line in f:
m = re.search('.*slurm\/uid_.*\/job_(\d+)\/.*', line)
if m:
return m.group(1)
return None | 30,182 |
def get_develop_directory():
"""
Return the develop directory
"""
if platform.system() == "Windows":
return os.path.dirname(os.path.realpath(__file__)) + "\\qibullet"
else:
return os.path.dirname(os.path.realpath(__file__)) + "/qibullet" | 30,183 |
def multiaxis_scatterplot(xdata,
ydata,
*,
axes_loc,
xlabel='',
ylabel='',
title='',
num_cols=1,
num_rows=1,
... | 30,184 |
def log1p_mse_loss(estimate: torch.Tensor, target: torch.Tensor,
reduce: str = 'sum'):
"""
Computes the log1p-mse loss between `x` and `y` as defined in [1], eq. 4.
The `reduction` only affects the speaker dimension; the time dimension is
always reduced by a mean operation as in [1]. ... | 30,185 |
def quaternion_inverse(quaternion: np.ndarray) -> np.ndarray:
"""Return inverse of quaternion."""
return quaternion_conjugate(quaternion) / np.dot(quaternion, quaternion) | 30,186 |
def set_lockto_collid(id):
"""Lock to a collection.
"""
cherrypy.response.cookie['lockto'] = id.encode('utf8')
cherrypy.response.cookie['lockto']['path'] = '/'
cherrypy.response.cookie['lockto']['version'] = '1' | 30,187 |
def find_pgfortran(conf):
"""Find the PGI fortran compiler (will look in the environment variable 'FC')"""
fc = conf.find_program(["pgfortran", "pgf95", "pgf90"], var="FC")
conf.get_pgfortran_version(fc)
conf.env.FC_NAME = "PGFC" | 30,188 |
def _make_indexable(iterable):
"""Ensure iterable supports indexing or convert to an indexable variant.
Convert sparse matrices to csr and other non-indexable iterable to arrays.
Let `None` and indexable objects (e.g. pandas dataframes) pass unchanged.
Parameters
----------
iterable : {list, d... | 30,189 |
def _soft_validate_additional_properties(validator,
additional_properties_value,
instance,
schema):
"""This validator function is used for legacy v2 compatible mode in v2.1.
This will skip ... | 30,190 |
def read_document(collection, document_id):
"""Return the contents of the document containing document_id"""
print("Found a document with _id {}: {}".format(document_id, collection.find_one({"_id": document_id}))) | 30,191 |
def batchnorm_forward(x, gamma, beta, bn_param):
"""
Forward pass for batch normalization.
During training the sample mean and (uncorrected) sample variance are
computed from minibatch statistics and used to normalize the incoming data.
During training we also keep an exponentially decaying running ... | 30,192 |
def rectangles_of_one(base):
"""
Given a base array, generate list of all (point, rectangle) where the rectangle is all ones.
"""
stack = []
for p, slice in array_to_point_slices(base):
stack.append((p, slice))
while stack:
p, slice = stack.pop()
if all_ones(slice):
... | 30,193 |
def mkdir_p(path):
"""
Creates directory with parent directory as needed
(similar to 'mkdir -p ${path}').
Does not raise an error if directory exists
Inputs:
-------
path: type(str)
"""
try:
os.makedirs(path)
except OSError as err:
if err.errno == errno.EEXIST ... | 30,194 |
def chunking():
"""
transforms dataframe of full texts into a list of chunked texts of 2000 tokens each
"""
word_list = []
chunk_list = []
text_chunks = []
# comma separating every word in a book
for entry in range(len(df)):
word_list.append(df.text[entry].split())
# create a chunk of ... | 30,195 |
def generate_random_string():
"""Create a random string with 8 letters for users."""
letters = ascii_lowercase + digits
return ''.join(choice(letters) for i in range(8)) | 30,196 |
def contains_message(response, message):
"""
Inspired by django's self.assertRaisesMessage
Useful for confirming the response contains the provided message,
"""
if len(response.context['messages']) != 1:
return False
full_message = str(list(response.context['messages'])[0])
return... | 30,197 |
def definition():
"""To be used by UI."""
sql = f"""
SELECT c.course_id,
c.curriculum_id,
cs.course_session_id,
description + ' year ' +CAST(session as varchar(2)) as description,
CASE WHEN conf.course_id IS NULL THEN 0 ELSE 1 END as linked,
0 as changed
FROM (... | 30,198 |
def exec_psql_cmd(command, host, port, db="template1", tuples_only=True):
"""
Sets up execution environment and runs the HAWQ queries
"""
src_cmd = "export PGPORT={0} && source {1}".format(port, hawq_constants.hawq_greenplum_path_file)
if tuples_only:
cmd = src_cmd + " && psql -d {0} -c \\\\\\\"{1};\\\\\\... | 30,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.