id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
009a197b03a4eaab19d8 | def daily_build(yyyy, mm, dd, loan_object, interest_object, collateral_object):
date_hist_str.append(date(yyyy,mm,dd))
loan_hist.append(loan_object.loan)
liquidity_hist.append(excess_availability(collateral_object, loan_object))
i_rate_hist.append(interest_object.interest_rate())
daily_accrued_inter... | |
009a30a89a3f2f7b8ea8 | def load(self, filename=""):
print("Testing " + self.arch + " in environment " + self.env)
# factory = arch_factory.AbstractFactory | |
009a44dfc3c660bc9623 | async def get_gridpoints_forecast_hourly(self: Nws) -> List[Dict[str, Any]]:
if self.wfo is None:
await self.get_points()
if self.wfo is None or self.x is None or self.y is None:
raise NwsError("Error retrieving points")
raw_forecast = await raw_gridpoints_forecast_hourly... | |
009a5a5825289f00d2e3 | def fill_rect(self, rect, color):
self.point_canvas.itemconfig(self.points[rect], fill=color) | |
009a5f27ccc1427c2a1e | def times(self):
return [ev[0] for ev in self.events] | |
009a85bef84054877de9 | def _write(self, vals):
if 'status' in vals:
self._cr.execute('select id, status, sr, sc from "%s" where id in %%s' % self._table, (self._ids,))
result = self._cr.dictfetchall()
old_status_per_id = {r['id'] : r for r in result}
for rec in self:
if ... | |
009aa1bbf4e35dda6eee | def _make_dataframe(self):
df = DataFrame(self._get_comuni(), columns=["id", "Comune", "Regione", "Provincia", "Abitanti"])
print("Data retrieved succesfully. Here's a sample:\n")
print(df.head(10)) # stampo le prime 10 righe del dataset
return df | |
009aa43729be2673ede7 | def api_check():
return jsonify({'success': True}) | |
009ab9824f9e4de463d7 | def as_unsigned(self):
return self & self.mask | |
009ad4606c1aa30e8215 | def configure_dcbx_app(self, ports, **kwargs):
raise SwitchException("Not implemented") | |
009af0333544989de0f8 | def action_spec(self, physics):
names = [physics.model.id2name(i, 'actuator') or str(i)
for i in range(physics.model.nu)]
action_spec = mujoco.action_spec(physics)
return specs.BoundedArray(shape=action_spec.shape,
dtype=action_spec.dtype,
... | |
009af033fc115eb3157d | def save(self, *args, **kwargs):
super().save(*args, **kwargs)
if self._original_state != self.state_id:
if self.state_id in ['withdrawn', 'rejected', 'no-response', 'overtaken']:
active_req_states = ['assigned', 'accepted', 'completed']
review_req_has_active_... | |
009b00f3f3aa302ef9d9 | def parse_event(event):
log.debug(f"Checking {_event_repr(event)} for configuration")
min_placeholders = None
min_capacity = None
for line in event.description.splitlines():
m = assignment_pattern.match(line)
if m:
key, value_str = m.groups()
if key == "min_capaci... | |
009b291883f648225921 | def step(self):
# Implement SGD! | |
009b5645b966b94bd6d8 | def exp_fitter(xdata, ydata, plot=True, title="", dataLabel = "") :
ab = np.polyfit(xdata,np.log(ydata), 1)
a = np.exp(ab[1])
b = ab[0]
if plot:
comp = matplotlib.offsetbox.AnchoredText('Best fit exponential equation: y = {:.3e} e^({:.3e} x)'.format(a,b), loc=1)
fig, ax = plt.s... | |
009b74e4727364de7703 | def update_coords_dir(self):
self.robot.update_points_triangle() #on met a jour ABC et le centre de gravite pour s'assurer d'avoir les bonnes valeurs pour les calculs,
#meme si on ecrasera ces valeurs par les nouvelles
... | |
009bc7b2878a29748d4c | def csv_header(example_output, datacolumns=["result", "abs_diff"], extracols=[]):
header=[]
numcols=len(datacolumns)
for objects, name in zip(example_output[0:numcols], datacolumns):
for i in range(len(objects)):
header += [name+"%d"%i]
header += ["DP_type", "blocker", "epsilon", "ga... | |
009bd47218e4614d8325 | def flatten(self):
return self.__class__(*[c.flatten() for c in self], **dict(self.iteritems())) | |
009bdfbe5da5df50ed29 | def training(self, loss, optimizer):
train_op = optimizer.minimize(loss[0])
return train_op | |
009bea75947bb784e3ba | def handle_input(self, event):
if event.type == pygame.KEYDOWN:
if self.selecting_key:
self.set_key(event.key)
self.selecting_key = False
elif event.key == pygame.K_DOWN:
if self.selected < len(self.items) - 1:
self.sele... | |
009c206d870773bea986 | def spline_fill(x, y, newindex, k=3, s=0):
# First line creates the relationship
tck = interpolate.splrep(x, y, k=k, s=s)
# Final line passes the new index to fill
return interpolate.splev(newindex, tck, der=0) | |
009c3ad28224880b4cce | def get_facts(self):
return self.__facts | |
009c4cdb17b1b43a95dc | def spaceX(elements, x0=-5, gap=5):
previousX = x0
for elt in elements:
elt.left = previousX + gap
previousX = elt.right | |
009c5231a76bd8619c4f | def get_size(self) -> int:
return self.size | |
009c66e470ca612f24d8 | def fake_data_generator(size, batch_size, preprocess_func):
while True:
X_batch = np.random.randint(low=0, high=256, size=(batch_size, size, size, 3), dtype=np.uint8)
y_batch = np.identity(1000, dtype=np.float32)[np.random.randint(low=0, high=1000, size=batch_size)]
yield (preprocess_func(X_... | |
009c769eded578439b0d | def __init__(__self__, *,
app_service_certificate_not_renewable_reasons: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
auto_renew: Optional[pulumi.Input[bool]] = None,
certificates: Optional[pulumi.Input[Sequence[pulumi.Input['CertificateOrderCertificateA... | |
009c83984b13d63b46cd | def text(self, response, status_code=None):
if status_code:
self.assertEqual(response.status_code, status_code)
self.assertEqual(response.headers['Content-Type'],
'text/plain; charset=utf-8')
return response.text | |
009caa7bb56566a6aacb | def __SameFunctionSpaceErrorCheck(self):
Comparison = len(self.Ensemble[0][0][0].dat.data)
for i in range(len(self.Ensemble)):
for j in range(len(self.Ensemble[i])):
for k in range(len(self.Ensemble[i][j])):
if len(self.Ensemble[i][j][k].dat.data) != Comp... | |
009cf579c4ceb784306f | def execute(self):
x = self._getrates()
result ="<br><p>"
result += '<br>Exchange rates for ' + str(x['base']) + ':'
for key in x['rates']:
result += "<br> " + str(key) + ": " + str(x['rates'][key])
return result + "<br></p>" | |
009d0ff6818cf658e014 | def split(self, criterion, where):
if criterion == 1:
method = "bayer_error"
elif criterion == 2:
method = "cross_entropy"
elif criterion== 3:
method = "gini_index"
info_list = []
# loop each featur... | |
009d3497ea57aa86c69b | def operators(self): | |
009d4a5fb064aa48c841 | def CustomParser(data):
j1 = json.loads(data)
return j1 | |
009d708a49806aa49286 | def re_init(self, activeMfeeders=None, next_feeder_method=None, repetitions=None):
if not (activeMfeeders is None):
self.activeMfeeders = activeMfeeders
if not (next_feeder_method is None):
self.next_feeder_method = next_feeder_method
if not (repetitions is None):
... | |
009d73242ada27beba0f | def test_bag_of_words() -> None:
corpus = [
"The fool doth think he is wise",
"but the wise man knows himself to be a fool",
]
#
# CountVectorizer tokenizes the training data and builds the vocabulary.
#
# Each word becomes a key, it's ordinal value is the value
#
# {
... | |
009d82396872087752e9 | def info(self, msg):
pass # pragma: nocover | |
009d8cf7abd912631b47 | def enable_usb_drive() -> None:
... | |
009dc590367e6154f124 | def create_train_data():
train_data = dict()
val_data = dict()
batch_size = 32
for fold in range(1):
train_imgs = np.load(train_npy_image_path.replace('train', 'train'+str(fold)))
train_aud = np.load(train_npy_audio_path.replace('train', 'train'+str(fold)))
train_text = np.load(t... | |
009de3dc60bafb17a250 | def min_tone(self):
return self._mid_tone.down(12 * self.octaves) | |
009df32e604f6ca551ee | def count(self) -> int:
return self.__count | |
009e01d8edc1cfacdd93 | def process_args(args):
if args.data is not DataType.REAL:
args.injected_ratio = fr_utils.normalize_fr(args.injected_ratio)
# Anon points
anon = []
# if args.dimensions[0] == 3:
# anon.append([0.825, 0.845])
# anon.append([0.865, 0.875])
# anon.append([0.875, 0.885])
... | |
009e25a5f3ce6464af0c | def _get_interface(self, name):
return proxy_new(
self.connection,
Gio.DBusProxyFlags.DO_NOT_LOAD_PROPERTIES |
Gio.DBusProxyFlags.DO_NOT_CONNECT_SIGNALS,
info=None,
name=self.bus_name,
object_path=self.object_path,
interface_nam... | |
009e2cf858b187499790 | def unregister(obj): | |
009e3503c66371eaf970 | def get_passenger_memory_stats(self):
stats = {
'passenger_watchdog_rss_mb' : None,
'passenger_helper_agent_rss_mb' : None,
'passenger_logging_agent_rss_mb' : None,
'total_private_dirty_rss_mb' : None,
}
status, out = commands.getstatusoutput(PASSE... | |
009e4928d6596d4da85c | def _get_paths_to_update(self):
return {
'tpDcc.loader': path_utils.clean_path(os.path.dirname(os.path.dirname(tpDcc.loader.__file__))),
'tpDcc.libs.python': path_utils.clean_path(
os.path.dirname(
os.path.dirname(os.path.dirname(os.path.dirname(tpDcc... | |
009e756193710693f53b | def on_launch(launch_request, session):
print("on_launch requestId=" + launch_request['requestId'] +
", sessionId=" + session['sessionId'])
# Dispatch to your skill's launch
return get_welcome_response() | |
009e95dd1d62b7c939e1 | async def end_game(self): | |
009ecd7b592a07ddf134 | def test_api_key_create(self):
pass | |
009ed7b0bfb00f4c1836 | def deep_rnn_model(input_dim, units, recur_layers, output_dim=29, activation='relu'):
# Main acoustic input
input_data = Input(name='the_input', shape=(None, input_dim))
# TODO: Add recurrent layers, each with batch normalization
rnn_input = input_data
for num in range(recur_layers):
rnn_nam... | |
009edc473904f525a8ef | def getUsers(self):
users_list = list()
return users_list | |
009ee8468b1378b5799a | def get(self):
# Create a Drive service
service = self.CreateDrive()
if service is None:
return
try:
# Requests are expected to pass the file_id query parameter.
file_id = self.request.get('file_id')
if file_id:
# Fetch the file metadata by making the service.files().get ... | |
009ee91e582bb6597008 | def getAllSessionId(self):
response = self.get(self.httpHeader+'/api/v1/sessions', silentMode=True)
sessionId = {}
for eachSessionId in response.json():
sessionId.update({eachSessionId['id']: {'userName': eachSessionId['userName'],
... | |
009eef32dff96a6023db | def _listdir(root, wildcard='*'):
for dirname, _, names in walk(root):
yield dirname, tuple(join(dirname, name) for name in names if fnmatch(name, wildcard)) | |
009f0fa8f066bf318be6 | def distance(a, b):
x1, y1 = a[0], a[1]
x2, y2 = b[0], b[1]
return round(math.sqrt((x1-x2)**2 + (y1-y2)**2)) | |
009f488cd46bb04065dc | def server():
pass | |
009f5680789622f57209 | def get_binary(self, fold_id, relative_path):
download_start = time.time()
padded_fold_id = "%06d" % fold_id
if self.bucket_prefix:
gcloud_path = f"{self.bucket_prefix}/{padded_fold_id}/{relative_path}"
else:
gcloud_path = f"{padded_fold_id}/{relative_path}"
... | |
009f5f5251f534551560 | def bootstrap(self):
logging.info("🛠️ Bootstrapping resources ...")
self._bootstrap_subresources() | |
009f65cccc52b2d76a79 | def play(self, square):
if self.won_by():
raise ValueError('Already won by {}'.format(self.won_by()))
elif square in self.open_moves:
active_user_board = getattr(self, self.current_user + '_board')
active_user_board.append(square)
del(self.open_moves[self.open_moves.index(square)])
... | |
009f87c996e35324d87c | def __init__(self, iterable):
self._iterable = iter(iterable) | |
009f93020481b814a9df | def have_to_reproduct(self, genome: Genome) -> bool:
return -self.ext_factors.overpopulation + genome.p_for_reproduction > \
uniform.rvs(self.params.loc, self.params.scale) | |
009fab4b917b1a1a84e6 | def _get_new(self):
return FormattedParameter(self._str_format, self._value, self._yaml_key) | |
009fc1db0c047134d646 | def build_model(args, task):
src_dict, tgt_dict = task.source_dictionary, task.target_dictionary
# token embeddings
encoder_embed_tokens = nn.Embedding(len(src_dict), args.encoder_embed_dim,
src_dict.pad())
decoder_embed_tokens = nn.Embedding(len(tgt_dict), args.... | |
009fc629879aa1293300 | def recurrence_sequence_ical(
start,
recrule=None,
from_=None,
until=None,
count=None,
duration=None,
):
# Always use python datetime objects and remove the microseconds
start = pydt(start, exact=False)
from_ = pydt(from_, exact=False)
until = pydt(until, exact=False)
tz = st... | |
009fc63ab7a09b3dfaf5 | def test_two_student_one_present_no_grades(self):
yesterday = today-timedelta(1)
group = mixer.blend(Group, name='g1')
student1 = mixer.blend(Student, name='s1', group=group)
student2 = mixer.blend(Student, name='s2', group=group)
class_date = mixer.blend(ClassDate,
... | |
009fdc560e3017c2f178 | def __getitem__(self, key):
result = super(SpatialDataFrame, self).__getitem__(key)
geo_col = self._geometry_column_name
if isinstance(key, string_types) and key == geo_col:
result.__class__ = GeoSeries
result.sr = self.sr
result._delete_index()
elif i... | |
009feb981dd896a06094 | def add_barriers(self):
self.add_barrier('east', 11, self.grid.width)
self.add_barrier('east', 12, self.grid.width)
self.add_barrier('east', 13, self.grid.width)
self.add_barrier('north', 11, self.grid.height)
self.add_barrier('north', 12, self.grid.height)
self.add_barr... | |
00a000356c30c2f0cc29 | def plots(self):
self.plot_voltage()
self.plot_map()
pyl.show() | |
00a0052452d5c7f1c843 | def pyramid_roi_align(inputs, pool_size, image_shape):
# Currently only supports batchsize 1
for i in range(len(inputs)):
inputs[i] = inputs[i].squeeze(0)
# Crop boxes [batch, num_boxes, (y1, x1, y2, x2)] in normalized coords
boxes = inputs[0]
# Feature Maps. List of feature maps from dif... | |
00a00f59b681f24b4f6a | def showFile(self):
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows() | |
00a02a45f764f3ff089d | def test_determine_keywords():
generator = KeysGenerator()
id = generator.load_jobs(test = True)
keywords = generator.determine_keywords(insert_into_db = False)
assert 0 < len(keywords) < 21
assert isinstance(keywords, list) | |
00a0584e918474e6a28d | def test__ScheduledEventEntityMetadataBase__copy_with__0():
entity_metadata = ScheduledEventEntityMetadataBase()
copy = entity_metadata.copy_with()
_assert_fields_set(copy)
vampytest.assert_eq(copy, entity_metadata)
vampytest.assert_is_not(copy, entity_metadata) | |
00a06ecf1ad983e291ff | def route_status(self) -> pulumi.Output[str]:
return pulumi.get(self, "route_status") | |
00a0731c4d4e61bcedbc | def get_image_url(self):
self.image_url = self.source.get_image_url()
self.status = 'Found image URL: %s' % self.image_url | |
00a075b818a30305eacc | def test_generate_readme_contents():
readme = gen_readme.generate_readme()
# Look for a string we know should appear in the README.
assert "### zmake build\n" in readme | |
00a08a928a91e707e16c | def ipv4_list(self):
self.__change_fid__()
capture_cmd = fos_cmd("fabricshow")
#### the next two lines would return each item from the fabricshow command
#ras = re.compile('\s?([0-9]{1,3}):\s+([\d\w]{6})\s+([:\d\w]{23})\s+([.\d]{7,15})\s+([.\d]{7,15})\s+(["_\w\d]+)')
#ras_result ... | |
00a08fd78cd8012debaa | def list_files(self):
self.check_dir()
self.ids.display_files.text = self.display_file_log() | |
00a0a1bef4f64b0d16e2 | def setFastSpeed(self, v):
self.fastSpeed = v | |
00a0a5656ced003d6dcb | def average_color(color_cluster):
num_colors = len(color_cluster)
if num_colors == 0:
return BLACK
r_sum = 0
g_sum = 0
b_sum = 0
for r, g, b in color_cluster:
r_sum += r
g_sum += g
b_sum += b
r = r_sum // num_colors
g = g_sum // num_col... | |
00a0e4dacbad53b3833a | def test_create_status_invalid_api_key(self):
data = json.dumps({
'api_key': self.app.config.get('API_KEY') + '123',
'user': 'r1cky',
'project': 'sumodev',
'content': 'bug 123456'})
response = self.client.post('/api/v1/status/', data=data,
... | |
00a0e700af2919522b2c | def capture_array(self):
img_data = self.capture()
if img_data:
ary = np.fromstring(img_data, np.uint8)
return cv2.imdecode(ary, cv2.IMREAD_COLOR)
return None | |
00a10f1ab4ff5f6df4bd | def parameter_name_st(draw):
prefix = draw(
st.text(ascii_letters + '_', min_size=1, max_size=1)
)
body = draw(
st.text(digits + ascii_letters + '_')
)
return f'{prefix}{body}' | |
00a11170df69e432c02d | def _import(import_str: str):
parts = import_str.split(".")
module = ".".join(parts[:-1])
m = __import__(module)
for comp in parts[1:]:
m = getattr(m, comp)
return m | |
00a1514faf8f7eb5bccf | def get_url(url):
page = urllib.request.urlopen(url)
doc = fix_auto_closing(page)
return BeautifulSoup(doc, 'html.parser') | |
00a16219190bcee91501 | def sanitize_for_serialization(cls, obj):
if isinstance(obj, HTTPHeaderDict):
return HTTPHeaderDict([
(key, cls.sanitize_for_serialization(val)) for key, val in obj.items()
])
else:
return super().sanitize_for_serialization(cls, obj) | |
00a1703cbf99a0104eeb | def create_service_object(credentials):
http_auth = httplib2.Http()
http_auth = credentials.authorize(http_auth)
service = discovery.build('analytics', 'v3', http=http_auth)
return service | |
00a1bde516d27aedd912 | def apply_transform(
self,
audio: np.ndarray,
sample_rate: int,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> Tuple[np.ndarray, int]:
return F.pitch_shift(audio, sample_rate, self.n_steps, metadata=metadata) | |
00a1d0e01c80b781a6d6 | def dump(self, filename):
text = self.dumps()
with open(filename, "w") as fd:
fd.write(text) | |
00a1d0e979215cc98abf | def empirical_msd(data, dim, n, k):
if dim == 1:
x = data
N = len(x)
x1 = np.array(x[:N - n])
x2 = np.array(x[n:N])
c = np.sqrt(np.array(list(x2 - x1)) ** 2) ** k
r = np.mean(c)
elif dim == 2:
l = int(len(data) / dim)
x = data[:l]
... | |
00a1d6effa06826256d3 | def predict(self, state, action):
raise NotImplementedError("Must be implemented in subclass.") | |
00a1da43daa2f5e49ad4 | def _fcn_sourcesDisplay(self):
idx = int(self._sourcesPickdisp.currentIndex())
if idx == 0:
self.sources_display(select='all')
elif idx == 1:
self.sources_display(select='none')
elif idx == 2:
self.sources_display(select='left')
elif idx == 3:
... | |
00a1e0df92242fcf9c89 | def get_resource(self, query_set=[]):
return json.load(open(os.path.join(basedir, 'examples/query_resource.response.json'))) | |
00a21597e24f8ef14586 | def get_status_output(cmd):
on_win = (sys.platform[:3] == "win")
if not on_win:
cmd = "{ " + cmd + "; }"
pipe = os.popen(cmd + " 2>&1", "r")
text = list()
for item in pipe:
text.append(item.rstrip())
try:
sts = pipe.close()
if sts is None: sts = 0
... | |
00a22011039dbed5a10a | def get_director(self) -> List[Director]:
raise NotImplementedError | |
00a24572f9a0db96d13a | def get_platform_dir():
#Detect platform
if sys.platform == 'win32':
platform = 'win'
elif sys.platform == 'darwin':
platform = 'darwin'
else:
platform = 'linux'
if PL.architecture()[0].startswith('32'):
platform += '32'
else:
platform += ... | |
00a27dc9a0d269c03122 | def test_tool_with_wrapper(self):
#set up paths
rwdir = os.path.join(self.wdir, 'diffcoeff_utility')
shutil.copytree(os.path.join(testdir,'files','diffcoeff_utility'),
rwdir)
outputname = os.path.join(rwdir, 'Diffusivity.txt')
plotname = os.path.join(rwdi... | |
00a282f67f7736c1c68f | def usage():
print "\n\n\n"
print "Command-line usage menu"
print "--help / -h to see the help menu"
print "--verbose / -v for verbose mode"
print "to/from to select mode"
print "Convert to HDF5 Arguments"
print "\t--dir / -d to specify the input directory containing the files to convert"
... | |
00a29dce6f719bc1532b | def test_bool(self):
x = True
self.assertTrue(self._bt['func'](x)) | |
00a2c42e1b169f5e865e | def is_empty(text):
return text is None or len(text) == 0 | |
00a2cbf9fa69d9163acf | def init_isweep_arrays():
global currentvals
currentvals = _n.linspace(cfg_isweep["Start"], cfg_isweep["Stop"], cfg_isweep["Steps"]) | |
00a2d7733bb98b2748d4 | def get_players_input(self):
while 1: # Query the action.
inpt = input("Shoot or move (S-M)? ")
try: # Ensure that the player choses a valid action (shoot or move)
mode = str(inpt).lower()
assert mode in ['s', 'm', 'q']
break
except (ValueError, AssertionError):
print... | |
00a2ef6490bee7050a84 | def screenshot(self, dsp:display.Display) -> np.ndarray:
width, height = self.window_pos[2], self.window_pos[3]
x, y = self.window_pos[0], self.window_pos[1]
#* Removed instantiating multiple display.Display objects because
#* of decreasing fps with time.
# dsp = display.Display... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.