query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Returns a set of all cells in self.cells that are known to be mines, given that the length of the set is equal to the clue count | def MinesKnown(self):
if len(self.cells) == self.count:
return set(self.cells)
else:
return set() | [
"def known_mines(self):\n return {cell for cell in self.cells if len(self.cells)==self.count}",
"def SafesKnown(self):\n if self.count == 0:\n return set(self.cells)\n else:\n return set()",
"def num_mines(self) -> int:\n count = 0\n for row in self:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the set of all cells in self.cells known to be safe. | def SafesKnown(self):
if self.count == 0:
return set(self.cells)
else:
return set() | [
"def MinesKnown(self):\n if len(self.cells) == self.count:\n return set(self.cells)\n else:\n return set()",
"def known_mines(self):\n return {cell for cell in self.cells if len(self.cells)==self.count}",
"def unset_cells(self):\n return (cell for cell in _cells... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
callback function to obtain yaw angle from odometry message | def yaw_from_odom(msg):
orientation_q = msg.pose.pose.orientation
orientation_vec = [orientation_q.x, orientation_q.y, orientation_q.z, orientation_q.w]
(roll, pitch, yaw) = euler_from_quaternion(orientation_vec)
return yaw | [
"def yawAngle(self):\n if self._calibratedYaw is None:\n return self.config.get('yaw', 0)\n else:\n return self._calibratedYaw",
"def yaw(eulers):\n return eulers[2]",
"def _odom_callback(self, data):\n\t\torientation_q = data.pose.pose.orientation\n\t\t\n\t\torientation_l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Featurize all docked structures. | def featurize_job(docked_compounds):
# Instantiate copy of binana vector
binana = Binana()
feature_len = binana_num_features()
feature_vectors = {}
for count, compound in enumerate(docked_compounds):
print "\nprocessing %d-th docked pdb %s" % (count, compound) | [
"def main():\n print \"***************************************************************************************\"\n print \" This test shows how to add StructureContainer objects together \"\n print \" A special test to double-check re-labeling ... add a big container to a 'small' one \"\n print \"******... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a ``networkx.Graph`` from a skeleton DataFrame. | def skeleton_df_to_nx(df, with_attributes=True, directed=True, with_distances=False, virtual_roots=False, root_dist=np.inf):
if directed:
g = nx.DiGraph()
else:
g = nx.Graph()
if with_attributes:
for row in df.itertuples(index=False):
g.add_node(row.rowId, x=row.x, y=row... | [
"def _reorient_skeleton(skeleton_df, root, root_parent=-1, g=None):\n g = g or skeleton_df_to_nx(skeleton_df, False, False)\n assert isinstance(g, nx.Graph) and not isinstance(g, nx.DiGraph), \\\n \"skeleton graph must be undirected\"\n\n edges = list(nx.dfs_edges(g, source=root))\n\n # If the gr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For each node (row) in the given skeleton DataFrame, compute euclidean distance from the node to its parent (link) node. | def calc_segment_distances(df, root_dist=np.inf):
# Append parent (link) columns to each row by matching
# each row's 'link' ID with the parent's 'rowId'.
edges_df = df[['rowId', 'link', *'xyz']].merge(
df[['rowId', *'xyz']], 'left',
left_on='link', right_on='rowId', suffixes=['', '_link'])
... | [
"def distances_from_root(df):\n g = skeleton_df_to_nx(df, directed=False, with_distances=True, virtual_roots=True, root_dist=0.0)\n d = nx.shortest_path_length(g, -1, weight='distance')\n d = pd.Series(d, name='distance').rename_axis('rowId')\n df = df.merge(d, 'left', on='rowId')\n return df",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the distance from the root node(s) to all nodes in the skeleton. Return those distances as a new column in the skeleton DataFrame. All root nodes will be used, as long as they all have virtual root of 1. | def distances_from_root(df):
g = skeleton_df_to_nx(df, directed=False, with_distances=True, virtual_roots=True, root_dist=0.0)
d = nx.shortest_path_length(g, -1, weight='distance')
d = pd.Series(d, name='distance').rename_axis('rowId')
df = df.merge(d, 'left', on='rowId')
return df | [
"def calc_segment_distances(df, root_dist=np.inf):\n # Append parent (link) columns to each row by matching\n # each row's 'link' ID with the parent's 'rowId'.\n edges_df = df[['rowId', 'link', *'xyz']].merge(\n df[['rowId', *'xyz']], 'left',\n left_on='link', right_on='rowId', suffixes=['', ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a DataFrame from and SWC file. The 'node_type' column is discarded. | def skeleton_swc_to_df(swc):
if hasattr(swc, 'read'):
swc = swc.read()
else:
assert isinstance(swc, str)
if swc.endswith('.swc'):
with open(swc, 'r') as f:
swc = f.read()
cols = ['rowId', 'node_type', 'x', 'y', 'z', 'radius', 'link']
lines = swc.split... | [
"def read_feat(file):\n df = pd.read_csv(file, sep=\" \", names=[\"node_id\"] + list(range(0, 1364)))\n return df",
"def create_df(file, df_type):\n try:\n date_id = file.split(\"/\")[-1].split(\".\")[0]\n report_timestamp = datetime.strptime(date_id, \"%m-%d-%y\").strftime(\"%Y-%m-%dT%H:%M... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an SWC file from a skeleton DataFrame. | def skeleton_df_to_swc(df, export_path=None):
df = df.copy()
df['node_type'] = 0
df = df[['rowId', 'node_type', 'x', 'y', 'z', 'radius', 'link']]
swc = "# "
swc += df.to_csv(sep=' ', header=True, index=False)
if export_path:
with open(export_path, 'w') as f:
f.write(swc)
... | [
"def create_sjr_sframe():\n sjr_sf = tc.SFrame()\n for p in os.listdir(DATASETS_SJR_DIR):\n if not p.endswith(\".csv\"):\n continue\n y = int(re.match(r'.*([1-3][0-9]{3})', p.split(os.path.sep)[-1]).group(1))\n sf = tc.SFrame.read_csv(\"%s/%s\" % (DATASETS_SJR_DIR, p))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attempt to repair a fragmented skeleton into a single connected component. Rather than a single tree, skeletons from neuprint sometimes consist of multiple fragments, i.e. multiple connected components. That's due to artifacts in the underlying segmentation from which the skeletons were generated. In such skeletons, th... | def heal_skeleton(skeleton_df, max_distance=np.inf, root_parent=None):
if max_distance is True:
max_distance = np.inf
if not max_distance:
max_distance = 0.0
if root_parent is None:
root_parent = -1
else:
# Fast path to exit early if we can easily check the number of ro... | [
"def extract_graph_from_skeleton(sk): \n #used/unsused\n sk_used = np.zeros_like(sk)\n sk_unused = np.copy(sk)\n #root node\n root_position = findroot(sk)\n print('root_position',root_position)\n root = Branch(pixels=[root_position],name='root')\n setvalue(sk_used,root_position,1)\n setva... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replace the 'link' column in each row of the skeleton dataframe so that its parent corresponds to a depthfirst traversal from the given root node. | def _reorient_skeleton(skeleton_df, root, root_parent=-1, g=None):
g = g or skeleton_df_to_nx(skeleton_df, False, False)
assert isinstance(g, nx.Graph) and not isinstance(g, nx.DiGraph), \
"skeleton graph must be undirected"
edges = list(nx.dfs_edges(g, source=root))
# If the graph has more th... | [
"def upsample_skeleton(skeleton_df, max_segment_length):\n if len(skeleton_df) in (0, 1) or (skeleton_df['link'] == -1).all():\n # Can't upsample a skeleton with no child-parent segments\n return skeleton_df\n\n seg_df = _skeleton_segments(skeleton_df)\n seg_df = seg_df.loc[seg_df['length'] >... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change the root node of a skeleton. In general, the root node of the skeletons stored in neuprint is not particularly significant, so the directionality of the nodes (parent to child or viceversa) on any given neuron branch is arbitrary. This function allows you to pick a different root node and reorient the tree with ... | def reorient_skeleton(skeleton_df, rowId=None, xyz=None, use_max_radius=False):
assert rowId != 0, \
"rowId is never 0 in NeuTu skeletons"
assert bool(rowId) + (xyz is not None) + use_max_radius == 1, \
"Select either a rowId to use as the new root, or a coordinate, or use_max_radius=True"
... | [
"def _reorient_skeleton(skeleton_df, root, root_parent=-1, g=None):\n g = g or skeleton_df_to_nx(skeleton_df, False, False)\n assert isinstance(g, nx.Graph) and not isinstance(g, nx.DiGraph), \\\n \"skeleton graph must be undirected\"\n\n edges = list(nx.dfs_edges(g, source=root))\n\n # If the gr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the table of childtoparent points and segment lengths. | def _skeleton_segments(skeleton_df):
segment_df = skeleton_df.merge(skeleton_df[['rowId', 'link', *'xyz', 'radius']],
'inner',
left_on='link',
right_on='rowId',
suffixes=['', '... | [
"def n_segments(tree):\n return sum(1 for _ in tr.isegment(tree))",
"def get_distances_section(self):\n table = {}\n\n row_length = (self.height // MyCommon.Constants.NUM_SECTIONS) + 1 ## + 1 TO COUNT LAST ITEM FOR RANGE\n col_length = (self.width // MyCommon.Constants.NUM_SECTIONS) + 1\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert new nodes into a skeleton make it "higher resolution". For all childparent segments with length greater than the given maximum length, subdivide each segment into N smaller equallength segments, such that all of the new segments are (ideally) not larger than the given max. The 'radius' column is interpolated bet... | def upsample_skeleton(skeleton_df, max_segment_length):
if len(skeleton_df) in (0, 1) or (skeleton_df['link'] == -1).all():
# Can't upsample a skeleton with no child-parent segments
return skeleton_df
seg_df = _skeleton_segments(skeleton_df)
seg_df = seg_df.loc[seg_df['length'] > max_segmen... | [
"def heal_skeleton(skeleton_df, max_distance=np.inf, root_parent=None):\n if max_distance is True:\n max_distance = np.inf\n\n if not max_distance:\n max_distance = 0.0\n\n if root_parent is None:\n root_parent = -1\n else:\n # Fast path to exit early if we can easily check t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attach a neuron's synapses to its skeleton as new skeleton nodes. Synapses are attached to their nearest skeleton node (in euclidean terms). | def attach_synapses_to_skeleton(skeleton_df, synapses_df):
skeleton_df = skeleton_df.copy(deep=False).reset_index(drop=True)
synapses_df = synapses_df.copy(deep=False).reset_index(drop=True)
skeleton_df['structure'] = 'neurite'
synapses_df['structure'] = synapses_df['type']
synapses_df['radius'] = ... | [
"def __connect(self):\n #self.outputNeuron = outputNeuron\n #self.inputNeuron = inputNeuron\n self.outputNeuron.addInputSynapse(self)\n self.inputNeuron.addOutputSynapse(self)",
"def star_neuron(wing_number=3,\n node_on_each_wings=4,\n spherical=False,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calls coach user api | def http_request_coachuser(self, data):
response_data_json = self._http_request(
method='POST',
url_suffix=URL_SUFFIX_COACH_USER,
json_data=data,
data=data,
)
return response_data_json | [
"def yo_user(self, username, **kwargs):\n username = username.upper()\n youser_data = {\"api_token\": self.token, \"username\": username}\n for kw in kwargs:\n youser_data.update( { kw:kwargs[kw] } )\n youser_url = \"https://api.justyo.co/yo/\"\n youser = urlfetch.fetch... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sigmoid function for use with Numpy for CPU evaluation. | def sigmoid(x):
return 1 / (1 + np.exp(-x)) | [
"def sigmoid(X):\n\n pass",
"def sigmoid(x):\n\t\n\t# Returning sigmoided array.\n\treturn 1 / (1 + np.exp(-x))",
"def sigmoid_array(x): \n\treturn 1 / (1 + np.exp(-x))",
"def sigmoid_numpy(x):\n\n s = 1/(1+np.exp(-x))\n\n return s",
"def sigmoid(t):\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DIOU nonmaximum suppression. diou = iou square of euclidian distance of box centers / square of diagonal of smallest enclosing bounding box | def diou_nms(dets, iou_thresh=None):
iou_thresh = iou_thresh or 0.5
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
order = scores.argsort()[::-1]
center_x = (x1 + x2) / 2
center_y = (y1 + y2) / 2
keep = []
while order.... | [
"def box_diou(boxes):\n # get box coordinate and area\n x = boxes[:, 0]\n y = boxes[:, 1]\n w = boxes[:, 2]\n h = boxes[:, 3]\n areas = w * h\n\n # check IoU\n inter_xmin = np.maximum(x[:-1], x[-1])\n inter_ymin = np.maximum(y[:-1], y[-1])\n inter_xmax = np.minimum(x[:-1] + w[:-1], x[-... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates detections with model outputs and anchors. | def _generate_detections(cls_outputs, box_outputs, anchor_boxes, indices,
classes, image_id, image_scale, num_classes,
max_boxes_to_draw, nms_configs):
anchor_boxes = anchor_boxes[indices, :]
scores = sigmoid(cls_outputs)
# apply bounding box regression to anchors... | [
"def generate_detections(det_model,seq_dir,conf_thresh,bs,imdim):\n\n # get model predictor object \n model,predictor = load_model(float(conf_thresh),det_model)\n detector = Detector(model,predictor)\n\n # detection list\n det_list = []\n #print(\"Processing %s\" % sequence)\n image_filen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns trend objects. Expects the geological area for which the trends are to be fetched | def get_trends(self, geo_location):
api_url = t_const.API_TREND + "?id=%s"
json_str = self.__https_obj.make_req(api_url % (geo_location), "GET", "", self.__token)
res_data = json.loads(json_str.decode('UTF-8'))
trends = res_data[0]['trends']
# return a list of trend objects
... | [
"def getTrends(self, geoID=23424977):\n trends = self.api.trends_place(geoID)\n self.helper.dumpJson(\"trends\", str(datetime.date.today()) + \".json\",\n trends)",
"def google_trends(term: str) -> dict:\n pytrend = TrendReq()\n pytrend.build_payload(kw_list... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize object with a trend | def __init__(self, json_data):
self._trend = json_data | [
"def _init_trend_array(self):\n\t\tself.T = [sum([self.X[i + self.q] - self.X[i]\n\t\t for i in range(self.q)]) / (self.q ** 2)]",
"def __init__(self):\n self.min_time = 6.0*60.0*60.0\n self.min_temp = -10.0\n self.max_temp = 10.0\n self.period = 60.0*60.0*24.0",
"def _... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get name if the trend. | def _get_name(self):
return self._trend['name'] | [
"def name(self):\n return super(Treant, self).name",
"def _get_name(self) -> \"std::string\" :\n return _core.DataHub__get_name(self)",
"def get_name(self):\n return self.__name_army",
"def trend_description(self) -> Optional[str]:\n return TREND_DESCRIPTIONS[self._trend]",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the object with the tweet data(json) | def __init__(self, json_data):
self._tweet = json_data | [
"def initWithRawData(self, tweet):\n\n for attr in self.desired_features['tweet']:\n if attr in tweet.keys():\n setattr(self, attr, tweet[attr])\n\n if 'preprocessed_text' in self.desired_features['tweet']:\n self.preprocessText(tweet['text'])",
"def parse_tweet(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns location of the user | def _get_location(self):
return self._get_user()['location'] | [
"def get_user_location(user):\n if user and user.is_authenticated(): \n prof = user.get_profile()\n if prof:\n return prof.location if prof.location else \\\n prof.supply_point.location if prof.supply_point \\\n else None",
"def location(self) -> str:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gives the count of retweets | def _get_retweets(self):
return int(self._tweet['retweet_count']) | [
"def _setRetweetCount(self):\n retweetCount = 0\n if \"retweeted_status\" in self._tweet:\n retweetCount = self._tweet[\"retweeted_status\"][\"retweet_count\"]\n return retweetCount",
"def retweetCount(self):\n return self._retweetCount",
"def __get_count_tweets(data, batc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
assemble file content, then pass it to hasher via temp file Either str or bytearray can be passed to outputText. Since we need to write this to a file and calculate a SHA1, we need bytes. For unicode servers, we have a charset specified which is used to convert a str to bytes. For a nonunicode server, we will have spec... | def outputText(self, h):
if self.p4.charset:
try:
# self.p4.__convert() doesn't work correctly here
if type(h) == str:
b = getattr(self.p4, '__convert')(self.p4.charset, h)
else:
b = getattr(self.p4, '__convert')... | [
"def _get_log_file_data_as_encoded_content():\n with io.BytesIO() as fp:\n with tarfile.open(fileobj=fp, mode='w:gz') as tar:\n for f in OUTPUT_FILES:\n tar.add(f)\n\n fp.seek(0)\n return base64.encode_as_bytes(fp.getvalue())",
"def __bytes__(self):\n with ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get moves for which reports should be generated Moves are grouped by stock transfer and by product, and assigned a reporting name based on the order within the stock transfer. | def move_report_list(self, _doc, moves):
return (
product_moves.with_context(default_name="%04d" % index)
for _pick, pick_moves in moves.groupby(lambda x: x.picking_id)
for index, (_product, product_moves) in enumerate(
pick_moves.groupby(lambda x: x.product_i... | [
"def _my_prepare_stock_moves(self, picking, qty, warehouse_id):\n self.ensure_one()\n res = []\n if self.product_id.type not in ['product', 'consu']:\n return res\n\n price_unit = self._get_stock_move_price_unit()\n\n template = {\n 'name': self.name or '',\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test exponential learning rate schedule | def test_exp_schedule(backend):
lr_init = 0.1
decay = 0.01
sch = ExpSchedule(decay)
for epoch in range(10):
lr = sch.get_learning_rate(learning_rate=lr_init, epoch=epoch)
assert np.allclose(lr, lr_init / (1. + decay * epoch)) | [
"def test_cyclic_exp_lr(self):\n gold = [0.1,0.26200002,0.39159995,0.49366,0.5723919,0.631441,0.48263744,0.35828033,0.25496817,0.1697357,0.1,\n 0.15648592,0.20167467,0.23726073,0.2647129,0.285302,0.23341745,0.19005677,0.15403408,0.12431534,0.1,\n 0.1196954,0.13545176,0.14785986,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Changes TERM to new value; useful for overriding terminal defaults. | def term(self, term):
self._env['TERM'] = term | [
"def SetTerminal(self, isTerminal):\n self.terminalNode = isTerminal",
"def terminal_mode( self ):\r\n self.mode = \"Terminal\"\r\n\r\n self.port = \"COM5\" #\r\n self.baudrate = 19200 # 9600 19200 38400, 57600, 115200, 128000 and 256000\r\n\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get number of buildings in a neighborhood | def get_num_buildings(nname):
engine = get_sql_engine()
building_stats = text(
"""
SELECT
count(v.*) as num_buildings
FROM vacant_buildings as v
JOIN philadelphia_neighborhoods as n
ON ST_Intersects(v.geom, n.geom)
WHERE n.neighborhood_name = :nname
... | [
"def neighborhood_size(G, v):\n return len([u for u, v1 in G if v1 == v])",
"def num_building(building_type: BuildingType, ai_stat: AI_GameStatus, count_under_construction=False):\n value = 0\n for b in ai_stat.map.building_list:\n if b.type == building_type:\n if count_under_constructi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all buildings for a neighborhood | def get_neighborhood_buildings(nname):
engine = get_sql_engine()
vacant_buildings = text(
"""
SELECT
"ADDRESS" as address,
"BLDG_DESC" as building_description,
"OPA_ID" as opa_id,
v.geom as geom
FROM vacant_buildings as v
JOIN phila... | [
"def get_neighborhoods(state):\n\n neighborhoods = set()\n \n listings = Listing.query.filter(Listing.address.like('%{}%'.format(state))).all()\n for listing in listings: \n neighborhoods.add(listing.neighborhood)\n\n return neighborhoods",
"def get_neighborhood_listings(\n self, neig... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A context manager that yields keyboard events. The context object is a generator that yields the actual events. An event is the tuple ``(key, pressed)``. The generator is stopped whenever the timeout is triggered. If this happens, ``None`` will be yielded as the last event. | def events(self, timeout=5.0):
def generator(q):
while True:
try:
yield q.get(timeout=timeout)
except queue.Empty:
yield None
break
# Yield the generator and allow the client to capture events
... | [
"def prepare_raw_getkey():\n #this is weird - pygame turns off keyboard repeat by default, which you can re-enable\n #by setting a delay in ms, but \"what the system normally does\" is not an option.\n #it seems like 150ms delay and 15 keys-per-second is normalish.\n pygame.key.set_repeat(150, 1000 / 15... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Yields all events necessary to type a string. | def string_to_events(self, s):
for c in s:
yield (c, True)
yield (c, False) | [
"def translate(self, string, regex=re.compile(r'%\\((\\w+)\\)s')):\r\n substream = None\r\n\r\n def yield_parts(string):\r\n for idx, part in enumerate(regex.split(string)):\r\n if idx % 2:\r\n yield self.values[part]\r\n elif part:\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that a single key can be tapped | def test_tap(self):
self.notify('Press and release "a"')
self.assert_keys(
'Failed to register event',
('a', True), ('a', False)) | [
"def tap_and_check(\n self, key: str, keysym: str, group: int = BASE_GROUP, level: int = BASE_LEVEL\n ) -> xkbcommon.Result:\n r = self.tap(key)\n assert r.group == group\n assert r.level == level\n assert r.keysym == keysym\n # Return the result for optional further tes... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that the enter key can be tapped | def test_enter(self):
self.notify('Press <enter>')
self.assert_keys(
'Failed to register event',
(pynput.keyboard.Key.enter, True)) | [
"def press_kp_enter():\n\tif pygame.key.get_pressed()[pygame.K_KP_ENTER]:\n\t\treturn True",
"def press_enter():\n\tif pygame.key.get_pressed()[pygame.K_RETURN]:\n\t\treturn True",
"def press_enter():\n return input('Press ENTER to continue...')",
"def _enter_key( self, event ) :\n w = event.widget\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that the modifier keys can be tapped | def test_modifier(self):
from pynput.keyboard import Key
for key in (
(Key.alt, Key.alt_l, Key.alt_r),
(Key.ctrl, Key.ctrl_l, Key.ctrl_r),
(Key.shift, Key.shift_l, Key.shift_r)):
self.notify('Press <%s>' % key[0].name)
self.assert_k... | [
"def test_modifier_and_normal(self):\n from pynput.keyboard import Key\n self.notify('Press a, <ctrl>, a')\n self.assert_keys(\n 'Failed to register event',\n ('a', True),\n ('a', False),\n ((Key.ctrl, Key.ctrl_l, Key.ctrl_r), True),\n ((Ke... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that the modifier keys do not stick | def test_modifier_and_normal(self):
from pynput.keyboard import Key
self.notify('Press a, <ctrl>, a')
self.assert_keys(
'Failed to register event',
('a', True),
('a', False),
((Key.ctrl, Key.ctrl_l, Key.ctrl_r), True),
((Key.ctrl, Key.c... | [
"def test_modifier(self):\n from pynput.keyboard import Key\n for key in (\n (Key.alt, Key.alt_l, Key.alt_r),\n (Key.ctrl, Key.ctrl_l, Key.ctrl_r),\n (Key.shift, Key.shift_l, Key.shift_r)):\n self.notify('Press <%s>' % key[0].name)\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that options are correctly set on OSX | def test_options_darwin(self):
self.assertTrue(
pynput.keyboard.Listener(
darwin_test=True,
win32_test=False,
xorg_test=False)._options['test']) | [
"def test_options_win32(self):\n self.assertTrue(\n pynput.keyboard.Listener(\n darwin_test=False,\n win32_test=True,\n xorg_test=False)._options['test'])",
"def test_get_options(self):\n pass",
"def validate_options():\n if os.environ.get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that options are correctly set on Windows | def test_options_win32(self):
self.assertTrue(
pynput.keyboard.Listener(
darwin_test=False,
win32_test=True,
xorg_test=False)._options['test']) | [
"def test_options_darwin(self):\n self.assertTrue(\n pynput.keyboard.Listener(\n darwin_test=True,\n win32_test=False,\n xorg_test=False)._options['test'])",
"def _check_option_support(options):\n for opt in options:\n if _is_option_supporte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorate methods that requires the user be logged in. | def authenticated(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if not self.current_user:
self.write({'status_code':404, 'error_msg':'not login'})
return
return method(self, *args, **kwargs)
return wrapper | [
"def requires_logged_in(func):\n def ret_fn(*args):\n \"\"\"\n wrapper function\n :param args: argument for decorated function\n :return: return decorated function return values\n \"\"\"\n self = args[0]\n if not self.is_logged_in:\n self.try_login(rais... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorate methods that access ip restricted. | def access_restricted(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
app_log.info("http access %s", self.request.remote_ip)
return method(self, *args, **kwargs)
return wrapper | [
"def local_or_whitelist_only(f):\n def decorator(*args, **kwargs):\n if not request.headers.getlist(\"X-Forwarded-For\"):\n ip = request.remote_addr\n else:\n ip = request.headers.getlist(\"X-Forwarded-For\")[0]\n if not ip == \"127.0.0.1\" and ip not in app.config[\"IP... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorate methods that request source signature verify. | def request_verify(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
params = []
for key in sorted(args):
if key == 'sign' or len(args[key]) == 0:
continue
params.append( '='.join([key, args[key][0]]) )
sign = args['sign'][0]
pre_sign_str = '&'.join(param... | [
"def signature_checking(self,meta):\n if self.vertification(meta):\n pass\n else:\n raise Exception('Incorrect Signature')",
"def verify(self, key, msg, sig): # pragma: no cover\n raise NotImplementedError()",
"def _check_signature(self, request, key):\n superc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return an open file handle to read the given external object. | def read_external_object(
self, doi_or_unique_name: str, title: str, component: Optional[str] = None,
) -> IOBase:
kwds = dict(doi_or_unique_name=doi_or_unique_name, title=title)
if component is not None:
kwds["component"] = component
return self.file_api.open_for_read(**... | [
"def open(self, oid):\n return open(self.path(oid), 'rb')",
"def get_file_obj(path: str) -> TextIOWrapper:\n return open(path, 'r')",
"def file_object(self) -> BufferedReader:\n return self.reader.file_object",
"def get_file_object(self):\n\n if self.file_obj == None:\n self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if tweet is filtered or not | def tweet_filter(self, tweet):
for rule in self.tf:
if not self.tf[rule](tweet):
return False
return True | [
"def _filter_tweet(self, tweet):\n if \"extended_tweet\" in tweet.keys():\n tweet[\"text\"] = tweet[\"extended_tweet\"][\"full_text\"]\n elif \"retweeted_status\" in tweet.keys() and \"full_text\" in tweet[\"retweeted_status\"].keys():\n tweet[\"text\"] = \"RT \" + tweet[\"retwee... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print single tweet on the wall | def print_tweet(self, tweet):
self.printer.echo('{}'.format(
tweet.get_created().strftime(self.outformat)), nl=False
)
self.printer.echo(' ({})'.format(tweet.get_url()))
self.printer.echo(tweet.get_author_name(), nl=False)
self.printer.echo(' [{}]'.format(tweet.get_au... | [
"def print_tweet(tweet):\n text = colorize(tweet, hashtag_wrap, mention_wrap, url_wrap)\n text = Markup.unescape(text)\n created_at = time_filter(tweet['created_at'])\n\n click.echo('------')\n click.secho('ID: {}'.format(tweet['id']), fg='green')\n click.secho(tweet['user']['name'], fg='blue', bo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Highlight parts of tweet by going thru its entities | def tweet_highlighter(self, tweet):
text = tweet.get_text()
result = ""
entities = []
for hashtag in tweet.get_entities_of_type('hashtags'):
entities.append(
(hashtag['indices'][0], hashtag['indices'][1],
self.printer.style(
... | [
"def colorize(tweet, hashtag_wrap, mention_wrap, url_wrap):\n text = tweet['text']\n\n entities = tweet['entities']['hashtags'] + tweet['entities'][\n 'user_mentions'] + tweet['entities']['urls']\n entities.sort(key=lambda e: e['indices'][0])\n\n shift = 0\n for entity in entities:\n te... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simple signal handler to say good bye to the user | def signal_handler(sig, frame):
print('\nBye! See you soon...')
sys.exit(0) | [
"def signal_handler(self, signum, frame):\n exit(0)",
"def signal_handler(signum, frame):\n\n raise ProgramKilledError",
"def quit_signal(self):\n\t\tprint 'Emitted a quit signal'",
"def signal_handler(sig_num, frame):\n\n global exit_flag\n if sig_num == signal.SIGINT:\n logger.warning... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Output polarity scores for a text using Vader approach. | def polarity(text):
vader_analyzer = SentimentIntensityAnalyzer()
return (vader_analyzer.polarity_scores(text)) | [
"def print_polarity_from_input(quest, text):\n if quest == 'naive':\n blob = Naive_Analysis(text).sentiment\n return blob\n #this will be: Sentiment(classification='pos', p_pos=0.5702702702702702, p_neg=0.4297297297297299)\n else:\n blob = TextBlob(text).sentiment\n return b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the active policy when MSVC is not found. | def msvc_get_notfound_policy():
debug(
'policy.symbol=%s, policy.value=%s',
repr(_MSVC_NOTFOUND_POLICY_DEF.symbol), repr(_MSVC_NOTFOUND_POLICY_DEF.value)
)
return _MSVC_NOTFOUND_POLICY_DEF.symbol | [
"def msvc_get_scripterror_policy():\n debug(\n 'policy.symbol=%s, policy.value=%s',\n repr(_MSVC_SCRIPTERROR_POLICY_DEF.symbol), repr(_MSVC_SCRIPTERROR_POLICY_DEF.value)\n )\n return _MSVC_SCRIPTERROR_POLICY_DEF.symbol",
"def is_policy(self):\n return self._policy",
"def promisc_mo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the default policy when msvc batch file execution errors are detected. | def msvc_set_scripterror_policy(MSVC_SCRIPTERROR_POLICY=None):
global _MSVC_SCRIPTERROR_POLICY_DEF
prev_policy = _MSVC_SCRIPTERROR_POLICY_DEF.symbol
policy = MSVC_SCRIPTERROR_POLICY
if policy is not None:
_MSVC_SCRIPTERROR_POLICY_DEF = _msvc_scripterror_policy_lookup(policy)
debug(
... | [
"def set_execution_policy_to_restrict(self):\n code_status = self.session.run_ps('%s restricted' % SET_EXECUTION_POLICY).status_code\n return SUCCESSFUL if code_status == 0 else ERROR",
"def set_policy(self, policy):\n self._policy = 'custom'\n self._P = policy",
"def _set_transaction_safety... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the active policy when msvc batch file execution errors are detected. | def msvc_get_scripterror_policy():
debug(
'policy.symbol=%s, policy.value=%s',
repr(_MSVC_SCRIPTERROR_POLICY_DEF.symbol), repr(_MSVC_SCRIPTERROR_POLICY_DEF.value)
)
return _MSVC_SCRIPTERROR_POLICY_DEF.symbol | [
"def msvc_set_scripterror_policy(MSVC_SCRIPTERROR_POLICY=None):\n global _MSVC_SCRIPTERROR_POLICY_DEF\n\n prev_policy = _MSVC_SCRIPTERROR_POLICY_DEF.symbol\n\n policy = MSVC_SCRIPTERROR_POLICY\n if policy is not None:\n _MSVC_SCRIPTERROR_POLICY_DEF = _msvc_scripterror_policy_lookup(policy)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Detects sentiment in the text. | def detect_sentiment(text):
document = language.types.Document(
content=text,
type=language.enums.Document.Type.PLAIN_TEXT)
sentiment = client.analyze_sentiment(document).document_sentiment
return sentiment.score, sentiment.magnitude | [
"def get_sentiment(text):\n response = requests.post(settings.SENTIMENT_ANALYSIS_API, data={\n 'text': text\n })\n return response.json()",
"def extract_sentiment(text):\n text = TextBlob(text)\n return text.sentiment.polarity",
"def sentiment_analysis_by_text(self,tweet):\n blob = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
How to do basic cleaning up of the text in each paragraph | def cleanparagraph(self, text):
text = cleantext(text)
text = text.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ')
text = ' '.join(text.split()).strip()
return text | [
"def cleanup(self):\n text = ''\n try:\n paragraphs = self.text.split('\\n')\n except AttributeError:\n return text\n\n for par in paragraphs:\n par = par.strip()\n if par == '':\n continue\n\n par = RE_SPACES.sub(' ',... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert collected data to paragraphs | def paragraphs(self):
pars = []
for par in self.data:
if len(par) > 0:
text = self.cleanparagraph(''.join(par)).strip()
if text:
pars.append(text)
return pars | [
"def get_paragraph_data(html_soup):\n polluted_text = str(soup.find_all(\"p\"))\n text_soup = BeautifulSoup(polluted_text)\n return text_soup.get_text()",
"def generate_paragraph(self):\n\n sentences = set()\n while True:\n sentences.add(self.generate_sentence())\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DutyDetails a model defined in OpenAPI | def __init__(self, when: DutyDetailsWhen=None, where: DutyDetailsWhere=None, requirements: object=None):
self.openapi_types = {
'when': DutyDetailsWhen,
'where': DutyDetailsWhere,
'requirements': object
}
self.attribute_map = {
'when': 'when',
... | [
"def __init__(self, worker_id: str=None, duty: Duty=None):\n self.openapi_types = {\n 'worker_id': str,\n 'duty': Duty\n }\n\n self.attribute_map = {\n 'worker_id': 'workerId',\n 'duty': 'duty'\n }\n\n self._worker_id = worker_id\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the when of this DutyDetails. | def when(self, when):
self._when = when | [
"def setJoinTime(self,when):\n if not when:\n return\n self.joinTime = when",
"def __init__(self, when: DutyDetailsWhen=None, where: DutyDetailsWhere=None, requirements: object=None):\n self.openapi_types = {\n 'when': DutyDetailsWhen,\n 'where': DutyDetailsWh... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the where of this DutyDetails. | def where(self):
return self._where | [
"def where(self):\n if self._where is None:\n self._where = self._get_attributes(\"where\")\n return self._where",
"def location(self):\n return self.patient.get('location', None)",
"def where(self, where):\n if self.local_vars_configuration.client_side_validation and wher... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the where of this DutyDetails. | def where(self, where):
self._where = where | [
"def where(self, where):\n if self.local_vars_configuration.client_side_validation and where is None: # noqa: E501\n raise ValueError(\"Invalid value for `where`, must not be `None`\") # noqa: E501\n\n self._where = where",
"def where(self):\n if self._where is None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the requirements of this DutyDetails. | def requirements(self):
return self._requirements | [
"def get_requirements(self):\n pass",
"def optional_requirements(self):\n return self.__optional_requirements",
"def data_requirements(self) -> List[DataRequirement]:\n return self._data_requirements",
"def equipmentRequirements(self):\n if self.reqid:\n return Equipment... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the requirements of this DutyDetails. | def requirements(self, requirements):
self._requirements = requirements | [
"def set_demand(self, d, j=None):\n if j is None:\n api.set_demands(d)\n else:\n api.set_demand(j, d)",
"def agent_requirements(self, agent_requirements):\n\n self._agent_requirements = agent_requirements",
"def update_dietary_requirements():\n if flask.request.meth... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the 2norm of the error between vectors x and y | def err_norm2(x, y):
normsq = sum(((x[k]-y[k])**2 for k in range(len(x))))
return np.sqrt(normsq) | [
"def std_error_slow(self, x, y):\n return self.std(x, y) / np.sqrt(self.num_points_in_bins(x))",
"def std_error(self, x, y):\n std, _, binnum = binned_statistic(x, y, statistic='std', bins=self.bin_edges)\n num_points = np.array([len(binnum[binnum==i+1]) for i in range(len(self))])\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function Finds the distance between each waypoint (by calling Google's Distance Matrix API) and stores the distance and duration between the two in a file. | def find_distances(all_waypoints):
waypoint_distances = {}
waypoint_durations = {}
for (waypoint1, waypoint2) in combinations(all_waypoints, 2):
try:
response = get_distance_matrix([waypoint1, waypoint2])
##"distance" is in meters
print(response)
di... | [
"def find_station_distances(station_list):\n output = \"\"\n for i in range(len(station_list)):\n station = station_list[i][0]\n n1 = station_list[i][1]\n e1 = station_list[i][2]\n for j in range(len(station_list[i:-1])):\n next_station = station_list[j][0]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A more general activation function, allowing to use just string (for prelu, leakyrelu and elu) and to add BN before applying the activation | def _activation(activation, BN=True, name=None, momentum=0.9, training=None, config=BATCH_NORM):
def f(x):
if BN and activation != 'selu':
if config == 'keras':
h = BatchNormalization(momentum=momentum)(x, training=training)
elif config == 'tf' or config == 'tensorfl... | [
"def add_activation(layers, activation):\n if activation == 'relu':\n layers.append(nn.ReLU(inplace=True))\n elif activation == 'sigmoid':\n layers.append(nn.Sigmoid())\n elif activation == 'tanh':\n layers.append(nn.Tanh())\n elif activation == 'softplus':\n layers.append(nn... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
raise all pylab windows with str in the title, whether they flash or raise depends on window manager and settings Note than figure(num='myname') is a legal way to name a fig | def raise_matching(str):
labs = pl.get_figlabels()
for lab in labs:
if str in lab:
pl.figure(lab)
mgr = pl.get_current_fig_manager()
mgr.window.tkraise() | [
"def namedWindow(winname, flags=...) -> None:\n ...",
"def graphic_window(self):",
"def update_title(name, window):\n\twindow.wm_title(name)",
"def add_window(self, name):\n self.window_names.append(name)\n cv2.namedWindow(name + \" (press ESC to quit)\")\n m = WeakMethod(self.handle_m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
close all pylab windows with str in the title, see also raise _matching | def close_matching(str):
(labs_nums) = zip(pl.get_figlabels(),pl.get_fignums())
closed = 0
for (lab,num) in labs_nums:
if str in lab:
pl.close(num)
closed += 1
if closed == 0: print('No figures matching {s} found'
.format(s=str)) | [
"def destroyWindow(winname) -> None:\n ...",
"def raise_matching(str):\n labs = pl.get_figlabels()\n for lab in labs:\n if str in lab:\n pl.figure(lab)\n mgr = pl.get_current_fig_manager()\n mgr.window.tkraise()",
"def close_window(window):\r\n window.destroy(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper to make a new item with given session_id, item_id and extra data Sets the housekeeping fields (TTL, created_at, expires_on, etc). | def new_session_item(sid, item_id, **extra) -> SessionItem:
return SessionItem(
session_id=sid,
item_id=item_id,
created_at=datetime.now(),
updated_at=datetime.now(),
expires_on=int(ITEM_TTL + time.time()) if ITEM_TTL else 0,
**extra,
) | [
"def new_session() -> SessionItem:\n base_session = SessionItem.get(BASE_SESSION_HASH_KEY, META)\n sid = str(uuid.uuid4())\n\n s = new_session_item(sid, META, meta=MetaAttribute())\n s.save()\n # Create the empty placeholders for the collections\n new_session_item(sid, PLOGS, plogs=[]).save()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new session, returning the 'meta' item for it | def new_session() -> SessionItem:
base_session = SessionItem.get(BASE_SESSION_HASH_KEY, META)
sid = str(uuid.uuid4())
s = new_session_item(sid, META, meta=MetaAttribute())
s.save()
# Create the empty placeholders for the collections
new_session_item(sid, PLOGS, plogs=[]).save()
new_session_... | [
"def test_create_session(self):\n _meta = SessionMeta.new(app_secret=self.manager.secret)\n\n session1 = self.manager.get_session(meta=_meta, new=True)\n session1['foo'] = 'bar'\n session1.commit()\n\n # read back session\n session2 = self.manager.get_session(meta=_meta, ne... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load all spCFrame files in a given directory. Return a dictionary of CFrame objects, keyed by cameraexpid string | def load_spCFrame_files(platedir):
print "loading spCFrame files from " + platedir
cframes = dict()
for filename in glob(os.path.join(platedir, 'spCFrame-*.fits')):
print ' ', os.path.basename(filename), asctime()
expid = get_expid(filename)
cframes[expid] = CFrame(filename)
r... | [
"def _process_dir(self) -> dict:\n camera_person = {}\n for scene_cam in self.camera_bboxes: \n scene, camera = scene_cam.split(\"_\")\n folder_path = osp.join(self.root, scene, camera, \"img1\")\n \n scene_cam_data = []\n for frame_id, x, y, w, h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that reprojects shp file crs to a given crs. Reprojected .shp files will be on the outshp \ directory. Reprojected .shp files will have the same name and all attributes from inshpdir. | def reproject(self, inshpdir, outshpdir, crs):
self.inshpdir = inshpdir
self.outshpdir = outshpdir
self.crs = crs
logging.info('%s %s', "Preparing to reproject files in :", self.inshpdir)
# Getting all the path of .shp files
path_of_shp_files= []
for filenam... | [
"def reproject(shapefile, crs):\n\treturn shapefile.to_crs(crs) if shapefile.crs != crs else shapefile",
"def reproject_shapefile(source_dataset, source_layer, source_srs, target_srs):\n # make GeoTransformation\n coord_trans = osr.CoordinateTransformation(source_srs, target_srs)\n\n # make target shapef... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a bounding box of polygon. Takes a polygon shp file as an input and creates a polygon shp file of bounding boxes for each of the polygon they represent. Bounding boxes will have the attributes of their respective pylogons. | def getBbox(self, srcfile, outfile):
self.srcfile = srcfile
self.outfile = outfile
with fiona.drivers():
logging.info("Reading file: " + self.srcfile)
with fiona.open(self.srcfile) as src:
self.meta = src.meta
logging.info("Creating ou... | [
"def make_polygon(\n class_name: str,\n point_path: List[Point],\n bounding_box: Optional[Dict] = None,\n subs: Optional[List[SubAnnotation]] = None,\n slot_names: Optional[List[str]] = None,\n) -> Annotation:\n return Annotation(\n AnnotationClass(class_name, \"polygon\"),\n _maybe_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a polygon shp file as an input and creates a point shapefile of centroids. Points are at the center of its polygon. This point layer will have the attributes from their respective pylogons. | def getCentroids(self, srcfile, outfile):
self.srcfile = srcfile
self.outfile = outfile
with fiona.drivers():
logging.info("Reading file: " + self.srcfile)
with fiona.open(self.srcfile) as src:
self.meta = src.meta
self.meta['schema']['... | [
"def create_point_shapefile(data, polygon, point_shapefile):\n print('Create a point shapefile with all the GLDAS grid cells')\n\n longitude_array = data['longitude_array']\n latitude_array = data['latitude_array']\n polygon_driver = polygon.driver\n point_driver = polygon_driver\n polygon_crs = p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Requests for the current weather data to openweather.com and generates a shapefile. | def getWeather(self, path_ids_file, ow_api, outputshp):
logging.info("Reading file for city ids: " + path_ids_file)
f = open(path_ids_file,"r")
self.api_id = ow_api
self.ids_txt = f.readline().strip()
self.outputshp = outputshp
logging.info("City ids found: ... | [
"def download_city_next_hour_weather_data():\n start_time = datetime.now()\n end_time = (start_time + timedelta(hours=1))\n\n requests_params = {'id': CITY_CODE, 'appid': OPEN_WEATHER_API_KEY}\n\n response = requests.get(url=OPEN_WEATHER_API, params=requests_params)\n\n logger.info(msg='Response stat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to snap lines to points. | def snapLineToPoints(self, pointshp, lineshp, outshpdir):
pass | [
"def snap_line(line, points, tolerance=1e-9): \n if shapely.get_type_id(line.geometry) == 0:\n if shapely.distance(point,line) < tolerance:\n line = shapely.snap(line, points, tolerance=1e-9)\n elif shapely.get_type_id(line.geometry) == 4:\n points = [point for point in points if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the schema of a shapefile. PARAMETER(S) | def getSchema(path):
path = path
with fiona.open(path) as shpfile:
schema = shpfile.schema.copy()
return schema | [
"def Shapefile(**keywords):\n keywords['type'] = 'shape'\n return CreateDatasource(keywords)",
"def schema(self):\n return self.get(\"/schema\").json()",
"def view_schema(self):\n pipeline = self._get_one_pipeline()\n uri = pipeline.get_artifacts_uri_by_component(\n GDPComp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the crs of the given .shp file. PARAMETER(S) | def getCrs(path):
path = path
with fiona.open(path) as shpfile:
crs = shpfile.crs
return crs | [
"def getCrs(self):\n with self._getDatasetLock:\n\n # use gcp if available\n if len(self.dataset.gcps[0]) != 0 and self.dataset.gcps[1]:\n crs = self.dataset.gcps[1]\n else:\n crs = self.dataset.crs\n\n # if no crs but the file is a NI... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Navigate a given path returning all files in folder and subfolders | def explore_path(path, recursive=True):
for dirname, _, filenames in os.walk(path):
for filename in filenames:
yield dirname, filename
if not recursive:
break | [
"def _get_files(path):\n ret_val = []\n for root, _, files in os.walk(path):\n for f in files:\n ret_val.append(os.path.join(root, f))\n return ret_val",
"def get_all_file_paths_in_path(path: str):\n def join_paths(dir_path, filenames):\n return (joinpath(p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Collect few info about phisical machine. | def get_machine_info():
return {
'platform': system(),
'hostname': gethostname(),
'ip_address': gethostbyname(gethostname()),
'mac_address': ':'.join(findall('..', '%012x' % getnode())),
} | [
"def machine_info():\n BYTES_IN_GIG = 1073741824\n free_bytes = psutil.virtual_memory().available\n return [{\"memory\": int(free_bytes / BYTES_IN_GIG), \"cores\": multiprocessing.cpu_count(),\n \"name\": socket.gethostname()}]",
"def gather_chassis_details(self):",
"def _get_machine_info(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> s = Solution() >>> s.isOneBitCharacter([1,0,0]) True >>> s.isOneBitCharacter([1,1,1,0]) False | def isOneBitCharacter(self, bits: list[int]) -> bool:
s = [len(bits) - 2]
while s:
i = s.pop()
if i == -1:
return True
if bits[i] == 0:
s.append(i - 1)
if i >= 1 and bits[i - 1] == 1:
s.append(i - 2)... | [
"def single_chars_only(lst):\n return all(len(i) == 1 for i in lst)",
"def __bool__(self: bitlist) -> bool:\n return 1 in self.bits",
"def is_binary(t):\n if t == zero or t == one:\n return True\n elif t.ty != Term.COMB:\n return False\n elif t.head == bit0 or t.head == bit1:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set wait condition SharkSEM request header contains set of flags, which specify conditions to execute the request. bit 0 Wait A (SEM scanning) bit 1 Wait B (SEM stage) bit 2 Wait C (SEM optics) bit 3 Wait D (SEM automatic procedure) bit 4 Wait E (FIB scanning) bit 5 Wait F (FIB optics) bit 6 Wait G (FIB automatic proce... | def SetWaitFlags(self, flags):
self.connection.wait_flags = flags | [
"def set_wait_in(self, value: bool) -> None:\n if value:\n self.wait_for |= Direction.IN\n else:\n self.wait_for = (self.wait_for | Direction.IN) ^ Direction.IN",
"def request_version_and_flags(self, req, msg):",
"def request_fewer_flags(self, req, msg):",
"def request_stat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read multiple images This extends FetchImage() capabilities. More image channels can be processed, 16bit images are supported. channel_list zerobased list of input video channels pxl_size number of image pixels (pixels) Scanning should be initiated first. Then, call this blocking function. During the call, messages fro... | def FetchImageEx(self, channel_list, pxl_size):
return self.connection.FetchImageEx('ScData', channel_list, pxl_size) | [
"def image_gather_channels(image_list: List[Image], im: Image = None, subimages=0) -> Image:\n \n if im is None:\n nchan = len(image_list)\n _, npol, ny, nx = image_list[0].shape\n im_shape = nchan, npol, ny, ny\n im = create_image_from_array(numpy.zeros(im_shape, dtype=image_list[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Store the GUID from the bundle in item's annotations in order to later be able to match up Plone objects with bundle items. | def _set_guid(self, obj, item):
IAnnotations(obj)[BUNDLE_GUID_KEY] = item['guid'] | [
"def test_division_logistics_items_guiditem_id_put(self):\n pass",
"async def _create_bundle(self,\n lta_rc: RestClient,\n bundle: BundleType) -> Any:\n self.logger.info('Creating new bundle in the LTA DB.')\n create_body = {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the path relative to the plone site for the given brain. | def get_relative_path(self, brain):
return '/'.join(brain.getPath().split('/')[2:]) | [
"def portal_path(): # pragma: no cover",
"def base_path(self):\n return self.path",
"def get_nb_path() -> Path:\n try: \n if is_colab(): return get_colab_nb_name()\n else: \n srv, path = _find_nb()\n if srv and path:\n root_dir = Path(srv.get('root_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resolves an item's parent pointer to a container obj and its path. | def resolve_parent_pointer(self, item):
parent_guid = item.get('parent_guid')
formatted_parent_refnum = item.get('_formatted_parent_refnum')
if parent_guid is not None:
parent_path = self.path_from_guid(parent_guid)
elif formatted_parent_refnum is not None:
pare... | [
"def parent(cls, item):\n\n parent_id = parent_uid = parent_item = None\n\n is_key = lambda fk, name: fk == name or \\\n isinstance(fk, (tuple, list)) and \\\n fk[1] == name\n\n all_items = item.job.items\n for link_item i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the block at a given location in the world's version | def block_at(world, dimension, x, y, z) -> Tuple[Block, BlockEntity]:
block, blockEntity = world.get_version_block(
x, y, z, dimension, (world.level_wrapper.platform, world.level_wrapper.version)
)
return block, blockEntity | [
"def get(self, pos):\n\n x, y = pos\n block = self.default_block\n\n if self.is_in_bounds(pos):\n block = self.map[y][x]\n\n return block",
"def get_block(self, blockname=None):\n if blockname is None:\n blockname = \"xia2\"\n assert blockname, \"inv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for batch_pickup_request | def test_batch_pickup_request(self):
pass | [
"def test_call_pickup(self):\n events = self.run_and_get_events('fixtures/xfer_misc/call_pickup.json')\n\n expected_events = self.events_from_tuples((\n ('on_b_dial', {\n 'call_id': 'vgua0-dev-1445001221.106',\n 'caller': CallerId(code=123450001, name='Alice', ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for connections_request | def test_connections_request(self):
pass | [
"def test_0040_test_connection(self):\n self.assertTrue(self.api.test_connection())",
"def verify_connection(self, request, client_address):\n return 1",
"def test_connect_with_prefix(self):\n conn = Connection(url=\"http://test.com/\")\n conn.connect()\n conn.request_path = \"/v1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for reconnect_all | def test_reconnect_all(self):
pass | [
"def reconnect():\n disconnect()\n connect()",
"def test_reconnect_route_request(self):\n pass",
"def _reconnect(self):\n self._terminate()\n self._session_init()\n self._connect()",
"def test_reconnect(self):\n self.transport.client_service.delay = 0\n old_prot... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for reconnect_route_request | def test_reconnect_route_request(self):
pass | [
"def test_reconnect_all(self):\n pass",
"def reconnect_callback():\n return mock.MagicMock()",
"def test_reconnect(self):\n self.transport.client_service.delay = 0\n old_protocol = self.protocol\n yield self.protocol.transport.loseConnection()\n yield deferLater(reactor, 0,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for register_route_request | def test_register_route_request(self):
pass | [
"def test_route_added(self):\n resp = requests.get(self.req)\n self.assertEqual(resp.status_code, 200, 'Route was not added')",
"def test_route_added_callback(self):\n self.ht.add_route('/blah/<param>', callback=dummy)\n\n resp = requests.get(self.ht.base + '/blah/12345')\n\n la... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for status_request | def test_status_request(self):
pass | [
"def test_verify_new_request_status(self):\r\n request = helpers.create_dummy_request(self.request_manager, 1)\r\n self.assertEquals(request.status, RequestStatus.UNASSIGNED)",
"def test_b_check_status_is_returned(self):\n self.assertTrue(self.status.is_returned(), \"The awaited status is returne... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for unregister_router | def test_unregister_router(self):
pass | [
"def delete_router(router):\n return IMPL.delete_router(router)",
"def remove_gateway_router(router):\n return IMPL.remove_gateway_router(router)",
"def remove_interface_router(router, body=None):\n return IMPL.remove_interface_router(router, body)",
"def test_2_remove_router_B(self):\n\n # Fi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of clips for a user. | def _get_clips(self, user_id, user_name, client_id=None, oauth_token=None):
logging.info("Getting clips for %s", user_name)
clip_headers = {}
if client_id is not None:
clip_headers['Client-ID'] = client_id
if oauth_token is not None:
clip_headers['Authorization'] ... | [
"def get_clips(self, client_id=None, oauth_token=None):\n logging.info(\"Getting clips\")\n self.client = TwitchHelix(client_id=client_id, oauth_token=oauth_token)\n total_clips = []\n for user in self.users_list:\n clips = self._get_clips(user['_id'], user['name'],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the view count of the video that a clip was created from. | def _get_clip_video_views(self, clip):
logging.info("Getting video views for clip %s", clip['id'])
if clip['video_id'] == '':
logging.info("Video couldn't be found for clip %s. Default to "
"900.", clip['id'])
return 900 # Default video views
vi... | [
"def video_count(self) ->int:\n return int(self._statistics.get('videoCount'))",
"def view_count(self) -> int:\n return int(self.statistics.get('viewCount'))",
"def _get_clip_rating(self, clip_views, video_views):\n return clip_views / (video_views/9 + 100)",
"def cameraCount(self):\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a rating given the view count of a clip and a video. | def _get_clip_rating(self, clip_views, video_views):
return clip_views / (video_views/9 + 100) | [
"def _get_clip_video_views(self, clip):\n logging.info(\"Getting video views for clip %s\", clip['id'])\n if clip['video_id'] == '':\n logging.info(\"Video couldn't be found for clip %s. Default to \"\n \"900.\", clip['id'])\n return 900 # Default video ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a subset of 'good' clips from a list of clips. | def _get_good_clips(self, clips):
logging.info("Getting good clips from %s clip(s)", len(clips))
good_clips = []
for clip in clips:
if (self.lang is None or clip['language'] in self.lang):
logging.debug("Clip %s by %s has %s views", clip['id'],
... | [
"def get_clips(self, client_id=None, oauth_token=None):\n logging.info(\"Getting clips\")\n self.client = TwitchHelix(client_id=client_id, oauth_token=oauth_token)\n total_clips = []\n for user in self.users_list:\n clips = self._get_clips(user['_id'], user['name'],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a list of information of 'good' clips from a list of users. | def get_clips(self, client_id=None, oauth_token=None):
logging.info("Getting clips")
self.client = TwitchHelix(client_id=client_id, oauth_token=oauth_token)
total_clips = []
for user in self.users_list:
clips = self._get_clips(user['_id'], user['name'],
... | [
"def _get_good_clips(self, clips):\n logging.info(\"Getting good clips from %s clip(s)\", len(clips))\n good_clips = []\n for clip in clips:\n if (self.lang is None or clip['language'] in self.lang):\n logging.debug(\"Clip %s by %s has %s views\", clip['id'],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The enrollment level of the service. Default value is `BLOCK_ALL`. | def enrollment_level(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "enrollment_level") | [
"def stealth_mode_blocked(self):\n if \"stealthModeBlocked\" in self._prop_dict:\n return self._prop_dict[\"stealthModeBlocked\"]\n else:\n return None",
"def part_salable_default():\n\n return InvenTreeSetting.get_setting('PART_SALABLE')",
"def get_block_events_enable(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If true, then the Policy is enforced. If false, then any configuration is acceptable. | def enforced(self) -> pulumi.Input[bool]:
return pulumi.get(self, "enforced") | [
"def enforced(self) -> bool:\n return pulumi.get(self, \"enforced\")",
"def PolicyEnforcement(self) -> PolicyEnforcement:",
"def allow(self) -> pulumi.Input[bool]:\n return pulumi.get(self, \"allow\")",
"def should_auto_approve():\n if settings.MODERATION_POLICY == moderation_policies.automat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If set to true, the values from the effective Policy of the parent resource are inherited, meaning the values set in this Policy are added to the values inherited up the hierarchy. | def inherit_from_parent(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "inherit_from_parent") | [
"def _inherit_from_parent(self):\n # TODO: there are more attributes (all) that can be inherited\n if not self.parent:\n return\n if self.group_id is None and self.parent.group_id:\n self.group_id = self.parent.group_id\n if TRACE: logger.debug('_inherit_from_pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load data from the database and return a pandas dataframe. Limit param specifies number of rows returned. Default is to return all | def load_dataframe_from_sql(river, limit=-1):
if limit > 0:
logger.debug("loading df for river {river} from sql with row limit of {limit}".format(river=river, limit=limit))
else:
logger.debug("loading entire df for river {river} from sql".format(river=river))
con = sqlite3.connect(DATABASE_P... | [
"def to_data_frame(self, num_records: int = 0) -> PandasDataFrame:",
"def _get_all_records(self):\n self._conn = create_engine(self._connection_str, echo=False)\n\n QUERY = (\"\"\"SELECT *\n FROM {}\n ORDER BY person_index, timestamp;\n \"\"\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |