id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
0063ae881d2fd9ef1e48 | def get_encoding_from_headers(headers):
content_type = headers.get('content-type')
if not content_type:
return None
content_type, params = cgi.parse_header(content_type)
if 'charset' in params:
return params['charset'].strip("'\"")
if 'text' in content_type:
return 'ISO-8... | |
0063b455a3b063a70295 | def recover(self):
# assume in map frame
self.end = [self.last_known_pos.x, self.last_known_pos.y]
self.start = [self.robot_pos.x, self.robot_pos.y]
print("finding path from ", (utils.show(self.start[0]), utils.show(self.start[1])), "to ",
(utils.show(self.end[0]), utils.sh... | |
0063d27878be7566f0dd | def set_approval_status(self, status):
assert status in ["approved", "denied"]
self.approval_status = status
if status == "denied":
pass | |
00640be330c1d2d30334 | def xS(self, x):
result = set();
for rightTerm in range(self.order):
result.add(self.multiply([x, rightTerm]));
return result; | |
0064174c338f146cb702 | def convertToString(inObject): # actually, we can probably do this in JavaScript
pass | |
0064260ee77295b55162 | def has_edge(self, edge):
pass | |
006429897af6e08eb159 | def __call__(self, results):
if self.file_client is None:
self.file_client = mmcv.FileClient(**self.file_client_args)
if results.get('seg_prefix', None) is not None:
filename = osp.join(results['seg_prefix'],
results['ann_info']['seg_map'])
... | |
0064306f4751122d6d53 | def exponential(self):
other = self.clone()
other.exponentiate()
return other | |
00643ea4095da7328473 | def go_sleep(self, length_time):
print("Sleeping for", length_time, "seconds")
sleep(length_time) | |
006467d28f039664ec4c | def test_scale(self):
in_range = [1, 2, 3]
out_range = ["red", "green", "blue"]
scale = pero.OrdinalScale(
in_range = in_range,
out_range = out_range)
self.assertEqual(scale.scale(1), "red")
self.assertEqual(scale.scale(2), "gree... | |
00646d9b42e4f1aa41f2 | def send_confirmation_email(to):
token = generate_confirmation_token(to)
confirm_url = url_for('confirmationview', token=token, _external=True)
html = render_template('confirmation.html', confirm_url=confirm_url)
send_email(to, 'Test server - confirm your registration', html) | |
00648a59ec8e8240018a | def config_param():
config = helper.TrainConfig()
# All those parameters should be configured accordingly.
config.batch_size = 1
config.vocab_size = 128
config.embed_dim = 10
config.hidden_dim = 10
config.num_hiddens = 1
config.mode_dim = 10
config.num_modes = 10
config.cmt_seq_l... | |
00649aa933ae833bf1d1 | def user_name_for ( name ):
name = name.replace( '_', ' ' )
name = name[:1].upper() + name[1:]
result = ''
last_lower = 0
for c in name:
if (c in uppercase) and last_lower:
result += ' '
last_lower = (c in lowercase)
result += c
ret... | |
0064c6ca14d9cbbc2ca6 | def data_loader():
tr_d, va_d, te_d = data()
train_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]]
train_results = [vector_result(y) for y in tr_d[1]]
train_data = zip(train_inputs, train_results)
val_in = [np.reshape(x, (784, 1)) for x in va_d[0]]
val_data = zip(val_in, va_d[1])
... | |
0064f879e054dbe66d08 | def plot(self, name_figure):
import matplotlib.pyplot as plt
# Bunch of things so the plot looks nice. Nothing to do here.
plt.rcParams['axes.linewidth'] = 1.5
font = {'family': 'serif', 'size': 15}
scatter_kwargs = {"zorder": 100}
error_kwargs = {"lw": .5, "zorder": 0}
... | |
0064ff594b9485e3b4b6 | def get_heading_types(self):
return # osid.type.TypeList | |
006528061b84ffef8a59 | def __init__(self, data: Dict[str, Any] = {}) -> None:
super().__init__()
self.last_batch = data.get("last_batch", None) # One of "rollover", "discard"
self.batch_size: Optional[int] = data.get("batch_size")
self.dataset: Optional[Dataset] = None
if data.get("dataset"):
... | |
006544fe49119eff06c4 | def deleteItem(self, event):
who = str(event.widget)[-4:]
confirm = messagebox.askyesno('Delete', "Delete this shortcut ?\n\nThe text specified will be removed from the clipboard and associated keys will return to normal use.")
if confirm == True :
self.active_shortcuts[who][0].p... | |
006557689039298abdad | def count_uniq_ip(l_d_flow_records, d_filters={}):
d_ipsrc_level_analysis = dict()
d_ipsrc_ports_protocols = dict()
d_ipdst_level_analysis = dict()
d_ipdst_ports_protocols = dict()
d_ipsrc_level_analysis_peringress = dict()
d_ipsrc_peringress_ports_protocols = dict()
d_ipdst_level_analys... | |
00657dcfdf5aea2a540d | def updateCells(self, dt):
# Setting dt (WARNING::WARNING)
#dt = 0.0005
# Setting dx and dy
dx = self.dx
dy = self.dy
# Updating the Mesh time
self.time += dt
# Looping over all the cells and updating if not boundary tagged
for i, elem in enum... | |
006596609f3b2c41b8b1 | def resize_move(self) -> None:
try:
self.resize(*win_size)
logger.debug(f'Resized window to {win_size}')
except:
logger.warning('Could not resize window')
if win_pos:
try:
self.move(*win_pos)
logger.debug(... | |
0065a2a2b3efe730eaac | def _get_profiles_base(self, source_ids, page):
date_start = BASE_DATE_START
resp, err = api_utils.exec_api_call(lambda: self.api.profile.list(source_ids=source_ids, limit=1000, date_start=date_start, page=page, sort_by="reception"))
if err is not None:
err = "Cannot get profiles fro... | |
006608bff743cbaa3fea | def has_output(self) -> bool:
return bool(self.stdout.strip() or self.files or self.failed_files) | |
006667bb6161f2e096d3 | def shuffle_card(self):
random.shuffle(self.deck_of_cards) | |
006681232cc88be9adbd | def getProbability(myhand,table_cards,logic_func,deck):
cards_left = 5 - len(table_cards)
Occurances = 0
for comb in itertools.combinations(deck,cards_left):
# print(comb)
if logic_func(myhand,table_cards+list(comb)):
Occurances += 1
total_combinations = count_iterable(iterto... | |
0066b099cc75d2958d45 | def saveInfo(self, writer):
writer.writeInfo(self.info) | |
0066b1d8934f6c2afd58 | def get_data():
# if randint(1, 100) % 2 == 0:
# return False, -1
# return True, np.random.random()
return True,yielder() | |
0066c466ce844d04bd97 | def document(self, id, rev=None):
uri = '/%s/%s' % (self.name, urllib.parse.quote_plus(id))
if rev:
uri += '?' + urllib.parse.urlencode({'rev': rev})
return Document(id=id, inputDict=self.get(uri)) | |
0066c4bb036c95b23555 | def draw(self, screen):
self.__currentState.draw(screen) | |
0066da601ce16e85677b | def validate_phone_input(phone):
if re.search("^[0-9]{5,}$", phone):
return True
flash("Invalid formatted phone. Valid phone must contain at least 5 characters, all must be digits.")
return False | |
00670f4f0f7df1e4dac8 | def easyXML(self, res):
from bioservices import xmltools
return xmltools.easyXML(res) | |
00672e13c7620493d85f | def locateContours(img,xoffset,yoffset):
#Find contours and sort largest to smallest
edged = cv2.Canny(img, 30, 200)
img1, contours, hierarchy = cv2.findContours(edged.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key = cv2.contourArea, reverse = True)[:75]
if... | |
00674f9f0035de3049d6 | def num_variables(self):
return len(self.expression.free_symbols) - len(self._parameters) | |
00675edd089217991442 | def _latency(self):
def _add_metric(proto, metric):
if proto == 'nfs':
mapping = array_specific_performance_mapping.nfs_array_specific_latency
elif proto == 'http':
mapping = array_specific_performance_mapping.http_array_specific_latency
elif p... | |
0067638d49c0c6edd7fa | def set_set_point(self, set_point: float) -> None:
self.__set_point = set_point | |
0067c3a57d6457128779 | def convert_gps_to_xy(lat_gps, lon_gps, lat_origin, lon_origin):
x_gps = EARTH_RADIUS * (math.pi / 180.) * (lon_gps - lon_origin) * math.cos((math.pi / 180.) * lat_origin)
y_gps = EARTH_RADIUS * (math.pi / 180.) * (lat_gps - lat_origin)
return x_gps, y_gps | |
0067f7134b6c89115978 | def calculate_precision(benchmark_pairs, aligned_pairs):
aligned_from_benchmark = 0
aligned_correctly = 0
for src, trg in benchmark_pairs.items():
if src in aligned_pairs.keys():
aligned_from_benchmark += 1
if trg == aligned_pairs[src]:
aligned_corr... | |
0067fa44aa49d66c959d | def path_update(self, lastPrice, lastTime):
self.pricePath.append({'timestamp': int(lastTime), 'price': float(lastPrice)}) | |
006830d0133363d6b043 | def disconnect(conn):
conn['cursor'].close()
conn['conn'].close() | |
0068427db43e11623b94 | def _model_definition(self, net):
# Input filtering and downsampling with max pooling
print(net.shape) #channels must be specified first otherwise keras assumes channels last
'''
net = Conv2D( filters=32, kernel_size=3, activation='relu', padding='same',
... | |
006862f081deefacb3ae | def get_move(self):
children_moves = self.game.get_moves_for_current_player()
best_move = None
best_score = -100000
print(len(children_moves))
for move in children_moves:
score = self.min_value(move, -100000, 100000, 1)
if score > best_score:
... | |
0068d549628772e1079f | def GetFile(file_name):
the_file = None
try:
the_file = open(file_name, 'rb')
except IOError:
the_file = None
return the_file | |
006901bdff40a7f3b21a | def setup_grid(self):
grid_dim = len(self.dihedrals)
gs = self.grid_spacing
grid_1D = range(-180+gs, 180+gs, gs)
self.grid_ids = tuple(itertools.product(*[grid_1D]*grid_dim)) | |
0069257298d734c4a94b | def _extract_header_token_value(request_headers):
authorization_header = request_headers.get(current_app.config["JWT_HEADER_NAME"])
token_prefix = current_app.config["JWT_HEADER_TOKEN_PREFIX"].lower()
if authorization_header and authorization_header.lower().startswith(token_prefix):
return authoriza... | |
006938be3bf4e255889b | def compODEdydt(self, t, y, args=None):
if self.b_vary_vehicle is False:
dydt = comp.Comp.compODEdydt_diffu (self, t, y, args)
# If infinite source, concentration doesn't change, but above dydt calculation
# is still needed since calling compODEdydt_diffu... | |
00695f6c02fe54adaa2d | def preprocess_text_with_line_numbers(filename):
input_lines = get_lines(filename) # get all lines from filename
abstract_lines = "" # create an empty abstract
abstract_samples = [] # create an empty list of abstracts
# Loop through each line in target file
for line in input_lines:
if line.startswith("... | |
0069be0e3afd5832f475 | def configure_dmd(self):
self.dmd = PROCDMD(self, self.machine)
return self.dmd | |
0069c335c9609cb10b7d | def task(cls) -> TaskType:
raise NotImplementedError | |
0069c67720beea3c9a3f | def get_queryset(self):
queryset = Structure.objects.all()
user = self.request.query_params.get('user', None)
if user is not None:
queryset = queryset.filter(owner_id=user)
return queryset | |
0069ecf7edc36ebf7718 | def calculate_activation_statistics(images, sess, batch_size=12, verbose=True):
act = get_activations(images, sess, batch_size, verbose)
mu = np.mean(act, axis=0)
sigma = np.cov(act, rowvar=False)
return mu, sigma | |
0069f5c4203b0d75b9b9 | def addNotesToPlaySeq(self, notes):
# tempo
# prevPitch
# prevDuration
# prevFreq
# note
# num
# typ
# ascNotes
# notesLen
# i
# ch
# dNote
# pitch
# freq
# ms
# ms16
# rest
te... | |
0069f6bbb16b29b86a5f | def mean(self):
raise NotImplementedError | |
006a1efaf8b817a82170 | def station_stats(df):
c_title = 'The Most Popular Stations and Trip'
space_cnt = display_stats_category(c_title)
start_time = time.time()
# display most commonly used start station
print('The most commonly used start station is\'{}\'.'.format(df['Start Station'].mode()[0]))
# display mos... | |
006a4e11269602c7407e | def get_num(self):
return len(self._queue) | |
006a649bfc266b8820d8 | def clean_file_name(file_name: str) -> str:
file_name = remove_special_chars(file_name, 1)
file_name = re.sub(r'__+', '_', file_name.replace(' ', '_'))
return file_name | |
006a762973e453ed85ad | async def wait_finished(self) -> None:
... | |
006ab862d9f7f103bd8a | def remove_job(context):
params = {'action':'remove'}
params['job'] = context['-n']
post(addr, params) | |
006abd5c8a33a92c4a20 | def check_installed(package_name):
with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):
result = run('dpkg -s {0} | grep "Status: install ok installed"'.format(package_name))
return result.startswith("Status:") | |
006acf0a93d209fb2bb2 | def close_files(infile, outfile):
if infile != sys.stdin:
infile.close()
if outfile != sys.stdout:
outfile.close() | |
006acf57c6ed1f6c5fe1 | def send_frames(self, frames):
for f in frames:
f.availability = self.get_time() + f.size / self.bandwidth + self.sending_delay | |
006ad532d332fb0f7713 | def unsupported_method_response():
response = Response()
response.status_code = 403
return response | |
006ae3f32542d5fc95e4 | def bus(self):
return self._pci_address['bus'] | |
006afef7b16297040890 | def add_layer(self, num_connections, num_neurons):
self.layers.append(Layer.Layer(num_connections, num_neurons)) | |
006b1a427d328e9aa392 | def _buildListToExport(self, list):
self._initGliffy()
result = []
for item in list:
diagram, did, cetag = item
code, etag = self.gliffy.head(did)
if (code):
if (cetag != etag):
result.append( (diagram, did, etag) )
... | |
006b21aa1d68c42c5bbb | def value_iteration(P, nS, nA, gamma=0.9, max_iteration=20, tol=1e-3):
V = np.zeros(nS)
policy = np.zeros(nS, dtype=int)
############################
# YOUR IMPLEMENTATION HERE #
############################
counter = 0
V_new = np.zeros(nS)
# Loop to get value convergence
while coun... | |
006b3559895770069ff2 | def _create_dials_env_script():
import os
import libtbx.load_env
if os.name == "nt":
filename = abs(libtbx.env.build_path.dirname() / "dials.bat")
else:
filename = abs(libtbx.env.build_path.dirname() / "dials")
if not os.path.exists(filename):
return
if os.name == "nt... | |
006b82101c938207104d | def _from_vector_inplace(self, vector):
raise NotImplementedError() | |
006b930b039888e7f3ba | def calculate_score(self):
qc = QualityControl.objects.filter(content_type=self.content_type,
object_id=self.object_id)
avg = qc.aggregate(
value=models.Avg(models.F('good') - models.F('bad')))
# normalise to between -1 and 1 - TODO check ... | |
006bcd7d575a65924ef8 | def has_credentials(self):
if self._api_key is not None:
return True
elif self._login is not None and self._pwd is not None:
return True
return False | |
006c17f8ac0f06efdaba | def copy(self):
return self[:] | |
006c1f3b9595004a0c8f | def executable_file(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "executable_file") | |
006c4e75e61d61c4fcbd | def add_session(self, data, course):
session = data[self.session]
course[session] = {'lectures': [], 'tutorials': []}
self.add_section(data, course[session], course)
return session | |
006c79ffa55d8804f786 | def test_consents_update(self):
preexisting_required_terms = Term.objects.filter(
required_type=Term.PROFILE_REQUIRE_TYPE
).active()
term1 = Term.objects.create(content="term1", slug="term1")
term1_option1 = TermOption.objects.create(
term=term1,
opti... | |
006c805e67ccd0d7210e | def generate_graph(num_families, age_groups_probs):
G = nx.Graph()
families = {}
all_colors = []
person_idx = 0
children = []
adults = []
elderly = []
person_to_family = {}
family_edges = []
for family_idx in range(num_families):
fam_size = family_sizes[family_idx]
... | |
006cc0663c50c608b743 | def sample_index(p):
return np.random.multinomial(1, p).argmax() | |
006cc3cba6ef01e02c65 | def test_request_context(self, *args, **kwargs):
from flask.testing import make_test_environ_builder
builder = make_test_environ_builder(self, *args, **kwargs)
try:
return self.request_context(builder.get_environ())
finally:
builder.close() | |
006cc9283d514ceae253 | def test_bin_centers(self):
c = self.b.get_center()
self.assertEqual(c[0], 0.5)
self.assertEqual(c[1], float('inf')) | |
006ccc679df03ad54cb5 | def do_history(self,args):
for idx in range(readline.get_current_history_length()):
sys.stdout.write(readline.get_history_item(idx + 1) + "\n") | |
006ce28fef1c94829c42 | def get_es_auto_doc_mapping(self):
doc_type = self.es_doc_type()
for field in doc_type._doc_type.mapping:
prep_func = getattr(doc_type, 'prepare_{0}'.format(field), None)
if prep_func is not None and callable(prep_func):
value = prep_func(self)
elif ha... | |
006d1e5f3cf2dd4a5326 | def runAllTests():
test.runAllTests() | |
006d384cc3e2d4147caf | def LV1():
import scipy as sc
import scipy.integrate as integrate
def dCR_dt(pops, t=0):
""" a function that returns the growth rate of
consumer and resource population at any given time step"""
R = pops[0]
C = pops[1]
dRdt = r * R - a * R * C
dCdt = -z * C... | |
006d41b8a8316e72d27f | def asignar_ejercitos(self, pais, ejercitos):
self.paises[pais].asignar_ejercitos(ejercitos) | |
006d4a5753c08cfb7aaa | def __init__(self, name, fuel, reliability=0.0):
super().__init__(name, fuel)
self.reliability = reliability | |
006d8afb212437473c76 | def prev_transition(self, transition):
assert isinstance(transition, Transition)
self._prev_transition = transition | |
006da219e9919a514702 | def normalize_image(image):
return ((image/255.0) - mean) / std | |
006da8356e0d29158e27 | def update_paddle(self, value, ball):
obj = self
if config.FRAME_WIDTH - 2*obj.get_shape[0] >= obj.get_x + value >= 0:
obj.set_x(obj.get_x + value)
if ball.get_velocity == [0, 0]:
ball.set_x(ball.get_x + value) | |
006dce5d5653ed3d201e | def compute_cdf_error(self):
srom_cdfs = self._srom.compute_cdf(self._x_grid)
target_cdfs = self._target.compute_cdf(self._x_grid)
# Check for 0 cdf values to prevent divide by zero.
nonzero_indices = np.where(target_cdfs[:, 0] > 0)[0]
srom_cdfs = srom_cdfs[nonzero_indices, :]
... | |
006dcfa7ea07026cc821 | def dump(url, device, checksum_type=None, checksum=None, **kwargs):
scheme, _, path, *_ = urllib.parse.urlparse(url)
if scheme not in VALID_SCHEME:
raise SaltInvocationError("Protocol not valid for URL")
# We cannot validate the compression extension, as we can have
# non-restricted file names... | |
006dd88735d1832d209c | def load_default_config(self):
return self.load(self._get_default_config()) | |
006dec99464b3b08967a | def fit_null_test(self):
pass | |
006e055ca8897267bff9 | def getMetaKeywords(): | |
006e0dfca5a11ee10a25 | def distance(point1, point2):
return point1.distance(point2) | |
006e18c3205784040bf2 | def normal_vector(v):
return num.array([-v[1], v[0]], float) | |
006e224c75705d561973 | def plot_multi_scatter_plot(list_of_y_data, list_of_x_data, list_of_legends, title_of_chart, x_axis_label, y_axis_label,
list_of_colors, size_of_marker=50):
for i in range(0, len(list_of_x_data)):
plt.scatter(list_of_y_data[i], list_of_x_data[i], s=size_of_marker, c=list_of_color... | |
006e2ade014c6431e5f4 | def cartpole_state_to_graph(state):
# Add state to globals as well.
globals = np.asarray([state], dtype=np.float32)
# State has 4 elements, simply wrote each to a node.
nodes = np.asarray([
# Note extra [] - batch dim required for node/edge features.
[state[0]],
[state[1]],
... | |
006e3e5f19fa2fce9706 | def textContent(self):
output = []
for item in self:
if item.nodeType == Node.TEXT_NODE:
output.append(item)
elif getattr(item, 'str', None) is not None:
output.append(item.str)
else:
output.append(item.textContent)
... | |
006e59de8f2c759f66e3 | def test_action_redirects(self):
req = self.req("post", "/the/url", data={"action-doit": "3"})
res = self.view(req)
self.assertEqual(res.status_code, 302)
self.assertEqual(res["Location"], "/the/url") | |
006e7fc14d8d6c79af9e | def tokenize(self):
from transformers import DistilBertTokenizerFast
self.tokenizer = DistilBertTokenizerFast.from_pretrained(BASE_MODEL)
self.eval_dataset = IMDbDataset(self.tokenizer, self.eval_df)
self.test_dataset = IMDbDataset(self.tokenizer, self.test_df)
self.train_datase... | |
006e90887fe8c6517d2f | async def current_window_handle(self):
if self.w3c:
return (await self.execute(Command.W3C_GET_CURRENT_WINDOW_HANDLE))['value']
else:
return (await self.execute(Command.GET_CURRENT_WINDOW_HANDLE))['value'] | |
006e9f98c71f044d83e5 | def predict_all(self, *args):
return self._predict_all(*args) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.