id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
fff89a3b2259e5daa335 | def quitter():
pygame.quit()
quit() | |
fff8c59137b37b1a4ce9 | def main():
parser = argparse.ArgumentParser()
parser.add_argument("-r", "--regen", help="increase output verbosity",
action="store_true")
args = parser.parse_args()
if args.regen:
train_class, train_frames = read_dir('dataset/train/*.txt', ' ')
test_class, test_... | |
fff8fdfbb8314caa2b50 | def ensure_unicode(s):
if (is_py2 and isinstance(s, str)) or (is_py3 and isinstance(s, bytes)):
s = s.decode('utf-8', 'replace')
return s | |
fff907f85191d04c2bd9 | def load_net(path_load):
print('==> Loaded net..')
checkpoint = torch.load(path_load)
state_dict = checkpoint['net']
accs = checkpoint['accs']
start_epoch = checkpoint['epoch']
return state_dict, accs, start_epoch | |
fff91b17b5f3c625cc4c | def readNodes(fil):
a = fromfile(fil,sep=" ").reshape(-1,3)
x = Coords(a)
print(x.shape)
return x | |
fff91f56f4fb1e16de0b | def gen_random_string(n=24):
# RFC 3986 section 2.3. unreserved characters (no special escapes required)
char_set = string.ascii_letters + string.digits + "-._~"
return "".join(random.choices(char_set, k=n)) | |
fff926f23a817cfe9ad2 | def _request(self, function, params, service='shodan', method='get'):
# Add the API key parameter automatically
params['key'] = self.api_key
# Determine the base_url based on which service we're interacting with
base_url = {
'shodan': self.base_url,
'exploits': s... | |
fff928bf3df1b817da78 | def HasNegativeLobes(self):
return _MaxPlus.FilterKernel_HasNegativeLobes(self) | |
fff931f5f26a6d9e1c75 | def __init__(self, input_size, config):
super(EmbeddingLayer, self).__init__()
if config.emtraining:
self.embedding = nn.Sequential(OrderedDict([
('embedding', nn.Embedding(input_size, config.emsize)),
('dropout', nn.Dropout(config.dropout))
]))
... | |
fff951c7bf66fef6c802 | def process_batch(batch):
images = batch[0].cuda().contiguous()
labels = batch[1].cuda().contiguous()
return images, labels | |
fff954fcd822158e2416 | def create_frame(self, frame):
# Define labels
step1_lbl = tk.Label(frame, text = 'Step 1: Connect spectro & piezo')
genCtrl_lbl = tk.Label(frame, text = 'Step 2: Setup spectro & piezo')
pos_lbl = tk.Label(frame, text = 'Go to position (um):')
inte_lbl = tk.Labe... | |
fff95cd549df18c40e6f | def get_resultados(self,_consulta):
self._cursor.execute(_consulta)
resultados_ = self._cursor.fetchall()
return resultados_ | |
fff960a4b20650aa49d3 | def __call__(self, _handler):
self._exceptions.append(_handler)
return _handler | |
fff961eb5a9390f4298c | def clean2(points, tol=1e-5):
xlist = []
ylist = []
for point in points:
xi, yi = point
xlist.append(xi)
ylist.append(yi)
xorig = np.array(xlist)
yorig = np.array(ylist)
x = xorig
y = yorig
k = 1
ndel = 0
while k < len(x) - 1:
xnew = np.hstack((x[:... | |
fff9939ee747712d655d | def _set_bypass_lsp_extensive(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="bypass-lsp-extensive", rest_name="bypass-lsp-extensive", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_path... | |
fff9b9d5faa4d2d565dd | def notify(self, msg: str) -> None: | |
fff9be972551abd42455 | def post(self):
AccountMove = self.env['account.move'].with_context(default_type='entry')
for rec in self:
validation = rec._check_payment_approval()
if validation:
if rec.state not in ('draft', 'approved'):
raise UserError(_("Only a draft or a... | |
fff9de512f09387ab16f | def exists(self):
from aiida.common import NotExistent, MultipleObjectsError
try:
Code.get_from_string("{}@{}".format(self.label, self.computer.name))
return True
except MultipleObjectsError:
return True
except NotExistent:
return False | |
fff9fbe30b358ab234e4 | def time_to_string(times):
if _isIterable(times):
return [time_double_to_string(t, "yyyy-MM-dd HH:mm:ss.SSSSSS") for t in times]
else:
return time_double_to_string(times, "yyyy-MM-dd HH:mm:ss.SSSSSS") | |
fffa002ee9f93c879c16 | def log_to(__path: str) -> None: | |
fffa5b9bca45013fdf39 | def bounds(self):
raise NotImplementedError() | |
fffaae1d5e57140785cb | def __getattr__(self, name):
# Undefined attributes will look up the given parameter
# return self.get(item)
return getattr(self.__parameters, name) | |
fffabfe0140e460993f9 | def project(self) -> pulumi.Input[str]:
return pulumi.get(self, "project") | |
fffae11e12491370b5e7 | def rectangle_with_access(frame, name, top=0, right=0, bottom=0, left=0):
cv.rectangle(frame, (left, top), (right, bottom),
(0, 255, 0), 2)
y = top - 15 if top - 15 > 15 else top + 15
cv.putText(frame, name, (left, y), cv.FONT_HERSHEY_SIMPLEX,
0.75, (0, 255, 0), 2) | |
fffaef07fb695bed39fe | def associate(
self, z: np.ndarray, zpred: np.ndarray, H: np.ndarray, S: np.ndarray,
): # -> Tuple[*((np.ndarray,) * 5)]:
if self.do_asso:
# Associate
a = JCBB(z, zpred, S, self.alphas[0], self.alphas[1])
# Extract associated measurements
zinds = np.... | |
fffafcacdb5b60d027fe | def getNumFrames(self):
return self.__iteratreOver(self.keyMap["QFRAME"]) | |
fffafdae20435246e46a | def writeData(self):
if not RECORD_SIMULATION:
return
if not os.path.isfile("../../evalData/" + self.fileName + ".txt"):
self.runString = "#FoldNumber; isTraining; RunNumber; StepNumber; BlockId; px; py; kx1; \
ky1; kx2; ky2; ori; actx; acty; PredBlockId;... | |
fffb1ca7f54f4d29f8cb | def set_target_map(self, target_map, map_target=False):
if map_target:
self.set_target(target_map[self.target_str])
self._target_map = target_map | |
fffb74e70f504c4e635b | def setVolume(self, volume):
assert volume >= 0 and volume <= 255
self.__sendUserMessage(volume, self.IPC_SETVOLUME) | |
fffb954bcb2b5d6885f5 | def getLoadedFeatures():
return tuple(_local.get('feature-modules', {}).keys()) | |
fffb9aba9ee34fb5cf75 | def start_looking(self):
self.__send('action_video', 'start watching') | |
fffba38f76c1e869743a | def getField(self, dataset, field):
#we should really use meta_data instead in future!
if self.data[dataset].has_key(field):
return self.data[dataset][field]
else:
return None | |
fffba49b0d4f2b803cdd | def select_reports(page):
selected = []
session = create_connection()
try:
search_data = session.query(Report).order_by(
Report.id.desc()
).offset((page * 10) - 10).limit(10)
for data in search_data:
tmp = {
"id": data.id,
"date... | |
fffbae77b59621879cf2 | def loss_function_gradient(self):
def local_loss(weights):
E = 0.0
for ind, x_in in enumerate(self.loss_control_points):
E += self.loss_function_kernel(weights, x_in,
self.loss_indices[ind])
return E
retur... | |
fffbc63ac6dea235b22d | def magnetisation(field):
# TODO: Valid volume
return field.mean() / field.orientation.norm.mean() | |
fffbe9889b178829b10a | def members(self, members):
self._members = members | |
fffc03b26778e14335c0 | def variance(seq):
# TODO: implement this function (this one is a bit harder) | |
fffc3784613936d42c9c | def modulation_transfer_function(lsf):
# normalize
lsf_norm = []
lsf_areas = []
for item in lsf:
try:
lsf_norm.append(item / simps(item))
lsf_areas.append(simps(item))
# lsf_norm.append(item / max(item))
except:
pass
lsf_avg_area =... | |
fffc52d1a44c99ed4979 | def set_transform_orientation(self, context):
context.space_data.transform_orientation = SnapStore.transform_orientation | |
fffc65f751ad7d9fb7c7 | def wrapped_color_distance(image_tensor: Tensor) -> Tensor:
batch_size = image_tensor.size()[0]
k1, k2 = kernel_size
top_padding, bottom_padding = k1 // 2, (k1 - 1) // 2
left_padding, right_padding = k2 // 2, (k2 - 1) // 2
padded = functional.pad(image_tenso... | |
fffc710123344b6c8b66 | def cluster_hdbscan(
locdata,
min_cluster_size=5,
loc_properties=None,
allow_single_cluster=False,
**kwargs,
):
parameter = locals()
if len(locdata) == 0:
locdata_noise = LocData()
collection = LocData()
if len(locdata) < min_cluster_size:
locdata_noise = copy(l... | |
fffc74d4dd0d89abf7d6 | def main():
root = load_data()
counts = {}
print('Searching data tree with DFS ...')
dfs(root, counts)
print('Done searching data tree.')
save_as_df(counts) | |
fffc7a2f1d89ddab181b | def instantiate_weights(self):
with tf.name_scope("embedding"): # embedding matrix
# [vocab_size,embed_size] tf.random_uniform([self.vocab_size, self.embed_size],-1.0,1.0)
self.Embedding = tf.compat.v1.get_variable("Embedding", shape=[self.vocab_size, self.embed_size],
... | |
fffc839e31532213d7eb | def swiss_pairings():
ps = player_standings()
matches = get_matches()
unmatched = set((player[0] for player in ps))
next_round = []
# if odd number of participants, assign bye
if len(unmatched) % 2 == 1:
for i in range(len(ps)-1, -1, -1):
if None not in matches[ps[i... | |
fffc8aff8de1c26f0650 | def server_close(self):
pass | |
fffd07ee6e1df13c4d9c | def test_get_application_different_class(self):
app_helper = self.add_helper(ApplicationHelper(ApplicationWorker))
app = yield app_helper.get_application({}, cls=RunningCheckApplication)
self.assertIsInstance(app, RunningCheckApplication) | |
fffd0a1835ee4d12770c | def reset(self):
self._obs_buffer.clear()
obs = self.env.reset()
self._obs_buffer.append(obs)
return obs | |
fffd24dc139c64e8bc01 | def is_mirror(self) -> bool:
cmd = ["git", "config", "--local", "--get", "remote.origin.mirror"]
try:
out = self.run_cmd(cmd, required_real_result=True)
except subprocess.CalledProcessError:
return False
return out.startswith("true") | |
fffd2c1927a794902364 | def _doProfile(self, save_request=None):
# get user Profile
prof = self._getProfileFromUser()
# if saveProfile(), process user-modifyable fields
if save_request:
for field in ('displayName', 'teeShirtSize'):
if hasattr(save_request, field):
... | |
fffd51a6458e208567f4 | def send(mandant, recipientlist, subject, html, text): | |
fffd5fd83eb5d5e64787 | def get_knee_gradient(gradient: np.ndarray) -> int:
t = thresh.isodata(gradient)
diff = np.absolute(gradient - t)
knee = np.argmin(diff[1:-1]) + 1
return knee | |
fffd68e09864aaaa2e5b | def GetValueLeft(self) -> float:
... | |
fffd76efccc695fbf05f | def get_version():
return ".".join([str(i) for i in _VERSION]) | |
fffd7c88bd46562a13f1 | def test_value_init7(self):
with self.assertRaises(TypeError) as err:
s1 = Square(1, "98")
msg = "x must be an integer"
self.assertEqual(str(err.exception), msg) | |
fffd8ba7c7aea8478ce9 | def label(self) -> str:
return self._label | |
fffd8f566659116502fe | def filter_pandas_df(df, filters):
return df[(df[list(filters)] == pd.Series(filters)).all(axis=1)] | |
fffd9c735597fb3f3314 | def test_matches_specialEntries_reboot_false( self ):
pass | |
fffd9ee4c484898549de | def change_role(self, request, pk=None):
data = {
"role": request.data.get('role', None)
}
instance: Member = self.get_object()
serializer = self.get_serializer(instance, data=data, partial=True)
serializer.is_valid(raise_exception=True)
serializer.save()
... | |
fffdeca60227e6e041a1 | def g_grep(pattern, lines):
if type(pattern) in types.StringTypes: pattern = [pattern]
cpattern = [re.compile(p) for p in pattern]
for line in lines:
for p in cpattern:
if p.search(line):
yield line
break | |
fffe1274decfbf225b02 | def test_tournaments_id_get(self):
headers = {
'Accept': 'application/json',
}
response = self.client.open(
'/v0.0.1/tournaments/{id}'.format(id='id_example'),
method='GET',
headers=headers)
self.assert200(response,
... | |
fffe27457391a78c5dcb | def test_labware_highest_z(
decoy: Decoy, engine_client: ProtocolEngineClient, subject: Labware
) -> None:
decoy.when(
engine_client.state.geometry.get_labware_highest_z(labware_id="labware-id")
).then_return(42.0)
assert subject.highest_z == 42.0 | |
fffe352e1d08e22df869 | def test_parse_genome_data_2(self):
self.record = SeqRecord(seq=Seq("atgc"),
id="OPQ123.1",
annotations=self.annotation_dict,
description=self.description,
features=self.feature_list
... | |
fffe37cdcd8b59c6fa09 | def get_race_start_time(cls, current_race):
for key in settings.RACES.keys():
if key == current_race:
return settings.RACES[key]['start_time']
return None | |
fffe395a9272f86f2973 | def test_has_chrome_manifest():
assert langpack.test_langpack_manifest(ErrorBundle(),
None) is None | |
fffe5094f1aa794b8065 | def _check_device_code(self):
body = urllib.urlencode({'grant_type': 'device_code', 'device_code': self._store['device_code']})
return self._check_token(body) | |
fffe7727064a50db403c | def der(func, radius_array):
#array of derivative values
derivative1 = []
# initialize value
val = 0
derivative1 = derivative(func, radius_array)
derivative1 = np.array(derivative1)
return derivative1 | |
fffe79880fca8521064c | def add_to_cart(self):
WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable(ProductPageLocators.ADD_TO_CART))
button = self.driver.find_element(*ProductPageLocators.ADD_TO_CART)
button.click() | |
fffe8b514386fbb6d8ec | def plot_cluster_instances():
clustering_fp = "./results/clusterings_with_all.txt"
out_fp = "./results/all_summaries.csv"
ks = [3, 4, 5]
ns = [4, 5, 6, 7, 8, 9]
metadata_fp = "./data/matrix_files/metadata0.tsv"
terms_fp = "./data/matrix_files/terms0.csv"
results_folder = "./results/"
... | |
fffebe3a0a2b501d5a48 | def pick(ll):
return ll[int(random() * len(ll))] | |
fffeca5c82fee7d442d9 | def all_none(*args):
if len(args) == 1 and isinstance(args[0], Iterable):
args = args[0]
if all(x is None for x in args):
return True
return False | |
fffeccf50a7924a722ef | def chronological(t):
t_sort=[]
res=[]
for s in t:
tup=(s[4:],s[2:4],s[:2],s)
t_sort.append((tup))
t_sort.sort()
for element in t_sort:
res.append(element[3])
return res | |
fffee63f8dad89c34ffa | def download_file(url, dst, overwrite=False):
if os.path.exists(dst):
logger.info(f"File {dst} already exists.")
if overwrite:
logger.info(f"Removing {dst}...")
os.remove(dst)
else:
return
command = ["wget", "-O", dst, url]
process = subprocess.Pop... | |
fffee73c4b010910481c | def test_signup_post_complete_data_returns_json_with_new_user_info(testapp):
data = {
'first_name': FAKE.first_name(),
'last_name': FAKE.last_name(),
'email': FAKE.email(),
'password': FAKE.password()
}
res = testapp.post('/signup', data)
for prop in ['first_name', 'last_... | |
fffee742c757f7dd27b9 | def test_higher_level_step():
hiro_agent = HIRO(config)
ll_env = hiro_agent.lower_level_agent.environment
h_env = hiro_agent.higher_level_agent.environment
h_env.reset()
# HIRO.goal_transition = lambda x, y, z: y
state_before = hiro_agent.higher_level_state
assert hiro_agent.higher_level_nex... | |
fffeeb280047dda9c444 | def ReadEntries(self):
entries = {}
config = wx.Config.Get()
config.SetPath(CLUSTER_CONFIG)
step = config.GetFirstGroup()
while (step[0]):
entries[step[1]] = True
step = config.GetNextGroup(step[2])
config.SetPath('..')
return entries | |
ffff0d738b79c157632e | def remove_not_playing(self):
sheetdata = self.p4sheet.to_df("Players!A1:AG")
sheetdata = sheetdata.drop_duplicates(subset='Username')
sheetdata = sheetdata.loc[sheetdata['Username'] != ""]
sheetdata.set_index("Username", inplace=True)
not_playing = sheetdata.loc[sheetdata['Not ... | |
ffff185c4c08246b9555 | def db_connect(self):
self.connection = pymysql.connect(host=self.host,
user=self.user,
password=self.password,
db=self.database) | |
ffff1c09a3799c545176 | def OnMove(self, slot_id): | |
ffff459c9ed05b0df741 | def sample_params(self, sample_shape=[1]):
return self.params_dist(sample_shape) | |
ffff5ef5f405e513f6f3 | def move_child(self, source_index, dest_index):
if 0 <= source_index < len(self.children) and \
0 <= dest_index < len(self.children) and \
source_index != dest_index:
item = self.children[source_index]
if source_index < dest_index:
dest_index += 1
... | |
ffff7aab4efdd2a30715 | def process_log_data(spark, input_data, output_data):
# get filepath to log data file
log_data = input_data + 'log_data/*/*/*.json'
# read log data file
df = spark.read.json(log_data)
# filter by actions for song plays
df = df.filter(df.page == 'NextSong')
# create a temp... | |
ffff8d21a78e46be30c6 | def test_description(self):
self.assertEqual(self.team_1.description,
"Grey-skinned humanoids, usually 3–4 feet tall, hairless, with large heads.")
self.assertEqual(self.team_2.description, "Tall humanoid with a spade-shaped head.") | |
ffff997f3f0d3f15f38c | def isClickInsideBox(self,x,y):
bbox = self.bbox
if (bbox[0]<x<bbox[2] and bbox[1]<y<bbox[3]):
self.highlighted = True
return True
else: return False | |
ffffa14b77a18e2634b1 | def get_client_ip(request):
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
if x_forwarded_for:
ip = x_forwarded_for.split(",")[0]
else:
ip = request.META.get("REMOTE_ADDR")
return ip | |
ffffda33417b5a9b8ac5 | def error_rate(predictions, labels):
return 100.0 - (
100.0 *
numpy.sum(numpy.argmax(predictions, 1) == numpy.argmax(labels, 1)) /
predictions.shape[0]) | |
fffffee253c53718ced1 | def _save_auxiliary_files(self):
super(DifferentiableSearchMemoryNetwork, self)._save_auxiliary_files()
lsh_file = open("%s_lsh.pkl" % self.model_prefix, "wb")
sentence_index_file = open("%s_index.pkl" % self.model_prefix, "wb")
pickle.dump(self.lsh, lsh_file)
pickle.dump(self.in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.