id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
0009733b0c9e80410b62 | def test_sparse(self):
dense_arr = self.ds_arr
sc = StandardScaler()
dense_scaled = sc.fit_transform(dense_arr)
dense_mean = sc.mean_.collect()
dense_var = sc.var_.collect()
sparse_scaled = sc.fit_transform(self.sparse_arr)
sparse_mean = sc.mean_.collect()
... | |
0009afe74a0b0b92b6bb | def touch(fname):
try:
os.utime(fname, None)
except OSError:
open(fname, 'a').close() | |
0009ba2d7266b2ded550 | def wsp(node):
mark = len(output)
w(node)
if mark != len(output):
w(" ") | |
0009c727bca764e2ca2a | def to_representation(self, instance):
ret = super().to_representation(instance)
if instance.geom:
instance.geom.transform(4326)
ret['geom'] = json.loads(instance.geom.json)
# respond with the 'description' field for the following items, which are otherwise
# re... | |
0009cb7bea66d7d6985e | def count(self):
return len(self.__data.itemList) | |
0009d07afa0474c9efda | def argmax(seq):
return argsort(seq)[-1] | |
0009d46e606eb3e109d6 | def get_position_decimal_degrees(pos_serie):
pos = np.vectorize(utils.decmin_to_decdeg)(pos_serie)
return pos | |
0009e095a8fcfff3401a | def __make_entities_list(self):
self.entities.append(self.mcgyver)
self.entities.append(self.guardian)
for i in self.maze.item_list:
self.entities.append(i) | |
0009ec90b49420acc419 | def dict_count_to_freq(d):
tot_d = sum(d.values())
for val in d:
d[val] /= float(tot_d)
return d | |
000a03ac8564e85bc647 | def initialize(self):
self._dist_std_dev = float(self.parameter("dist_std", default=0.5))
logger.info("Pinger Noise standard deviation: %.4f"% self._dist_std_dev) | |
000a5612cb0f91868524 | def obsdata_2_df(obs):
sour=obs.source
df = pd.DataFrame(data=obs.data)
df['fmjd'] = df['time']/24.
df['mjd'] = obs.mjd + df['fmjd']
telescopes = list(zip(df['t1'],df['t2']))
#reorder stations alphabetically
df['is_alphabetic'] = df['t1']<df['t2']
df_alphabetic = df[df.is_alphabetic==Tru... | |
000a827f263bc7ee9588 | def mergeSum(self, x_stats):
pass | |
000ab8ed9b232bbd5e8f | def test_fresh(self):
# setup mock locked_shelf:
fresh = build_response()
mock_shelf = mock_shelfcache(CacheResult(data=fresh,
expired=False))
# setup mock requests.get method
mock_getter = build_getter(fresh)
# DUT:
... | |
000ad66411f7bf835f6e | def set_labels(ax, label_value, label_axis):
if label_axis == 'x':
ax.set_xticks(np.arange(len(label_value)))
axis = ax.get_xticklabels()
else:
ax.set_yticks(np.arange(len(label_value)) + 1)
axis = ax.get_yticklabels()
labels = [items.get_text() for items in axis]
count =... | |
000ad7ca635b47d1ae67 | async def run_commands(self, commands, iteration):
for command in commands:
if await command.should_handle(iteration):
if self.debug:
print(f"Handling: {command.__class__}")
await command.handle(iteration) | |
000ae1b65186e0cc743a | def group2(lst, key=lambda v: v[0]):
res = {}
for v in lst:
res.setdefault(key(v), []).append(v)
return res.items() | |
000af907ce9d71572796 | def get_data(fn):
data = []
with open(fn, 'r') as file:
csv_reader = reader(file)
for row in csv_reader:
if not row:
continue
data.append(row)
return data | |
000b097814fbed4507ec | def saveStateTrajectoryCSV(stateTraj,f):
state0 = dict((k,v[0]) for (k,v) in stateTraj.items())
state0['iter'] = 0
saveStateHeaderCSV(state0,f)
if len(list(stateTraj.items()))==0:
return
length = len(list(stateTraj.values())[0])
for i in range(length):
state0['iter'] = i
... | |
000b1271c5e1a604bd89 | def sample_(self) -> Sample:
self._ensure_fitted()
return self._crossfit.sample_ | |
000b1a95b227891b68c4 | def cos_vec(u,v):
# Calculate dot product
u_dot_v = lambda u,v: (u[0]*v[0]+u[1]*v[1]+u[2]*v[2])
# Calculate mid point between to atoms
u_mid_v = lambda u,v: [(x+y)/2 for (x,y) in zip(u,v)]
# find the length of a vector
u_len = lambda u: math.sqrt(u[0]**2 + u[1]**2 + u[2]**2)
# Move vector to... | |
000b619c045c51fe08fe | def test_action_create_from_md(correctly_formatted_md_action):
soup = BeautifulSoup(correctly_formatted_md_action, "html.parser")
action = Action.create_from_md(soup.table)
_test_action(action) | |
000b656155fe0b954b68 | def test_different_product_models(self):
self.cart.add(self.deer, 10.00, 1)
self.cart.add(self.ticket, 25.00, 1)
self.session.save()
response = self.show_response()
self.assertContains(response, '1 deer for $10.0')
self.assertContains(response, '1 Clint Mansell for $25.... | |
000b696e90f7fb4e2511 | def send_file(self, file_name: str) -> None:
with open(file_name, 'rb') as f:
message = {'type': 'DATA', 'data': None}
read_size = 16 * 60
f.seek(self.offset)
while True:
if self.state == AWAIT_HANDSHAKE:
self.offset = f.tell()... | |
000b69a0be200227339a | def _draw_filtered_spectrum(self):
# Any smoothing?
# [TODO]
# Draw it on the top axes.
self._axes[0].lines[1].set_data(self._dispersion, self._filtered_flux)
# And draw it on it's own in the middle axis.
self._axes[1].lines[0].set_data(self._dispersion, self._filtered_... | |
000b7d816989e07763c5 | def name_is_special(method_name):
return method_name.startswith('__') and method_name.endswith('__') | |
000bac521547345f166c | def test_db_api(self):
self.assertTrue(app.config['lib'] is not None,
'No connection with the database api') | |
000bc39d924f5bb9c723 | def makeBigHex():
makeHex()
turtle.forward(50)
turtle.right(60)
makeHex()
turtle.forward(50)
turtle.right(60)
makeHex()
turtle.forward(50)
turtle.right(60)
makeHex()
turtle.forward(50)
turtle.right(60)
makeHex()
turtle.forward(50)
turtle.right... | |
000bc522cc2092c571dc | def get(self, filename: str, description: str = ""):
response = self.http.request(
method=HttpMethodEnum.GET,
endpoint=f'{self.endpoint}/{filename}',
payload={
'name': filename,
'description': description
}
... | |
000bc5edc813c7168482 | def copySaveGame ( self, widget, device):
if self.array == []:
self.noMoreSG()
return
if device == 'local':
com = "cp -pr \"%s\" \"%s\"" %(self.array[self.index][0], self.mssave)
else:
com = "cp -pr \"%s\" \"%s\"" %(self.array[self.index][0], self.tSave)
if os.path.isdir(self.mssave):
## no n... | |
000c04b443f4e67f9f5f | def allow_admin_create_user_only(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "allow_admin_create_user_only") | |
000c0ab24348cbcf2e6a | def __init__(self, n_nodes, n_edges):
# key = node ID, value = Node-object
self.nodes = dict()
# call the create network method of the respective sub-class
self.__create_network__(n_nodes, n_edges) | |
000c24113ce70f8cc116 | def put(self):
request = transforms.loads(self.request.get('request'))
if not self.assert_xsrf_token_or_fail(
request, 'import-course', {'key': None}):
return
if not CourseOutlineRights.can_edit(self):
transforms.send_json_response(self, 401, 'Access den... | |
000c524691769d1754c7 | def any_sample_election():
return any_sample_of(SAMPLE_ELECTIONS) | |
000c5f5ae2015233b8a1 | def get_index_record(self) -> Optional[Dataset]:
return self.collection.index_.datasets.get(self.id_) | |
000c904f0daf5f184877 | def showme(self):
self.window.showme() | |
000caade3e601cbe9205 | def create_task(self, **kwargs):
new_task = objects.Task(statemgr=self.state_manager, **kwargs)
self.state_manager.post_task(new_task)
return new_task | |
000cb03c9567fc95a646 | def run(self, player1, player2):
raise NotImplementedError("Not implemented in this subclass. See run_turn()") | |
000cc47d66211017d596 | def new_issue(self, issue):
pass | |
000cc737af9defcd2701 | def __auth(self) -> HTTPBasicAuth:
if self._username is None or self._password is None:
return None
return HTTPBasicAuth(self._username, self._password) | |
000d1642e450c2a16aa1 | def save(file, grid: Grid) -> None:
cell_ndcount = np.array(grid.cell_ndcount)
origin = np.array(grid.origin)
cell_sides_length = np.array(grid.cell_sides_length)
np.savez(
file,
cell_ndcount=cell_ndcount,
origin=origin,
cell_sides_length=cell_sides_length) | |
000d49d75f00ccce6082 | def chunked_md5sum(filename, blocksize=8388608):
hashobj = md5()
with open(filename, "rb") as f:
for block in iter(lambda: f.read(blocksize), b""):
hashobj.update(block)
return hashobj.hexdigest() | |
000d530665dd30ddf491 | def generate_dataflow(self, pix, kernel_size, stride, padding_size):
# Add padding to the input. Get input dimensions.
rows = pix.shape[0]
columns = pix.shape[1]
pix = Convflowgen.add_margin(pix, padding_size, padding_size)
# Rows and columns are processed in parallel.
... | |
000d53744593c2ef093f | def rotate(self, pc, cfg):
# Not checking for height dimension as preserving absolute height dimension improves some models.
if np.abs(pc[:, :2].mean()) > 1e-2:
warnings.warn(
f"It is recommended to recenter the pointcloud before calling rotate."
)
method... | |
000d5ccd7b67cfac7c33 | def linear_merge(list1, list2):
return linear_merge_acc(list1, list2, []) | |
000d64f9807d1c67e506 | def action_reward(self, state, action, next_state):
to_home = tf.equal(next_state, TARGET)
return tf.case({
to_home: lambda: 10.0,
},
default = lambda: -1.0,
exclusive=True) | |
000d65d6cbef178f2c58 | def timer(cls, *args, **kwargs): # pylint: disable=unused-argument
return Timer() | |
000d8d354faf192d3778 | def monotonic():
ts = timespec()
if clock_gettime(CLOCK_MONOTONIC, ctypes.pointer(ts)):
errno = ctypes.get_errno()
raise OSError(errno, os.strerror(errno))
return ts.tv_sec + ts.tv_nsec / 1.0e9 | |
000d99bacb0ad3aa8b6c | def get_batch_size(self):
return 0 | |
000dc4a192a3ce3d76e6 | def to_header(self):
if self.present and not self.filled:
return "@{}".format(self.name)
return super().to_header() | |
000dd453b6866892b858 | def class_dict(cl):
dic = {}
for attr_name, attr in cl.__dict__.items():
comp = getattr(cl, attr_name)
if isinstance(comp, (int, float, str,
dict, tuple, list, np.ndarray)):
continue
if comp is None:
dic[attr_name] = 'Not Defined'
else:
... | |
000e19165ecb4bb1a8ac | def unregister(self, *args, **kwargs):
... | |
000e1df7525cff721cce | def to_matrix(self) -> np.ndarray:
return np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, np.exp(1j * self.angle)]], dtype="complex") | |
000e2589f11842d35c15 | def _set(self, value):
self._value = value | |
000e34ec805574aeb2eb | def delete_directory(path):
if Local.dir_exists(path):
shutil.rmtree(path)
log.debug("Deleted local directory %s", path) | |
000e606e93e52fe43967 | def __parse_request(self):
parameters = {}
splitted_path = self.path.split("?")
parameters["path"] = splitted_path[0]
params = re.findall(r"[\w']+", ' '.join(map(str, splitted_path[1:])))
if len(params) % 2:
params.pop()
if len(params) > 1:
for i i... | |
000e774a96f3157e3dd7 | def read_all():
print(len(APPLIANCES))
return {"appliances" : list(appliance.__dict__ for appliance in APPLIANCES)} | |
000e8b4ea08b13c6e67f | def related_groups(tile_i):
return _in_groups[tile_i] | |
000eb54b581287229969 | def __neg__(self):
from .numpyx_core_api import var
return var(self.self_var, op="Neg") | |
000ebc09699b40b4bc4b | def create_dirs():
raw_data_dir = os.path.join(project_dir, 'data', 'raw')
save_dir = os.path.join(raw_data_dir, time.strftime("%d-%m-%Y"))
os.makedirs(save_dir, exist_ok=True)
return save_dir | |
000ebed7ecf6ccf0f5d6 | def tick(self):
raise NotImplementedError | |
000ec1e6ef84a10267b4 | async def create_api_async(
self,
request: cloud_api20160714_models.CreateApiRequest,
) -> cloud_api20160714_models.CreateApiResponse:
runtime = util_models.RuntimeOptions()
return await self.create_api_with_options_async(request, runtime) | |
000ef357f9fd3e359aca | def blur_bilateral_filter(self):
self._update_img(self.Bilateral.apply(self.tmp_image)) | |
000ef57b9c44d5523f08 | def bloquear(self):
self._bloqueado = True | |
000f189d412d3aa5f522 | def __init__(self, can_channel, motor_id):
self.bus = can.interface.Bus(
channel=can_channel, bustype='socketcan_ctypes')
self.motor_id = motor_id
self.speed = 0
self.now_speed = 0
self.alive = False
self.weight = 0
self.ser = serial.Serial('/dev/ttyUS... | |
000f33869cce5bc81497 | def processor_usage(self):
try:
raw_data = self.__exec_sys_command("top", "-bn1")
line = str(raw_data.stdout, 'utf-8').split('\n', 3)[2]
cpu = re.search('%Cpu\(s\): {1,}(\S+).us, {1,}(\S+).sy, {1,}(\S+).ni', line)
return tuple([float(cpu.group(i).replace(',', '.')... | |
000f4a04739a0fe49c8f | def add_callback(self, callback=None, index=None, run_now=False,
with_ctrlvars=True, **kw):
if callable(callback):
if index is None:
index = 1
if len(self.callbacks) > 0:
index = 1 + max(self.callbacks.keys())
self.... | |
000f4f3eb90588cb7c84 | def show_text2(self, txt, font=None):
if (type(txt) is not list) or (len(txt)==0) or (type(txt[0]) is not tuple):
raise Exception("a list of tuple is expected")
imgs = []
im = divoom_image.draw_multiple_to_image(txt, font)
slices = horizontal_slices(im)
for i, s in en... | |
000f54f774407d073cf9 | def angle(self):
rb = self.getComponent(kind=kge.RigidBody)
if rb is not None:
if rb.body is not None:
self.dirty = True
if rb.angle != self._transform.angle:
self.dirty = True
self.debuggable = True
... | |
000fa71ea35e4f287010 | def generate_trees(df, output_dir, root_taxon_ids):
for taxon_id in root_taxon_ids:
root_node = df[df['tax_id'] == taxon_id].iloc[0]
root_name = root_node['name'].lower()
tree = generate_tree(df, root_node)
write_tree(tree, output_dir, f"{NCBI_OUTPUT_BASE}_{root_name}") | |
000fbb204cb640381547 | def cleanData(self):
self.data = None
self.taxaList = []
self.sequenceFileEdit.clear()
self.taxamap = {} | |
000fca890696b74e9aed | def get_total_steps(self) -> int:
return self.total_steps | |
000fd99592a4b5bfd74a | def _check_number(num: int) -> bool:
if not 0 <= num <= 0x9999:
raise ValueError('Invalid number range')
for index in range(4):
if (num >> 4 * index) & 0xF > 0x9:
raise ValueError('Invalid number, contains digit > 9')
return True | |
000ff320c5afcb76613d | def read_required_files(self):
self.stops = pd.read_csv(self.zf.open("stops.txt"))
self.routes = pd.read_csv(self.zf.open("routes.txt"))
self.trips = pd.read_csv(self.zf.open("trips.txt")) | |
000ff514e4669fff95d1 | def make_carla_env():
sys.path.append('/home/frcvision1/Final/My_Environments/')
import Carla
host = 'localhost'
port = 2000
env = gym.make('CarlaEnv-v0')
env = DummyVecEnv([lambda: env])
return env, host, port | |
0010014a71d4a93d6c83 | def _calc_beta_map(model, trial_type, hrf_model, tstat):
import numpy as np
# make it so we do not divide by zero
TINY = 1e-50
raw_beta_map = _estimate_map(model, trial_type, hrf_model, 'effect_size')
if tstat:
var_map = _estimate_map(model, trial_type, hrf_model, 'effect_variance')
... | |
00100a9d2ae4119f3250 | def selectTrianglesFaces():
cmds.polySelectConstraint(m=3, t=8, sz=1)
cmds.polySelectConstraint(dis=True) | |
001014bf1c1cdfabb407 | def remove_tiles(self, tile_coordinates):
for coord in tile_coordinates:
self.set_tile_type(coord[0], coord[1], TileType.EMPTY) | |
00102d06011131706c14 | def play_random_video(self):
videos = self._video_library.get_all_unflagged_videos()
if not videos:
print("No available videos")
return
vid = random.choice(videos)
self.play_video(vid.video_id) | |
0010355bf05230ab5d03 | def get_new_volume_location(self, obj_or_param, VolObj, reservedSpace={}) :
self.Logger.debug("called with Prj=%s, VolObj=%s" % (obj_or_param, VolObj))
this_project = self.get_object(obj_or_param)
if not this_project : return None
if VolObj.type == "RW" :
sps = this_project... | |
00104b108592742e7dd3 | def test_enumerated_initialization(enumerated_design_space):
assert enumerated_design_space.name == 'enumerated'
assert enumerated_design_space.description == 'desc'
assert len(enumerated_design_space.descriptors) == 2
assert enumerated_design_space.descriptors[0].key == 'x'
assert enumerated_design... | |
00105e79e74d120f8f72 | def sum_lista(func, lista: list) -> float:
return sum((func(*tupla) for tupla in lista)) | |
0010604d224b3d6ea363 | def hanger_params(res, **kwargs):
# Check if some other type of hardware is supplied
hardware = kwargs.pop("hardware", "VNA")
assert hardware in ["VNA", "mixer"], "Unknown hardware type! Choose 'mixer' or 'VNA'."
# Whether or not to use a smoothing filter on the data before making guesses
use_filt... | |
001075e1440713192b03 | def convertNpObjToStr(obj):
if isinstance(obj, np.ndarray):
obj = np.ascontiguousarray(obj)# this is a very important step, because many times the np object doesn't have its content in continous memory
data_b64 = base64.b64encode(obj.data)
return json.dumps(dict(__ndarray__=data_b64,dtype=str(obj.dtype),s... | |
0010a12b12ec3bef0156 | def clean_key(key):
if key.startswith("$") or key.startswith("_"):
return key[1:]
return key | |
0010a81649585b7e73a6 | def run_django_production():
print "IN DEVELOPMENT"
with lcd(BIN_DIRECTORY):
local("python manage.py collectstatic")
local("python manage.py compress --force")
local("python manage.py run_gunicorn --workers 5 --settings=www.conf.dev.settings") | |
0010b041269327f0c5ee | def has_more_pages(self) -> bool: | |
0010c221ee0317c81522 | def itkEuclideanDistancePointSetToPointSetMetricv4PSD2_cast(obj: 'itkLightObject') -> "itkEuclideanDistancePointSetToPointSetMetricv4PSD2 *":
return _itkEuclideanDistancePointSetToPointSetMetricPython.itkEuclideanDistancePointSetToPointSetMetricv4PSD2_cast(obj) | |
0010d548c1d29c929af2 | def refine_housing_units(households, buildings, mcd_total):
year = orca.get_injectable("year")
b = buildings.to_frame(
buildings.local_columns + ["hu_filter", "sp_filter", "semmcd"]
)
mcd_total = mcd_total.to_frame([str(year)])
# get units
bunits = b["residential_units"]
bunits = bu... | |
0010eaa6a47e7030f993 | def study(self):
self.procrastinate()
self.student.study() | |
0010f0e4f0d7d8b111f5 | def sample_negatives(X, n_e):
M = X.shape[0]
corr = np.random.randint(n_e, size=M)
e_idxs = np.random.choice([0, 2], size=M)
X_corr = np.copy(X)
X_corr[np.arange(M), e_idxs] = corr
return X_corr | |
0010f8bff982e9cbbaec | def check_herm(self):
self._isherm = None
return self.isherm | |
00111881f47709a0e67d | def mpl2chaco(fig):
return MPLChaco(fig) | |
00112817272fd35dc11d | def unused_indexes(self):
return self.execute(sql.UNUSED_INDEXES) | |
0011611eda5fb91a3a93 | def forward_pass(self, inputs, training=None):
pass | |
0011a8c8b0cec67c04e9 | def calculate_diff(old, new):
dir_diff = DirectoryDiff(old, new).diff()
diff = Diff(old, new)
diff.added = dir_diff.added
diff.removed = dir_diff.removed
diff.changed = dir_diff.changed
return diff | |
0011b22828d649d915d3 | def copy(self):
return(Data(self.df.copy())) | |
0011c68e4e2474131e26 | def close(self):
if self.conn:
self.conn.commit()
self.cur.close()
self.conn.close() | |
0011d723c7f0168fbc66 | def AddLabelsField(parser):
help_text = """\
Labels that are applied to the configuration and propagated to the underlying
Compute Engine resources.
Example:
$ {command} --labels=label1=value1,label2=value2"""
parser.add_argument(
'--labels',
metavar='LABELS',
type=arg_parsers.ArgDict(... | |
0011ef59dff1994599ca | def load_data(self,fname):
return np.load(fname) | |
0011f417467e61b11cd5 | def betas(self):
if self._beta_v is not None:
return self._beta_v.copy()
else:
return None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.