id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
006ea5d10e5ff830c23d | def create_function_name_string(self):
# Creating the string for the line in which the function name is being specified
string_list = ["function:", str(self.function_name)]
# returning the assembled string
return ''.join(string_list) | |
006eba4331d76cd03547 | def _check_consistency(self):
headers = np.roll(self._make_header(self.packed), 1, axis=1).astype(
np.uint64)
footers = np.roll(self._make_footer(self.packed), -1, axis=1).astype(
np.uint64)
mask_hf = np.uint64(0b1110000000000000000000000000000111)
res = (self... | |
006ec01d8e847513fde1 | def run_script(self, filename, **kwargs):
return self._run_command(["-noprompt", "-run", "<<%s" % filename],
**kwargs) | |
006ef786d058668caf64 | def draw_bullet(self):
pygame.draw.rect(self.screen, self.colour, self.rect) | |
006f17034b45e76644b2 | def start(ctx, name):
ProjectCmd(ctx).start(name) | |
006f1712aa85ef86823e | def __get_status(self):
return self.__status | |
006f18225fa383f1dd48 | def encode(self) -> bytes:
return self.type.value.to_bytes(2, byteorder='big') + self.data | |
006f238ebdc4b94d6f77 | def put(self, data):
exist = self.check_if_entry_exists(data["url"])
if exist:
return False
else:
self.collection.insert_one(data)
return True | |
006f25f9dc8597624956 | def set_origin(event,x,y,flags,param):
global nb_clicks, marks, marks_coordinates, full
if event == cv2.EVENT_LBUTTONDBLCLK and (nb_clicks < len(marks_coordinates) or marks_coordinates ==[]):
if marks_coordinates == []:
user_input = pg.prompt(text="Prompt lat/long of the point (Google Map d... | |
006f292801d6959afe58 | def create_vlan_interface(node, vlan_id, ip_address):
with node.libs.vtysh.ConfigVlan(vlan_id) as ctx:
ctx.no_shutdown()
with node.libs.vtysh.ConfigInterfaceVlan(vlan_id) as ctx:
ctx.ip_address(ip_address)
ctx.no_shutdown() | |
006f3f20d3d9be033953 | def test_local_regressor_ols_intersite(monkeypatch):
from resistics.regression.local import LocalRegressor
from mocks import mock_window_selector
import numpy as np
# patch out the writeTF function
monkeypatch.setattr(LocalRegressor, "writeResult", mock_local_regressor_writeResult)
selector = ... | |
006f51d9e15621507b5f | def clean_text(text, nlp):
doc = nlp(text, parse=False, entity=False)
words = [token.text for token in doc if not token.pos_=='PUNCT']
return ' '.join(words) | |
006f54804655600fd2f2 | def add(self, element):
raise NotImplementedError | |
006f7ae3df150ca2c0aa | def test_write_pipeline_data_to_file_remove_contam_pipeline_version_option(self):
finder = data_finder.DataFinder(ini_file, self.pipeline_root)
tmpfile = "tmp.data_finder.write_pipeline_data_to_file.remove_contam.v0.1.1.out"
expected_file = os.path.join(
data_dir, "write_pipeline_dat... | |
006f93623b4ddc4a6ff8 | def set_embedding(self, label, model):
label_id = Variable(torch.LongTensor([GNN_IDS[label]]))
emb = model.init_const(label_id)
self.embedding = [emb] | |
006fe21c4c409214c822 | def UpdateReceivedShare(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | |
006fed4a8bd191ab1d03 | def get_account_level_dir_list(self):
return self._account_level_dir_list | |
006fff92fc1c484eb340 | async def test_no_discovery_info_climate(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
assert CLIMATE_DOMAIN not in hass.config.components
assert await async_setup_component(
hass,
CLIMATE_DOMAIN,
{CLIMATE_DOMAIN: {"platform": MODBUS_DOMAIN}},
)
await hass... | |
007008715d726f1041c3 | def is_hostmask(s):
return _hostmaskRe.match(s) is not None | |
007039c631ea93d92110 | def create_op(self, args=None, sslbls=None):
assert(sslbls is None), ("EmbeddedOpFactory objects should not be asked to create "
"operations with given `sslbls` (these are already fixed!)")
Embedded = _op.EmbeddedDenseOp if self.dense else _op.EmbeddedOp
op = se... | |
007045621fea386568d8 | def sampler(codes, prior):
fc2=prior.predict(codes)
dist=tfp.distributions.Categorical(logits=fc2)
sampled = dist.sample()
return sampled | |
00704ddc18856046bcd0 | def GetRequiredNumberOfOverlappingPixels(self) -> "unsigned long long":
return _itkMaskedFFTNormalizedCorrelationImageFilterPython.itkMaskedFFTNormalizedCorrelationImageFilterISS3IF3_GetRequiredNumberOfOverlappingPixels(self) | |
007056da02705edb24de | def construct_observation_matrix(x_train,x_val):
for observation in x_train: | |
00706831d6d2d635f3e2 | def voters(self, offset=0):
url = '/api/v4/answers/%d/voters' % self.id
params = {
'offset': offset,
'limit': 20
}
data = req.get(url, params)
return data if req._raw else parser.voters(data) | |
00706ad78e54252447a2 | def testShortKey(self):
pass | |
00707b00684be1642885 | def js_minify(request):
res = ''
files = []
url = request.GET.get('url')
if url:
minified_js = utils.minify_js_from_url(request, url)
if minified_js:
res = '%s\n%s' % (res, minified_js)
if request.GET.get('files'):
files = request.GET['files'].split(',')
... | |
00707d91602aa3616387 | def wraa(data, lg_woba, scale):
return ((data["woba"] - lg_woba) / scale) * data["pa"] | |
007094f0c72f96246158 | def __init__(self, n: int, weighting: float = 0.9) -> None:
assert isinstance(n, int) and n >= 1
weighting = float(weighting)
assert weighting > 0 and weighting <= 1
self.n = n
self.weighting = weighting
self.timestep = 0
self.A = np.zeros([n, n])
self._P... | |
0070fd03fe6fa459c7aa | def min(self, data):
return data \
.map(lambda (key, value): (build_key(self.combo, key), value)) \
.reduceByKey(lambda a, b: a if a < b else b) | |
0071108604133acb69df | def GetPID(self):
return 0 | |
0071244f6a61ff7e925d | def draw_flower():
turtle.setheading(0)
draw_petal()
turtle.setheading(90)
draw_petal()
turtle.setheading(180)
draw_petal()
turtle.setheading(270)
draw_petal()
turtle.setheading(270)
turtle.forward(250)
return | |
00714b92e1ed64f6fc22 | def doc_stats(document):
data = re.sub('\.*\n{2,}', '. ', document)
data = re.sub('\n', ' ', data)
data = re.sub('\s+', ' ', data)
data.strip()
processed_doc = nlp(data)
#ignore_pos = ['PUNCT', 'SYM', 'X']
word_list = []
num_words = 0
dist_words = set... | |
0071762e85e1753b08eb | def set_error_message(self, message):
self.error_message = message
self.sql_manager.execution_update(self.id, error_message=self.error_message) | |
0071817472a4d5d6d251 | def test_unassign_referral_by_admin_user(self, _):
user = factories.UserFactory(is_staff=True)
referral = factories.ReferralFactory(state=models.ReferralState.ASSIGNED)
assignment = factories.ReferralAssignmentFactory(
referral=referral, unit=referral.topic.unit
)
re... | |
00718cd001a00b57ca02 | def levenshteinDistance(s1, s2):
# pylint: disable=invalid-name
# special cities and countries
if len(s1) > len(s2):
s1, s2 = s2, s1
distances = range(len(s1) + 1)
for i2, c2 in enumerate(s2):
distances_ = [i2 + 1]
for i1, c1 in enumerate(s1):
if c1 == c2:
... | |
00718d388a2a09a5513c | def testFullWordTruncation(self):
tf = TitleFilter(truncateAfter=r"virus")
# Note that the truncation code will chop off the first part of the
# title (the title ID).
self.assertEqual(
TitleFilter.DEFAULT_ACCEPT,
tf.accept("gi|400684|gb|AY421767.1| herpes virus 1"... | |
0071a87775c963b42737 | def __call__(
self,
session: requests.Session,
response: requests.Response,
request: requests.Request,
**kwargs: Any,
) -> requests.Request | None: # pragma: no cover | |
0071af727a526aea19ca | def size(self):
return self._size | |
0071e6fdb6d9c49d2553 | def render_font(self,font,size,msg,color=(255,255,255)):
selected_font = pg.font.Font(setup.FONTS[font],size)
return selected_font.render(msg,1,color) | |
0071ebb0586cce2d5a78 | def remove(self, node_id):
self.queue.pop(node_id)
heapq.heapify(self.queue) | |
00720bcb10de7164c6b5 | def tpc_prepare(self): # real signature unknown; restored from __doc__
pass | |
00720f9999c1b5c807c9 | def sense(self, robot):
row, col = robot.row, robot.col
robots = []
for i in range(-self.sensor_radius, self.sensor_radius + 1):
for j in range(-self.sensor_radius, self.sensor_radius + 1):
if i == 0 and j == 0:
continue
new_row,... | |
00723d909951882ad98a | def createKey(self, key, *args):
self.toManager.put([SM_COMMANDS.CREATE_KEY, [[key] + list(args)]])
message = self.fromManager.recv()
if isinstance(message, StudentAPIKeyError):
raise message
return | |
007260007dfdac9cca71 | def process_weather(forecast_file):
pass | |
00726b14bfa5c576f19d | def voxel_size(self):
x = self.header.cella.x / self.header.mx
y = self.header.cella.y / self.header.my
z = self.header.cella.z / self.header.mz
sizes = np.rec.array((x, y, z), VOXEL_SIZE_DTYPE)
sizes.flags.writeable = False
return sizes | |
00727538029912aa94e5 | def signed_url(self, url):
if not url or url == '':
return
parsed = urlparse.urlparse(url)
urlToSign = parsed.path + "?" + parsed.query
decodedKey = base64.urlsafe_b64decode(self.privateKey)
signature = hmac.new(decodedKey, urlToSign, hashlib.sha1)
encodedSign... | |
007277b80048ec40fa43 | def get_rule_kwargs_interactive(self, pnames, listpnames):
print "\n\tgetting parameters (leave any blank for defaults)"
params = {}
for pname in pnames:
val = raw_input("\t\t{}: ".format(pname))
if val:
try:
val = self.lookup[val]
... | |
0072852c3bd602014a46 | def multi_output_response(self) -> global___MultiOutputResponse: | |
00729632d8c06ccdfe48 | def looks_like_issubclass(obj, classname):
t = obj
if t.__name__ == classname:
return True
for klass in t.__mro__:
if klass.__name__ == classname:
return True
return False | |
0072d2231f0cdc95a944 | def _logRegister(self):
#self.logger.info('logRegister started')
self._thzProtocol.logRegister(self._logRegisterId)
self._params['logRegister']['item'][0]('done', source = 'thzRefresh')
#self.logger.info('logRegister completed')
#def _setRegister(self):
"""requests writing t... | |
0072fae8aa403f9f20ba | def _process_kwargs(self, kwdict):
for key in kwdict:
if key in self.settings:
if type(kwdict[key]) != type(self.settings[key]):
raise ValueError, 'Parameter %s in settings has to be ' \
' of type %s. Got %s instead'%(
key,
type(self.settings[key]),
type(kwdict[k... | |
007306ee5e98dc7288fa | def tick(self):
self.time += 1 | |
00731a34bdabd4996ad9 | def get_messages(self):
messages = self.input_queue.get_messages()
self.logger.debug('Got {0} messages'.format(len(messages)))
return messages | |
00732011bda897d9ac7f | def create_end_time(self):
new_minutes = datetime.timedelta(minutes=4)
new_end_time = self.start_time + new_minutes
self.end_time = new_end_time | |
00733b65ab4333956eb4 | def process_map(fn, *iterables, **tqdm_kwargs):
from concurrent.futures import ProcessPoolExecutor
if iterables and "chunksize" not in tqdm_kwargs:
# default `chunksize=1` has poor performance for large iterables
# (most time spent dispatching items to workers).
longest_iterable_len = ma... | |
00733eafe72b25c00afe | def required_parts(self):
parts = []
for item in self.bom_items:
parts.append(item.sub_part)
return parts | |
007344c289ef44ff738e | def randn(shape=(), dtype=float, scale=1.0, loc=0.0,
num_threads=None, seed=None, dist='normal'):
if seed is not None:
seed_rand(seed)
if isinstance(shape, Integral):
d = shape
shape = (shape,)
else:
d = prod(shape)
if num_threads is None:
# only multi... | |
00735d13b6a5dae74c17 | def run():
# Create the evaluation directory if it doesn't exist.
prediction_dir = FLAGS.prediction_dir
if not tf.gfile.IsDirectory(prediction_dir):
tf.logging.info("Creating prediction directory: %s", prediction_dir)
tf.gfile.MakeDirs(prediction_dir)
g = tf.Graph()
with g.as_default():
# Bui... | |
007392c83e033b1db988 | def smooth(self):
if hasattr(self,'smoothing') and self.smoothing is not None:
self.rho = ndimage.gaussian_filter(self.rho,sigma=self.smoothing) | |
00739726340adfbdba5a | def list(self, max=100, app=None):
url = '/'.join((self.url, 'lib', 'get_jobs.php'))
params = dict(max=max)
url = '?'.join((url, urlencode(params)))
resp, content = self.http.request(url, 'GET')
return load_json(content) | |
00739c0f27449a4eb1dd | def testWalkHSPExactMatchWithGap(self):
read = Read("id", "ACGT")
hsp = HSP(
33,
readStart=0,
readEnd=4,
readStartInSubject=0,
readEndInSubject=4,
subjectStart=0,
subjectEnd=4,
readMatchedSequence="A-GT",
... | |
00739eb985291bdb24d9 | def noop_callback(loop, delay):
loop.call_later(delay, noop_callback, loop, delay) | |
0073acc08aaa1286d0b5 | def get_large_audio_transcription(r, path):
file1 = open("write.txt","w+")
# open the audio file using pydub
sound = AudioSegment.from_wav(path)
# split audio sound where silence is 500 miliseconds or more into chunks
chunks = split_on_silence(sound,
min_silence_len = 500,
s... | |
0073f73d06bd76f46767 | def getNewId(rand_f=randrange):
NUM_DIGITS = 12
return ''.join(map(str, [rand_f(10) for i in range(NUM_DIGITS)])) | |
0073fc81b161ac9fdd95 | def test_cost_living():
cost_living_df = cost_living()
assert cost_living_df.shape[0] > 0 | |
007406f61e91b8cb68e7 | def rodVectorToAngle(rvec):
angle = np.linalg.norm(rvec)
normal_rvec = rvec / angle
return angle, normal_rvec | |
00746438936dbf73b688 | def sort(self):
for i in range(len(self.chromosomes)-1):
max = i
for j in range(i+1, len(self.chromosomes)):
if self.chromosomes[max].fitness < self.chromosomes[j].fitness:
max = j
temp = self.chromosomes[i]
self.chromosomes[i] ... | |
00748628f815c68055b4 | def network_interfaces(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['VirtualMachineCloneCustomizeNetworkInterfaceArgs']]]]:
return pulumi.get(self, "network_interfaces") | |
00748d7e3c75eb27ba16 | def _get_ids(tokens, tokenizer, max_seq_length):
token_ids = tokenizer.convert_tokens_to_ids(tokens)
input_ids = token_ids + [0] * (max_seq_length - len(token_ids))
return input_ids | |
00750a87ab3a95c91d7e | def _read_data(self, count):
# Build a read request frame.
frame = bytearray(count+1)
# Add the SPI data read signal byte, but LSB'ify it
frame[0] = reverse_bit(_SPI_DATAREAD)
time.sleep(0.005) # required
frame = self._spi.xfer(frame) #pylint: disable=no-member
... | |
00752883a71ce81c25d9 | def train(config_data, logger):
if os.path.exists(os.path.join(config_data['common_dir'], config_data['dataset']['file_name'])) is not True:
logger.error("Dataset is not found")
else:
trainer = ModelTrainer(logger)
trainer.prepare_data_set(
config_data['common_dir'],
... | |
00753540abad8f142dba | def add(self, document_dictionary):
for id, text in document_dictionary.items():
# check if document is already in index, skip it
if id in self.raw_text:
#raise LookupError("Document already in index - no need to add it!")
continue
self.raw_te... | |
0075383b7c79d703e4b8 | def _restore_vars(v_list, t_list):
ops = []
for v, t in zip(v_list, t_list):
ops.append(v.assign(t))
return ops | |
00753874adacdb9bd84a | def stage_changes(branch):
run('git checkout develop && git merge --no-ff ' + branch)
run('python manage.py migrate footbagmoves') | |
007539b0a1a916409e20 | def k_fold_random_split(y, tx, k, seed=1):
# Create space for k subsets of the initial dataset
subsets_y = [None] * k
subsets_tx = [None] * k
# Rearrange the indices of the initial dataset
np.random.seed(seed)
indices = np.random.permutation(len(y))
# Calculate the number of rows per subse... | |
00754f33edd57d26e98c | def test_clean_database(self):
db_conflicts()
self.assertQuerysetEqual(Conflict.objects.all(), Conflict.objects.none()) | |
00756159a50516b78a18 | def load_default_session(self) -> TracerSession: | |
0075652ae658e96e6322 | def antenna_insertion_loss(self, antenna_insertion_loss):
self._antenna_insertion_loss = antenna_insertion_loss | |
00756e6b915fb5bf301e | def __init__(self, ensemble_size, data_path, vocabulary_path, labels_path, stop_words_path, pre_train_path=None,
k=3):
self.model = None
self.dataset = []
self.subsets = []
self.classifiers = []
self.ensemble_size = ensemble_size
self.data_path = d... | |
007571fa2c4c5a277196 | def MatrixMax(input_matrix):
return np.max(input_matrix) | |
0075bfe0aa18eee16b41 | def test__plot_pr_curve_iou_mean(od_detection_eval, basic_ax):
_plot_pr_curve_iou_mean(basic_ax, od_detection_eval.coco_eval["bbox"]) | |
0075c464cea46d387855 | def test_move_to_opposite_side_slower_going_away_from_banana(self):
if self.tb.training == 2.3:
# timing not great right out of the starting gate...
messenger.send('x_axis', [0])
for i in range(30):
taskMgr.step()
# first check away from banana dir... | |
0076179672bb51a8e3a6 | def num_non_bouncy(x):
return num_increasing(x) + num_decreasing(x) - 9 | |
00767efe60684b1a897e | def url(url, method):
from werkzeug.exceptions import MethodNotAllowed, NotFound
try:
rule, arguments = current_app.url_map.bind('localhost')\
.match(url, method=method, return_rule=True)
_print_url_rules(
('Rule', 'Endpoint', 'View', 'Arguments', 'Options'),
... | |
007681e052fff3df0791 | def getTimeDelta(timestr, log):
rv = None
try:
time_parts = tuple(int(x[0:-1]) for x in re.search("^(\d+w)?\s*(\d+d)?\s*(\d+h)?\s*(\d+m)?$", timestr.strip())
.groups(default="0t"))
rv = timedelta(**dict(zip(("weeks", "days", "hours", "minutes"), time_parts)))
excep... | |
00769293ad9097ddc82a | def check_sublist(list_one, list_two):
slice_length = len(list_one)
if slice_length == 0:
return True
elif slice_length > len(list_two):
return False
else:
slices_of_two = [list_two[i:i+slice_length]
for i
in range(len(list_two)-... | |
0076963de6d06417d9c0 | def _energy_func(self, x):
return x | |
0076d1d90fe0f670038d | def file_copy(self, src, dest=None, file_system="bootflash:"):
if not self.file_copy_remote_exists(src, dest, file_system):
dest = dest or os.path.basename(src)
try:
file_copy = self.native.file_copy(
src, dest, file_system=file_system
... | |
0076d56ff596758bc445 | def notify_follow(e):
# Retrieve info
target = e['target']
if target['screen_name'] != c['original_name']:
return
source = e['source']
created_at = e['created_at']
# Format
source_user = cycle_color(source['name']) + \
color_func(c['NOTIFICATION']['source_nick'])(
' @... | |
0076ed7a0ce4e8895a25 | def get_current_version(self) -> str:
return firmware_version | |
0077084bbc37263e2485 | def folderReport(self, message_list, name=""):
if not len(message_list):
# self.logger.debug("Empty message not processed")
return
message_list = Gmail.email_filter(message_list)
# CSV Report
fout_path = Gmail.makePath(name + "_report.csv", Gmail.output_directory)... | |
007730cf9ac1bf6f9c3b | def __init__(self, g: Graph):
self.g = g
self.visited = [False] * self.g.get_size()
self.vertex_group = [0] * self.g.get_size() | |
00773d1acc35d9f75e56 | def digit_count(digits):
zero_count = 0
even_count = 0
odd_count = 0
for i in digits:
if i == 0:
zero_count += 1
elif i % 2 == 0:
even_count += 1
else:
odd_count += 1
return zero_count, even_count, odd_count | |
00774f63c0742d5d32b3 | def create_freq(words_list: list) -> dict:
freq = {}
for w in words_list:
if w in freq:
freq[w] += 1
else:
freq[w] = 1
return freq | |
00775e66308796bafadb | def as_xml(self):
return self.tostring() | |
00776a592b044e10512f | def _set_enable_relay_agent(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enable-relay-agent", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, nam... | |
0077723a8f6c4a0183e6 | def _get_filename_from_url(url: str) -> str:
return url.split('/')[-1] | |
0077b37ef0d03cf01544 | def _get_close(self, embedding, idtype="node"):
distances = cosine_distances([embedding], self.graph_embedding[idtype])[0]
similarities = 1/(1+distances)
ids = numpy.arange(len(similarities))
max_sim = similarities.max()
if max_sim < self.min_score:
return None
... | |
0077ca7a41f29f0ade22 | def register():
ui = request.form['user_id']
pw = request.form['password']
try:
bc.register_user(ui, pw)
except UserAlreadyExistsError:
return 'UserAlreadyRegistered'
except ValueError:
return 'InvalidKey'
except UserNotExistError:
return 'UserNotExist'
... | |
0077e21d3449503ea12b | def generate_average(names, output):
global measure
# Calcium/pH mode
meanname = ''
if measure == 'Calcium':
meanname = 'Mean Calcium (nM)'
elif measure == 'pH':
meanname = 'Mean pH'
# Drop empty columns and determine shortest experiment
means = pd.DataFrame()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.