id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
002388e728d84d6fa1e4 | def g_spd(t1, t2):
n0 = len(t1)
n1 = len(t2)
lats0 = t1[:, 1]
lons0 = t1[:, 0]
lats1 = t2[:, 1]
lons1 = t2[:, 0]
dist = 0
for j in range(n1):
dist_j0 = 9e100
for i in range(n0 - 1):
dist_j0 = np.min((dist_j0, point_to_path(lons0[i], lats0[i], lons0[i + 1], lat... | |
0023977e6cbea949dfcf | def tags_route(self, request):
ctx = plugin_util.context(request.environ)
experiment = plugin_util.experiment_id(request.environ)
return http_util.Respond(
request, self.tags_impl(ctx, experiment), "application/json"
) | |
0023afe4985f69059565 | def test_R_g(self):
assert u.isclose(disk_test.R_g, R_g_test, atol=0 * u.cm, rtol=1e-2) | |
0023b7ac184c4f07194a | def sql(self) -> str:
cl = [self.time_constraint(self._min_time, self._max_time)]
cl.append('coding.code="{}"'.format(self._code))
# We don't need to filter coding.system as it is already done in flattening.
if self._values:
codes_str = ','.join(['"{}"'.format(v) for v in self._values])
cl.a... | |
0023cb45946f284ac2f2 | async def setup_server_loop():
asyncio.ensure_future(update_servers()) | |
00240548e931c7c41788 | async def output_answer(self, ctx: commands.Context, *, question: str) -> None:
if len(question.split()) >= 3:
answer = random.choice(ANSWERS)
await ctx.send(answer)
else:
await ctx.send("Usage: .8ball <question> (minimum length of 3 eg: `will I win?`)") | |
00240b98dd50e91b1411 | def solve__(m, n): | |
0024450ccc76b9baf53c | def GradVandermonde2D(N,r,s):
V2Dr = num.zeros((len(r),(N+1)*(N+2)/2));
V2Ds = num.zeros((len(r),(N+1)*(N+2)/2));
# find tensor-product coordinates
a,b = rstoab(r,s);
# Initialize matrices
sk = 0;
for i in range(N+1):
for j in range(N-i+1):
V2Dr[:,sk],V2Ds[:,sk] = Grad... | |
0024807b51d63a1bc367 | def get_n1(self):
return self.n1 | |
002482ed55da65a1809f | def get_possible_filters(self):
return(self.nitro.request('get_possible_filters')) | |
0024836b79c41744bc2f | def get_vcdn_net_interfaces(ns_uuid, search_for_mid_cache="vCache-mid-vdu",
search_for_edge_cache="vCache-edge-vdu"):
vdus_list = []
interfaces = {"mid": None, "edge": None}
edges_interfaces_all = {}
count_index = None
# Fetch the VNFs by given NS instance
token = be... | |
0024bf211527277cd5c0 | def checkkwargs(self, kwargs, globalcheck=None, **kwargsexpected):
for k in self.METADATA:
v = kwargsexpected.get(k)
if v is None:
continue
if isinstance(v, str) and kwargs[k] != v:
return False
if isinstance(v, int) and kwargs[k] !... | |
00251711d2d9de7111f5 | def __define_test_macros(self):
self.test_macros = {
"data_base_dir": "/tests/data",
"out_base_dir": "/tests/out",
"data_dir": "/tests/data/0", # data_base_dir/ds_id
"out_dir": "/tests/out/0", # data_base_dir/comb_id
"comb_id": 0,
"ds_id... | |
002524c20793407d084d | def loadSummarizedContextStats(infiles, outfile):
windows.loadSummarizedContextStats(infiles, outfile) | |
002529e82739c446fb5c | def cleanup_html_lookup_file(filename):
with open(filename, 'r', encoding='utf-8') as fs:
lines = list({item.strip().lower() for item in fs.readlines()})
# while we are at it, let us alphabetize the entries by query
lines.sort(key=str.lower)
with open(filename, 'w', encoding='utf-8') as fs:
... | |
002540dc7f0e4da4da21 | def SetNthComponent(self, c: 'int', v: 'float const &') -> "void":
return _itkVectorPython.itkVectorF6_SetNthComponent(self, c, v) | |
00255f4abc6258fa3d14 | def _volume_get(context, volume_id):
return TEST_VOLUME[int(volume_id.replace("-", ""))] | |
0025626b9256a63b385e | def get_returns(self, r, p, n):
if r == []: return []
if not (p != [] and n != []): return r
g = np.zeros_like(r)
# Find indices of terminal observations.
for index in np.argwhere((n == -1) | (np.arange(len(n)) == len(n)-1)):
g[index] = r[index]
index_p =... | |
00258dbb42cea16eecac | def preparePath(self, path):
if not os.path.isabs(path):
path = os.path.join(self.rel_base, path)
return os.path.abspath(path) | |
00259d1999a5d463c9cd | def get_labels(self, issue):
labels = []
for l in issue.labels:
labels.append({
"color": l.color,
"external_id": l.url,
"name": l.name
})
labels.append({'name': 'github'})
return labels | |
0025a053910624a966ca | def operation_list(self):
return self._operation_modes | |
0025b54f4c002df6d716 | def features_for_rank(self, proc, results):
feature_list = []
meta = []
results = results['hits']['hits']
search_name = proc['word']
code_mention = proc['features']['code_mention']
class_mention = proc['features']['class_mention']
for rank, entry in enumerate(res... | |
0025ec41c1003fd1b77a | def test_data_in_param(self): | |
0025f3d7b2edad6882bd | def handle_all_404(*_):
return response_fn(404, "error", "url not found") | |
0025f75aae5efce255ab | def voigtAverage( values=[], weights=[] ):
voigtAve = 0
sumWeight = 0
i = 0
if type(values) == np.ndarray and (
type(weights) == np.ndarray) and (
len(values) == len(weights)):
for w in np.nditer(weights):
sumWeight += w
for i in range(len(values)):
voigtAve += weights[i]*values[i]/sumWeight
... | |
0026095e1c8b70f6ece8 | def test_init(self):
pass | |
00263986ded7fd5f3b27 | def gaussian_lcb(X, model, kappa=1.96, return_grad=False):
# Compute posterior.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
if return_grad:
mu, std, mu_grad, std_grad = model.predict(
X, return_std=True, return_mean_grad=True,
retu... | |
00264ee1b2041c09b752 | def verify_slack_signature():
if app.debug:
return
timestamp = request.headers['X-Slack-Request-Timestamp']
signature = request.headers['X-Slack-Signature']
if time.time() - int(timestamp) > 5 * 60:
app.logger.error('Stale command request.')
abort(403)
compstr = f'v0:{timesta... | |
0026a77f2cb05f91c670 | def _set_status(status: Optional[str], code: Optional[int]) -> str:
if status is not None:
return status
elif code == 0:
return Status.ok
else:
return Status.error | |
0026a8d123621c94bbc1 | def _get_process_memory_info(pid, module):
# initialize the main dictionary
proc = {}
process_output = _execute_command("ps -auxww | grep " + pid, module)
processes = process_output.split('\n')
for row in processes:
# skip blank lines
if row is '' or not row:
continue
... | |
0026ea3893a03cd49d86 | def __create_grid(self):
if self.rank == 0:
#Create uniform rectangular grid
j = np.complex(0,1)
ext = self.extension
grid = np.mgrid[
-ext:
self.plate_length+ext:
((1.0+2.0*ext/self.plate_length)*(self.node... | |
0026ed43b6e3550b00cc | def test_sort_by_timestamp(self):
results = self._cc_client.getRunResults(
None, 500, 0, None, ReportFilter(), None, False)
self.assertEqual(len(results), 4)
sort_timestamp = SortMode(SortType.TIMESTAMP, Order.ASC)
results = self._cc_client.getRunResults(
None,... | |
0026f22d2095fa105037 | def log_metric(self, run_id, key, value, timestamp=None, step=None):
self.tracking_client.log_metric(run_id, key, value, timestamp, step) | |
0027198e073ad6248afc | def _get_constraints(self, tree):
tree_data = tree.tree_data
constraints = []
for k in range(tree.n_nodes - 1):
const_k = []
for i in range(tree.n_nodes - 1):
if k != i:
# add to constriants if i shared an edge with k
... | |
002723a7c507bebb565d | def _create_dict_row(kim, line, desired_facets):
row_dict = dict()
split = line.replace("\n", "").split(",")
row_dict["TestSubject"] = split[kim["TestSubject"]]
row_dict["TimeStamp"] = split[kim["TimeStamp"]]
for e in desired_facets:
row_dict[e+"Evidence"] = split[kim[e+"Evidence"]]
retu... | |
00272c8c51713fbcd425 | def t_ha(node):
return Call(
func=Attribute(
value=node.func.value,
attr='has_attr',
ctx=node.func.ctx
),
args=node.args,
keywords=node.keywords
) | |
00276507df438bfc2076 | def data():
df = pd.read_csv(
os.path.join(HERE, 'data', 'wg93.txt'),
sep='\t',
dtype='category',
usecols=['A', 'B', 'C', 'D'])
return df | |
00276e1bebddbdcad6d7 | def load_data_from_bq(data_names,project_name):
client = bigquery.Client(location="US")
queries = [f"""SELECT * FROM `{project_name}.{name}`""" for name in data_names]
dfs=[]
for i, _ in enumerate(data_names): dfs.append(client.query(queries[i],location="US").to_dataframe())
return(dfs) | |
00277c8d6ff132316102 | def getDeck():
deck = []
for suit in (HEARTS, DIAMONDS, SPADES, CLUBS):
for rank in range(2, 11):
deck.append((str(rank), suit)) # Add the numbered cards.
for rank in ('J', 'Q', 'K', 'A'):
deck.append((rank, suit)) # Add the face and ace cards.
random.shuffle(deck)
... | |
002788c08f525bbb5e02 | def execute(self):
config = self.get_config()
hive_db = config["hive_db"]
hive_table = config["hive_table"]
key_columns = config.get("key_columns")
partitioned_by = config.get("partitioned_by")
archive_path = config['archive_path']
force_truncate = co... | |
0027bb9984ae8436e19d | def get_settings():
return Settings() | |
0027e25e032abf5a803e | def _installCallbacks():
pass | |
0027e87c5027e6e795fb | def config_log():
my_formatter = logging.Formatter(
"%(asctime)s - %(name)s - level=%(levelname)s - %(message)s"
)
my_handler = logging.StreamHandler()
my_handler.setFormatter(my_formatter)
logging.getLogger().addHandler(my_handler)
logging.getLogger().setLevel(LEVEL_MAPPING[LOGGING_LE... | |
002816f0714353a82d7a | def haiku(robot):
robot.sound_system.speech_maker.speak("I am a robot").wait()
robot.sound_system.speech_maker.speak("I speak this haiku for you").wait()
robot.sound_system.speech_maker.speak("Did you enjoy it").wait() | |
00282c0135afc6668522 | def serialize_to(package, file_):
return _Serializer(package, file_, _FORMAT).serialize() | |
00284445f39b71006ced | def status(self):
resp = self._batch_client.read(self.job_id)
if 'failed_reason' in resp:
warn('Job failed: {}'.format(resp.get('failed_reason')))
self._set_status(resp.get('status'))
return dict(status=resp.get('status'),
updated_at=resp.get('updated_at')... | |
0028448a1cd63f8a2fbb | def feasible(self,allvars):
for var in self.variables:
if var.name not in allvars:
raise NameError("no variable in the problem instance named %r" % var.name)
return True | |
002847bad004528b913f | def Top_k(self,hstack_indexs):
# get top-k label
itemfreq = stats.itemfreq(np.squeeze(hstack_indexs))
top_k = itemfreq[np.argsort(-itemfreq[:,1])][:self.K][:,0]
return top_k | |
0028605d3dddeb3f2bb4 | def into_buffer(self, buf, offset):
self.payload = containerize(exclude_fields(self))
self.parser = MsgExtEvent._parser
self.stream_payload.reset(buf, offset)
return self.pack_into(buf, offset, self._build_payload) | |
0028a3e5bf631404ea45 | def main(
ctx: click.Context,
include: str,
exclude: str,
src: List[PathLike],
output: PathLike,
verbose: bool,
):
log_level = logging.DEBUG if verbose else logging.INFO
logging.basicConfig(format="[%(levelname)s] %(message)s", level=log_level)
if output == "-":
outstream = ... | |
0028a6fcd4b38cf344d3 | def refine(self, REFINE_RATIO, hmin, hmax):
print "refining %.2f%% of max error" % (REFINE_RATIO * 100)
mesh = self.mesh
V = FunctionSpace(mesh, "CG", 1)
Hxx = TrialFunction(V)
Hxy = TrialFunction(V)
Hyy = TrialFunction(V)
phi = TestFunction(V)
U = project(self.U_ex, V)
... | |
0028cbe6c8b4c2c2e94b | def rezoneActors(self):
#
# Start with a list of actors to find homes for based on any that
# were not in any zones at all
moved = self.unzoned_actors
self.unzoned_actors = set()
#
# Find all the actors that are no longer in the right zone
# and remove the... | |
0028e2623e76c7fecf2e | def _is_positive(self, x):
return x>=_eps and (not math.isinf(x)) and (not math.isnan(x)) | |
002909b47b15dfe3976e | def list_dir(path):
return gcs.listbucket(_abs_filename(path)) | |
002915ff8f9fe6ecfb08 | def gameChoice():
global AIRPORT_SIGN, PARIS, ROME, KICKED_GANGLEADER, ZURICH, \
CRACK_CONCRETE, OPEN_CHEST, ZU_BOOK, BERLIN, BE_WALL, LONDON, LO_CONTAINER, \
THAILAND, BUNGALOW_DOOR, ENDGAME
invFile3 = open("inv.data")
showInv3 = invFile3.readlines()
choice = input("--> ")
#gamestart opt... | |
00291e5a47f1a1440086 | def getSourceGraph(self, refresh=False):
if refresh or not self._sourceGraph:
self._sourceGraph = self._getRelationGraph(em.RELATION_SOURCE, refresh)
return self._sourceGraph | |
00292036c89d727cfb38 | def python_value(self): | |
0029387dd2bd89fec4b3 | def syncStatus(card, sync=None):
req = {"req": "hub.sync.status"}
if sync is not None:
req["sync"] = sync
return card.Transaction(req) | |
00294e617a58362bea3f | def get_latlong(query):
r = requests.get("https://maps.googleapis.com/maps/api/geocode/json?"
"address={}".format(query))
location = r.json()['results'][0]['geometry']['location']
return location | |
002981a3b20d8067a0b0 | def send( self, message ):
self.target.messageReceived( message ) | |
002983c0e0fda900b1de | def is_blocking(self) -> bool:
raise NotImplementedError() | |
00299093061b0d0cb4b8 | def formatExceptionInfo(self, maxTBlevel=5):
cla, exc, trbk = sys.exc_info()
excName = cla.__name__
try:
excArgs = exc.__dict__["args"]
except KeyError:
excArgs = "<no args>"
excTb = traceback.format_tb(trbk, maxTBlevel)
return (excName, excArgs, e... | |
002993afc81211e0572c | def ltrmin(perm):
n = perm.__len__()
L = []
minval = len(perm) + 1
for idx, val in enumerate(perm):
if val < minval:
L.append(idx)
minval = val
return L | |
0029a2a1b9928c87cc73 | def active_element(self):
return self.browser.switch_to_active_element() | |
0029dbf4390861b09ef4 | def contract(self, date):
raise NotImplementedError("Should implement 'contract()'") | |
002a1931b9113447f57e | def _set(self, schema):
if isinstance(schema, CommonSchema):
self.__spl_type = False
self.__schema = schema.schema()
else:
self.__spl_type = schema.__spl_type
self.__schema = schema.__schema | |
002a358abf274382b91f | def set_freq(self, freq):
self.stream.write("FREQ {} HZ\n".format(freq).encode()) | |
002a497cf2849627c351 | def attach_permission(role_name, policy_name, policy_doc):
# Create the policy
# If the policy with policy name $policy_name already exists,
# then we need to delete it first
# Note: you need to make sure that you do not have a policy
# with $policy_name in production, because we will delete it
... | |
002a51c55e5a540e98d9 | def mk_xor(s, a, b):
return (~s | a | b) & (~s | ~a | ~b) & (s | ~a | b) & (s | a | ~b) | |
002a52a91355d3363692 | def get_customer_data(self):
customer = {}
signals.customer_data_query.send(sender=type(self), instance=self, customer=customer)
return customer | |
002a8665df309877b3f9 | def map_column_names_of_dataframe(self, df):
map_dict = self.settings.pmap.get_parameter_mapping(df.columns.tolist())
return self._rename_columns_of_dataframe(df, map_dict) | |
002aa5850d7826b1ce57 | def test_s1_norm_werner(n, a):
rho = werner(n, a)
# See:
# N. Johnston.
# Norms and Cones in the Theory of Quantum Entanglement.
# PhD thesis (arXiv:1207.1479)
# Proposition 5.2.10 and Table 5.1
expected = (1 + abs(min(0, a))) / (n * (n - a))
lower_bound, upper_bound = sk_operator_norm(... | |
002abafe6c33769a6d32 | def load_latest_200_tweets():
for status in tweepy.Cursor(api.user_timeline).items(200):
tweets_list.append(status._json) | |
002ad34691722bbbcad1 | def test_tags_manager(self):
tags_eq(self.untagged_question, []) | |
002aee982a3ba1546411 | def warning(*objs):
print("WARNING: ", *objs, file=sys.stderr) | |
002b038bed0372a413e8 | def command_down(self, char):
self.keystroke_convenience(char, command_down=True) | |
002b142e41a0ed1404f7 | def getpeername(self):
return self.__proxypeername | |
002b63bff8d38264ddb2 | def correct_dimension(data):
new_data = data
if new_data.ndim == 0:
new_data.shape += (1, 1)
elif new_data.ndim == 1:
new_data.shape += (1,)
return new_data | |
002b7c9fd9b6d35d384e | def gauss2D_FIT(xy, x0, y0, sigma_x, sigma_y):
x0 = float(x0)
y0 = float(y0)
x = xy[0]
y = xy[1]
g2 = np.exp(
-((x - x0) ** 2 / (2 * sigma_x ** 2) + (y - y0) ** 2 / (2 * sigma_y ** 2))
)
g2_norm = g2 / np.max(g2.flatten())
return g2_norm.reshape(-1) | |
002b7da33af051dad7d7 | def test_recovery(Pd):
from os import path
from matdb.utility import symlink, chdir
from glob import glob
Pd.setup()
Pd.execute(env_vars={"SLURM_ARRAY_TASK_ID":"1"})
files = ["vasprun.xml", "OUTCAR"]
folder = path.join(reporoot, "tests", "data", "Pd", "manual_recover")
with chdir(folde... | |
002b982ad1b6017e10b3 | def calculate_weights(mc, word):
weights = np.array(
list(mc[word].values()),
dtype=np.float64)
weights /= weights.sum()
return weights | |
002bbdad3f4605cfa60b | def test_type_sanity():
assert Types.INIT_REQ == 1 | |
002bf28b1c5a9902e08f | def encode_docs(documents,token_vectors,num_dimensions_word2vec,max_len):
vectors_sequences = np.zeros(shape=(len(documents),max_len,num_dimensions_word2vec),dtype="float16")
for document_ind,document in tqdm(enumerate(documents)):
tokens = document.split()
for i in range(min(max_len,len(tokens))):
to... | |
002c0891cab40b6ce880 | def model_evaluate(model_type, parameter_set, X, y, num_fold):
best_cv_acc = 0
best_parameter = 500
for hidden_size in parameter_set:
if model_type == "CNN":
model_unfitted = CNN_model_define(filter_size, window_size, strides, hidden_size)
if model_type == "DCNN":
mod... | |
002c13ab4a38c40a9771 | def _allocate_workspace(self,solution):
import numpy as np
state = solution.state
num_eqn,num_aux,num_waves,num_ghost,aux = state.num_eqn,state.num_aux,self.num_waves,self.num_ghost,state.aux
#The following is a hack to work around an issue
#with f2py. It involves wastefully ... | |
002c31d80a84c41ff1df | def xy(self) -> List[Tuple]:
xy = []
for bezierCurve in self.bezierCurves:
xy.extend(bezierCurve.xy)
xy = list(set(xy)) # remove duplicates
return xy | |
002c39a4c17de8a3777a | def welcome_user():
return "welcome" | |
002c7214d601982c9cc8 | def __do_rpc(self, rpc):
if not self.connected:
raise ImpalaBeeswaxException("Not connected", None)
try:
return rpc()
except BeeswaxService.BeeswaxException as b:
raise ImpalaBeeswaxException(self.__build_error_message(b), b)
except TTransportException as e:
self.connected = Fals... | |
002c8d3b148aaa0fb73c | def save_figure(self):
self.figure_canvas.save() | |
002c910fc560c0b3d738 | def Init(self, *args, **kwargs):
pass | |
002ca1848f362448fbe9 | async def _event_details(self, ctx, event_id: str):
with DbConn() as c:
c.execute("""
SELECT id, date, name, location, description, owner
FROM events
WHERE id = ?
""",
event_id)
... | |
002ca9aea67b85cd2e6d | def print_board(brd):
for i in range(len(brd)):
if i % 3 == 0 and i != 0:
print("-----------------------")
for j in range(len(brd[0])):
if j % 3 == 0 and j != 0:
print(" | ", end="")
if j == 8:
print(brd[i][j])
else:
... | |
002cb39ae18418f332c3 | def print_index():
header = """---
layout: default
title: Morbergs receptsamling
nav_order: 1
---
"""
print(header)
print("# Morbergs receptsamling\n")
dirs = get_dirs()
print_categories(dirs) | |
002cc45a42ad4d5cab89 | def setup_app(self):
environment = os.environ.copy()
environment.setdefault("app_name", uuid.uuid4().hex)
self.app = get_application(**environment)
@self.app.before_request
def before_request_handler():
return before_request()
# construct response class so w... | |
002ccfec3d0d1f83ed14 | def create_ufd_network_file(self, port_name, config_parser_instance=None):
file_name = '/etc/systemd/network/{0}.network'.format(port_name)
with self.switch.ssh.client.open_sftp() as sftp_client:
with sftp_client.open(file_name, 'w') as remote_file:
if config_parser_instance ... | |
002cd2d17ae05eb55422 | def is_unshare(self):
return self._tag == 'unshare' | |
002cec2c9237d9a556c0 | def clear_screen():
if PlatformHolder.is_windows():
os.system('cls')
else:
os.system('clear') | |
002cff85a7f2f3afdc01 | def db():
pass | |
002d14e2fd47a7751f5a | def check_for_available_moves(game_board, grid_size):
filled_box_counter = 0
for row in game_board:
for square in row:
if square != '_':
filled_box_counter += 1
if filled_box_counter == grid_size * grid_size:
return False
else:
return True | |
002d16c90676559bdfbb | def size(self):
return len(self._list) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.