query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Method that deletes a user comment by id | def delete_user_comment(username, comment_id):
result = get_comment_by_id(username, comment_id)
# remove from list
commentslist.remove(result) | [
"def delete_comment(request, comment_id):\n raise NotImplementedError",
"def deleteComment(self, id):\n text = self.generateRequest('/v2.1/Comments/' + str(id), 'DELETE','')\n return True",
"def comment_delete(request, post_id, comment_id):\n if request.method == 'POST':\n comment = C... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to get all user comments based on their usename | def all_user_comments(username):
# comment = [
# comment for comment in commentslist if comment["username"] == username
# ]
return commentslist | [
"def all_user_comments(username):\n return commentslist",
"def user_comments(request, name):\n\n comments = User.objects.get(username = name).comments.all()\n context_instance=RequestContext(request, {'comments': comments})\n return render_to_response('accounts/user_comments.html', context_instance)"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that deletes a user comment by id | def delete_user_comment(username, comment_id):
result = get_comment_by_id(username, comment_id)
# remove from list
commentslist.remove(result) | [
"def delete_comment(request, comment_id):\n raise NotImplementedError",
"def deleteComment(self, id):\n text = self.generateRequest('/v2.1/Comments/' + str(id), 'DELETE','')\n return True",
"def comment_delete(request, post_id, comment_id):\n if request.method == 'POST':\n comment = C... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if username exists in USERS_LIST | def check_username(search_username):
for find_username in USERS_LIST:
if find_username["username"] == search_username:
return True
return False | [
"def user_exist(cls,user_name):\n for user in cls.user_list:\n if user.user_name == user_name:\n return True\n return False",
"def user_exists(cls,name):\n for user in cls.Users_list:\n if user.user_name==name:\n return True\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if there are any queries Returns | def __checkForEmptyQuery(self):
empty = True
for key in self.queries:
if len(self.queries[key]) > 0:
empty = False
break
return empty | [
"def has_no_results_for_query(self):\n return self.num_results == 0 or self.effective_query",
"def db_query_is_empty(result):\n\n rows = []\n # start iterating through GqlQuery\n for r in result:\n rows.append(r)\n break\n if len(rows) > 0:\n return False\n return True",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Produce a block of queries for the given type (without parantheses) | def __produceBlock(self, qType, qList=None):
block = ""
first = True
for query in (qList if not (qList is None) else self.queries[qType]):
if first:
block += qType + ":" + query
first = False
else:
block += self.connectorStr... | [
"def _build_type_query(account, params):\n if params.get(\"type\") == None:\n return Q(debit_account=account) | Q(credit_account=account)\n elif params.get(\"type\") == \"charges_paid\":\n return (Q(type=Transaction.TYPE_CHARGE) &\n Q(debit_account=account))\n elif params.get(\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Give a list of all title queries that are searched for Returns | def getAllTitleQueries(self):
return self.queries["ti"] | [
"def all_title() -> list:\n return [i[\"title\"] for i in Blogs_Manager.TablePost.all_query()]",
"def get_results(self):\n self.format_keywords()\n self.get_content()\n self.format_results() \n return self.results",
"def listSearchCriteria():",
"def fetchTitles(self):\r\n cur ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add an author to be contained in the query string Add an author to also search for. All authors, title, and abstract queries will be searched for (orconnected). At least one of them has to be specified to have a valid query string. | def addAuthorQuery(self, authorName):
if not (authorName in self.queries["au"]):
self.queries["au"].append(authorName) | [
"def add_query_to_article(article, query=''):\n article['query'] = query\n return article",
"def _add_author_filter(self, find_kwargs, bundle):\n if bundle.request.GET.get('author'):\n find_kwargs['spec']['commit.author'] = bundle.request.GET['author']\n return find_kwargs",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add an string to be contained in a title to the query string Add a word to search in titles for. All authors, title, and abstract queries will be searched for (orconnected). At least one of them has to be specified to have a valid query string. | def addTitleQuery(self, titleQuery):
if not (titleQuery in self.queries["ti"]):
self.queries["ti"].append(titleQuery) | [
"def add_title_criteria(self, title):\n self.criteria.append({'title': title})",
"def add_searches(title, url, new_article, session):\n\n # Split the title, path and url netloc (sub domain)\n all_words = title.split()\n from urllib.parse import urlparse\n\n # Parse the URL so we can call netloc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove an author from the query string Stop searching for a given author. At least one query has to be specified overall to have a valid query string. | def removeAuthorQuery(self, authorName):
try:
self.queries["au"].remove(authorName)
except ValueError:
raise NotInQueryException | [
"def delete_author():\n try:\n key = list(request.args.keys())[0]\n val = request.args[key].strip('\"')\n if key is None:\n return render_template(\"error.html\", message=\"Please enter a correct key\"), 400\n except IndexError:\n queryVal = request.form.to_dict()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove all authors from the query string Stop searching for authors. At least one query has to be specified overall to have a valid query string. | def removeAllAuthorQueries(self):
self.queries["au"] = [] | [
"def removeAuthorQuery(self, authorName):\n try:\n self.queries[\"au\"].remove(authorName)\n except ValueError:\n raise NotInQueryException",
"def _get_authors_soup_text_clean(self, author_soup_text):\n authors = []\n for author in author_soup_text:\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove an title query from the query string Stop searching for a given string in titles. At least one query has to be specified overall to have a valid query string. | def removeTitleQuery(self, titleQuery):
try:
self.queries["ti"].remove(titleQuery)
except ValueError:
raise NotInQueryException | [
"def clean_query(args, query):\n if args['bookmark']:\n return query\n elif args['open'] and not (args['search'] or args['wolfram'] or\n args['first']):\n # The query consists of links to open directly\n return query.split()\n else:\n # Replace spec... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove all titles from the query string Stop searching for titles. At least one query has to be specified overall to have a valid query string. | def removeAllTitleQueries(self):
self.queries["ti"] = [] | [
"def strip_args(url):\n FLAGS = ['on.nytimes.com/public/overview', 'query.nytimes.com']\n\n if not any(flag in url.lower() for flag in FLAGS):\n for i in range(len(url)):\n if url[i] == \"?\" or url[i] == \"#\":\n url_str = url[:i]\n if url_str.endswith('/all/')... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove an abstract query from the query string Stop searching for a given string in abstracts. At least one query has to be specified overall to have a valid query string. | def removeAbstractQuery(self, abstractQuery):
try:
self.queries["abs"].remove(abstractQuery)
except ValueError:
raise NotInQueryException | [
"def clean_abstract_phrases(self, abstract):\n sfp = SciFullTextProcessor()\n try:\n clean_abstract = sfp.remove_abstract_phrases(abstract)\n except TypeError:\n clean_abstract = abstract\n except UnboundLocalError:\n clean_abstract = abstract\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Starts creating new graph. | def start_new_graph(self):
self.nodes = {}
self.reset_graph() | [
"def create_graph(identifier=None):",
"def create_graph(self, colorful):\n\n # Get flow data\n flow_data = self.get_flow_data()\n\n # Get all flows names\n self.flows = [flow for flow_file in flow_data for flow in flow_data[flow_file]]\n\n print('Drawing graph...')\n # Gr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resets the internal state of graph creator. | def reset_graph(self):
raise NotImplementedError | [
"def reset():\n\n globals()[\"currentGraph\"] = CompositionGraph()",
"def reset(self):\n\t\ttf.reset_default_graph()\n\t\tdel self.train_x_state, self.train_y_state\n\t\tdel self.test_x_state, self.test_y_state",
"def _restoreGraph(self):\n\n # self.tempG = self.g.copy()\n\n if nx.is_directed(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses a `dataflow` that comes from Pipeline Manager application. If any error during parsing occurs it is returned. If parsing is successful a kenning pipeline is returned. | def parse_dataflow(self, dataflow: Dict) -> Tuple[bool, Union[Dict, str]]:
try:
interface_to_id = {}
graph = dataflow['graph']
for dataflow_node in graph['nodes']:
kenning_node = self.nodes[dataflow_node['type']]
parameters = dataflow_node['pr... | [
"def ParsePipeline(self):\n negated = False\n\n self._Peek()\n if self.token_type == Id.KW_Bang:\n negated = True\n self._Next()\n\n child = self.ParseCommand()\n assert child is not None\n\n children = [child]\n\n self._Peek()\n if self.token_type not in (Id.Op_Pipe,):\n if n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a node interface based on it's IO specification. | def _create_interface(
self,
io_spec: Dict[str, List],
direction: str
) -> Tuple[str, List]:
interface_id = self.gen_id()
interface = {
'name': io_spec['name'],
'id': interface_id,
'direction': direction
}
return... | [
"def _generate_node(cls, interface_cls, interfaces):\n node = cls.xml_generator.create_node()\n\n # Add comment about specified class.\n cls.xml_generator.add_comment(\n node, \"Specifies {}\".format(interface_cls.__name__)\n )\n\n # Add interfaces sorted by their names... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build a graph using build_graph and write it out. | def write_graph(build_graph, out_dir):
g = ops.Graph()
with g.as_default():
build_graph(out_dir)
filename = os.path.join(out_dir, 'test_graph_%s.pb' % build_graph.__name__)
with open(filename, 'wb') as f:
f.write(g.as_graph_def().SerializeToString()) | [
"def write_graph(build_graph, out_dir):\n g = ops.Graph()\n with g.as_default():\n build_graph(out_dir)\n filename = os.path.join(out_dir, 'test_graph_%s.pb' % build_graph.__name__)\n with open(filename, 'wb') as f:\n f.write(g.as_graph_def().SerializeToString())",
"def export_graph(self, filename... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function prepares code_batch dictionary. If code_x is not provided, it is sampled from gaussian distribution. if code_y is not provided, it is sampled from uniform distribution. | def sample_codes(self, batch_size, code_x=None, code_y=None, name='codes'):
with tf.name_scope(name):
if code_x is None:
code_x = tf.random_normal(
[batch_size, self.code_size], mean=0.0, stddev=1.0, name='x', dtype=tf.float32)
else:
... | [
"def preprocess(self):\n timeStart = time.time()\n self.canvasClicked.addingCoco = False\n self.canvasClicked.addingNoncoco = False\n self.canvasClicked.deleting = False\n if not os.path.isfile(Parameters.codebookFileName):\n imgHeight = self.imgArray.shape[0]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
client.add(source_id, "graph_string", dest_id || [dest_ids]) => None | def add(self, source, graph, dest):
return self.server.execute(self._execute_operation(
source, graph, dest,
ttypes.ExecuteOperationType.Add)) | [
"def _add_edge(edges, src, dest):\n edge = (src, dest)\n if edge not in edges:\n edges.add(edge)",
"def add_edge_from(self, edges):\n \n for source_id, dest_id in edges:\n if self.has_node(source_id):\n source_node = self.get_node(source... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
client.remove(source_id, "graph_string", dest_id || [dest_ids]) => None | def remove(self, source, graph, dest):
return self.server.execute(self._execute_operation(
source, graph, dest,
ttypes.ExecuteOperationType.Remove)) | [
"def test_remove_node_by_id(self):\n data = {\n \"nodes\": [\n {\"data\": {\"id\": \"0\"}},\n {\"data\": {\"id\": \"1\"}},\n {\"data\": {\"id\": \"2\"}},\n ],\n \"edges\": [\n {\"data\": {\"source\": \"0\", \"target\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
client.get(source_id, "graph_string", dest_id || [dest_ids]) => (edges,) | def get(self, source, graph, dest):
return self.get_all([(source, graph, dest)])[0] | [
"def outgoing_edges(*identifier):",
"def dfs_edges_generator(graph, source, reverse=...):\n ...",
"def path_graph_from_ids(source_num, target_num, unigraph):\n\n\t# Use the ids provided to make urls (which are the actual node ids used in the graph)\n\tsource_id = \"http://eprints.gla.ac.uk/view/author/\" + s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
client.get_metadata(source,_id, "graph_string") => obj.source_id/state_id/count/updated_at | def get_metadata(self, source, graph):
return self.server.get_metadata(source, self.graphs.get(graph)) | [
"def metadata(self) -> FeedMetadata:",
"def test_ontology_metadata():\n query = \"\"\"\n MATCH (node:OntologyFileMetadata)\n RETURN count(node) as counter \"\"\"\n with Neo4jHelper.run_single_query(query) as result:\n for record in result:\n assert record[\"counter\"]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
시간 중 시를 설정한다. 속성 __hour에 시를 할당하기 전에 시가 0~23(둘 다 포함) 사이의 정수인지를 확인한다. | def hour(self, hour):
assert hour >= 0 and hour < 24, "'시'는 0-23 사이의 정수여야 합니다."
self.__hour = hour | [
"def getHour(self, parent):\r\n self.now = datetime.now()\r\n self.current_time = self.now.strftime(\"%H:%M:%S\")\r\n self.lineEditWidgets[\"HORA\"].setText(self.current_time)",
"def initialtime_hour(self):\n return self._get_time_info([\"Initial_Time_H\", \"initialTimeHour\"])",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
시간 중 분을 설정한다. 속성 __minute에 분을 할당하기 전에 분이 0~59(둘 다 포함) 사이의 정수인지를 확인한다. | def minute(self, minute):
assert minute >= 0 and minute < 60, "'분'은 0-59 사이의 정수여야 합니다."
self.__minute = minute | [
"def __init__(self, start_minutes = 0):\n self.minutes = start_minutes",
"def minute(self) -> int:\r\n return self._minute",
"def _get_minute(self):\n return self.datetime.minute",
"def minute(self):\n return self.time[1]",
"def getMinute(self):\n return _libsbml.Date_getM... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
시간 중 분을 설정한다. 속성 __second에 초를 할당하기 전에 초가 0~59(둘 다 포함) 사이의 정수인지를 확인한다. | def second(self, second):
assert second >= 0 and second < 60, "'초'는 0-59 사이의 정수여야 합니다."
self.__second = second | [
"def second(self) -> int:\r\n return self._second",
"def _get_second(self):\n return self.datetime.second",
"def _draw_second_leds(self):\n seconds = self._time.second\n\n # convert the string seconds to a binary string. Remove the\n # '0b' from the beginning of the string and... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fit the classifier using the generator gen that yields batches as specified. This function is not supported for this detector. | def fit_generator(self, generator: "DataGenerator", nb_epochs: int = 20, **kwargs) -> None:
raise NotImplementedError | [
"def fit_generator(self, generator, nb_epochs=20, **kwargs):\n from art.data_generators import KerasDataGenerator\n\n # Try to use the generator as a Keras native generator, otherwise use it through the `DataGenerator` interface\n if isinstance(generator, KerasDataGenerator) and not hasattr(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the sequential id for this test for the passed in client | def sequential_id(self, client):
if client.client_id not in self._sequential_ids:
id_ = sequential_id("e:{0}:users".format(self.name), client.client_id)
self._sequential_ids[client.client_id] = id_
return self._sequential_ids[client.client_id] | [
"def sequential_id(self, client):\r\n if client.client_id not in self._sequential_ids:\r\n id_ = sequential_id(\"e:{0}:users\".format(self.name), client.client_id)\r\n self._sequential_ids[client.client_id] = id_\r\n return self._sequential_ids[client.client_id]",
"def client_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs the nodes and edges of a section using a mapping of section data, and returns a reference to those nodes and edges in a sequence. Does not construct junction nodes/edges. | def build_section(self, section_map):
section = []
for coordinate_map in section_map['shape']:
vertex = self.graph.add_vertex()
# Build a property map containing the geolocation, speed, ID, and bearing.
self.node_locations[vertex] = [coordinate_map['lon'], coordinate... | [
"def _create_sections(self):\n\t\t# NOTE: cell=self is required to tell NEURON of this object.\n\t\tself.node = [h.Section(name='node',cell=self) for x in range(self._axonNodes)]\n\t\tself.mysa = [h.Section(name='mysa',cell=self) for x in range(self._paraNodes1)]\n\t\tself.flut = [h.Section(name='flut',cell=self) f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds an edge and node to the end of a section, representing the departure from a section into a junction. | def add_entrance(self, section, junction):
assert section # The section may not be an empty sequence.
previous_node = section[-1]
junction_node = self.graph.add_vertex()
# Update property map with the node's geolocation, speed, ID, and bearing.
self.node_locations[junction_nod... | [
"def add_exit(self, section, junction):\n assert section # The section may not be an empty sequence.\n\n next_node = section[0]\n junction_node = self.graph.add_vertex()\n\n \"Build a property map containing the geolocation, speed, ID, and bearing\"\n self.node_locations[junction... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds an edge and node to the beginning of a section, representing the departure from a junction into a section. | def add_exit(self, section, junction):
assert section # The section may not be an empty sequence.
next_node = section[0]
junction_node = self.graph.add_vertex()
"Build a property map containing the geolocation, speed, ID, and bearing"
self.node_locations[junction_node] = [junc... | [
"def add_entrance(self, section, junction):\n assert section # The section may not be an empty sequence.\n\n previous_node = section[-1]\n junction_node = self.graph.add_vertex()\n\n # Update property map with the node's geolocation, speed, ID, and bearing.\n self.node_locations[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Increases the number of nodes in the graph by adding new nodes between each edge which carries a weight greater than maximum_distance. The new nodes inherit the attributes of the destination node, unless it is a junction in which case they inherit from the source node. | def split_edges(self, maximum_distance):
""" Iterate through the vertices of each section. For each vertex v, evaluate edges for which v is a source.
If an edge of weight greater than maximum_distance, then split it. """
for section_id in self.sections:
utils.print_progress(len(self.... | [
"def addDistance(graph):\n distanceList = graphCalculate._calculateDistance(graph)\n for dist, edge in zip(distanceList, graph.edges(data=True)):\n edge[2]['distance'] = dist",
"def add_neighbors(node):\n #print('add_neighbors '+node)\n try:\n location = map_data['nodes'][nod... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the total change in angle is given by calculating the sum of the difference in angle between each vertex pair. | def total_edge_angle(e1, e2):
e1_source = section.index(e1[0])
e2_target = section.index(e2[1])
""" Given a pair of vertices, call angle_delta between them. """
f = lambda pair: utils.angle_delta(self.node_heading[pair[0]], self.node_heading[pair[1]])
""" Ma... | [
"def sum_angle(self, t):\n TIMESTEP = (self.end - self.start) / RESOLUTION\n\n theta1, theta2 = self.angle(t), self.angle(t + TIMESTEP)\n delta = theta2 - theta1\n print(delta)\n self.theta += delta",
"def _compute_total_degrees(self):\n total = 0\n if not self.sym... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the total distance traversed by two adjacent edges, either of which might be compound edges. | def total_edge_length(e1, e2):
return cumulative_edge_length(e1) + cumulative_edge_length(e2) | [
"def node_distance(self, node1, node2):\n if node1 == node2:\n return 0.0\n for i, (n1, n2) in enumerate(zip(self.paths[node1], self.paths[node2])):\n if n1 != n2:\n break\n else:\n i = min(len(self.paths[node1]), len(self.paths[node2]))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines if a merge is allowable. A merge is allowable if... the target of the first edge is the source of the second edge (they are adjacent) length(e1) + length(e2) < minimum_distance delta(bearing_1, bearing_2) + delta(bearing_2, bearing_3) < maximum_angle_delta | def permissible(e1, e2):
return e1[1] == e2[0] and \
total_edge_length(e1, e2) < maximum_distance and \
total_edge_angle(e1, e2) < maximum_angle_delta | [
"def allows_merge_commit(self):\n\n return self.data[\"mergeCommitAllowed\"]",
"def valid_merge( group1, group2, target_dir, max_list_size, split_toplevel=True ):\n if len( group1 ) <= 0 or len( group2 ) <= 0:\n return True\n if ( lsize( group1 ) + lsize( group2 ) ) <= max_list_size:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merges edges e1 and e2 together. An edge is a sequence where the first two elements are [source, target]. An edge may have additional elements. | def merge(e1, e2):
assert permissible(e1, e2)
return [e1[0], e2[1], None] # A merged edge has not been added, so it has no ID. | [
"def add_edge(self, node1: Node, node2: Node):\n self.__add_edge(node1, node2)\n self.__add_edge(node2, node1)",
"def _add_edge(edges, src, dest):\n edge = (src, dest)\n if edge not in edges:\n edges.add(edge)",
"def merge(self, other):\n self.add_nodes(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find a path between two sections. | def find_section_path(self, section_id1, section_id2):
result = graph_tool.topology.shortest_path(
self.graph, self.sections[str(section_id1)][0],
self.sections[str(section_id2)][-1],
weights=self.edge_weights)
edges = result[1]
for edge in edges:
... | [
"def find_path(self, start_member, end_member, path=[]):\n network = self.__network_dict\n path = path + [start_member]\n if start_member == end_member:\n return path\n if start_member not in network:\n return None\n for member in network[start_member]:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the vertices and edges in a path between two vertices. | def find_vertex_path(self, vertex_id1, vertex_id2, as_network_object):
v1 = self.graph.vertex(vertex_id1)
v2 = self.graph.vertex(vertex_id2)
vertices, edges = graph_tool.topology.shortest_path(self.graph, v1, v2, weights=self.edge_weights)
if v1 == v2:
vertices = [v1, v1]
... | [
"def find_all_paths(self, start_vertex, end_vertex, path=[]):\n graph = self.__graph_dict \n path = path + [start_vertex]\n if start_vertex == end_vertex:\n return [path]\n if start_vertex not in graph:\n return []\n paths = []\n for vertex in graph[st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a section ID, returns the exit junction. | def get_exit_junction(self, id):
return self.sections[id][-1] | [
"def get_entrance_junction(self, id):\n return self.sections[id][0]",
"def add_exit(self, section, junction):\n assert section # The section may not be an empty sequence.\n\n next_node = section[0]\n junction_node = self.graph.add_vertex()\n\n \"Build a property map containing ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a section ID, returns the exit junction. | def get_entrance_junction(self, id):
return self.sections[id][0] | [
"def get_exit_junction(self, id):\n return self.sections[id][-1]",
"def add_exit(self, section, junction):\n assert section # The section may not be an empty sequence.\n\n next_node = section[0]\n junction_node = self.graph.add_vertex()\n\n \"Build a property map containing the... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a section ID, returns the entrance and exit junctions. | def get_junctions(self, section_id):
return self.get_entrance_junction(section_id), self.get_exit_junction(section_id) | [
"def get_entrance_junction(self, id):\n return self.sections[id][0]",
"def get_exit_junction(self, id):\n return self.sections[id][-1]",
"def find_section_path(self, section_id1, section_id2):\n result = graph_tool.topology.shortest_path(\n self.graph, self.sections[str(section_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the real distance between two vertices, given their vertex IDs. | def vertex_distance(self, v1, v2):
return utils.real_distance(self.node_locations[v1], self.node_locations[v2]) | [
"def compute_distance(pt_id_a, pt_id_b):\n pt_a = np.array(source.GetPoint(pt_id_a))\n pt_b = np.array(source.GetPoint(pt_id_b))\n return np.linalg.norm(pt_a - pt_b)",
"def dist(v1, v2):\n return ( (v1[0] - v2[0])**2 + (v1[1] - v2[1])**2 )**0.5",
"def compute_distance(node1, node2):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a list of vertices to a list of sections | def to_sections(self, path):
return list(map(lambda tup: tup[0], groupby(path, key=lambda v_id: self.node_id[v_id]))) | [
"def edgify(vertices:list)->list:\n edges = []\n for k in range(0, len(vertices) - 1):\n edges.append([vertices[k], vertices[k + 1]])\n return edges",
"def process_vertices(vertices):\n return [new_vertex(v) for v in vertices]",
"def vertices(self):\n for v in self.vert:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete an edge edgeNumber Edge number to be deleted | def deleteEdge(self, edgeNumber):
edge = self.edgeIndex[edgeNumber]
startVertex = edge.startVertex
endVertex = edge.endVertex
startVertexNumber = startVertex.vertexNumber
endVertexNumber = endVertex.vertexNumber
vertexIndex = self.vertexIndex
parentInde... | [
"def delete_edge(identifier):",
"def delete_edge(self,_id):\n path = build_path(edge_path, _id)\n return self.request.delete(path, params=None)",
"def delete_edge(self, _id):\n raise NotImplementedError",
"def delete(self, edge):\n assert len(edge) in [2, 3], 'Illegal input format!... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes a vertex. Should be used with care vertexNumber Vertex number to be deleted | def deleteVertex(self, vertexNumber):
del self.vertexIndex[vertexNumber] | [
"def delete_vertex(self, _id):\n path = build_path(vertex_path,_id)\n return self.request.delete(path,params=None)",
"def delete_vertex(self, _id):\n raise NotImplementedError",
"def delete_vertex(self, vertex_name):\n for vertex in self.vertices:\n if vertex.name == verte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all graph vertex numbers an array consisting of all the vertices numbers | def getVertexNumbers(self):
return self.vertexIndex.keys() | [
"def get_vertices(self) -> []:\n res = []\n for v in range(self.v_count) :\n res.append(v)\n return res",
"def vertices(self):\n return list(self._graph)",
"def vertex_ids(self):\n return self.get_ids()",
"def list_vertices(self):\n return list(self.graph_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the last edge number __lastEdgeNumber the last edge number assigned to edges. | def getLastEdgeNumber(self):
return self.__lastEdgeNumber | [
"def last_edge(self):\n return self._edge",
"def getLastColorNum(self):\n return self.last_color_num",
"def getLastDepthNum(self):\n return self.last_depth_num",
"def last_index(self) -> int:\n return self._last_index",
"def getLastInt(self):\n ii = int(getLast())\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get neighbors for a vertex vertexNumber Vertex number for which neighbors have to be obtained | def getNeighbors(self, vertexNumber):
parentIndex = self.parentIndex
neighborNumbers = parentIndex[vertexNumber]
neighbors = []
for neighborNumber in neighborNumbers:
neighbors.append(Vertex(neighborNumber))
return neighbors | [
"def neighbors(self, n):\n return self.graph[n]",
"def neighbors_in(self, vertex):\n return list(self.neighbor_in_iterator(vertex))",
"def neighbors(self, v):\n for edge in self.ed:\n if v in edge[0]:\n yield edge[0].nbr(v)",
"def search_neighbours(self, graph):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get number of neighbors for a vertex vertexNumber Vertex number for which number of neighbors have to be obtained Number of neighbors | def getNumberOfNeighbors(self, vertexNumber):
return self.__degreeCount[vertexNumber] | [
"def num_neighbors(self):\n return self._num_neighbors",
"def n_neighbors(self,n):\n return sum(1 for x in self.hex.get_neighbors_ring(n) if x is not None and x.is_occupied == 1)",
"def num_neighbors(self,pnums,flatten=False):\n\n #Count number of neighbors\n if flatten:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get degree distribution degreeDistribution Dictionary indexed on degree. Values are the number of nodes for a degree | def getDegreeDistribution(self):
degreeDistribution = {}
degreeCount = self.__degreeCount
vertexNumbers = self.vertexIndex.keys()
for vertexNumber in vertexNumbers:
try:
numberOfNeighbors = degreeCount[vertexNumber]
except KeyError:
... | [
"def in_degree_distribution(digraph):\n distribution_in_degree = dict()\n degree_count = compute_in_degrees(digraph)\n for count in degree_count.values():\n if count in distribution_in_degree:\n distribution_in_degree[count] += 1\n else: \n distribution_in_degree[count] ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write the connected components to a file fileName File name to store the connected components allSCC List of list of connected components | def writeCC(self, fileName, allSCC):
f = open(fileName,'w')
for compNumber in range(0,len(allSCC)):
f.write("Component number %s: " % (compNumber))
f.write("%s\n" % (str(allSCC[compNumber])))
f.close() | [
"def write_conformers(self, filename): # ccids):\n cnt = 0\n for confId in range(self.nconf): #ccids:\n w = Chem.SDWriter('%s_c%03d.sdf'%(filename,cnt+1))\n w.write(self.mol, confId=confId)\n w.flush()\n w.close()\n cnt += 1",
"def writeChemComp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write edges to file fileName File name to store edges in | def writeEdges(self, fileName, format):
edges = self.edgeIndex.values()
if format == 'simple':
f = open(fileName,'w')
for edge in edges:
f.write("%s -- %s\n" % (edge.startVertex.vertexNumber, edge.endVertex.vertexNumber))
f.close()
elif format ... | [
"def save_edges(self, file_name, **kwargs):\n self.__checkpath(file_name, **kwargs)\n\n # Get sources, targets, nsyns and edge_type_id for all edges.\n print(\"> building tables with %d nodes and %d edges\" % (self._network.nnodes, self._network.nedges))\n indptr_table = [0]\n nsy... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read edges from file fileName File name to read edges from | def readEdges(self, fileName, format):
f = open(fileName)
if format == 'simple':
edgesRaw = f.read().split("\n")
if edgesRaw[-1] == '': edgesRaw = edgesRaw[:-1]
for edge in edgesRaw:
[startVertex, endVertex] = edge.split("--")
newEdge... | [
"def read_edges(filename):\n g = nx.read_edgelist(filename, nodetype=str,create_using=nx.DiGraph())\n return g",
"def read_graph(filename):\n return nx.read_edgelist(filename, delimiter='\\t')",
"def read_graph(filename):\n return nx.read_edgelist(filename, create_using=nx.DiGraph(), nodetype=str)",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find edge with a given edge number edgeNumber Edge number to look for | def findEdge(self, edgeNumber):
try:
return self.edgeIndex[edgeNumber]
except KeyError:
raise EdgeError(edgeNumber, ErrorMessages.edgeNotFound) | [
"def findEdge(self,edge,param):\r\n\t\t\r\n\t\t#TODO: it would be good to find a faster way to \r\n\t\t#do this,ie, to hash by parameter or sort instead\r\n\t\t#of looping through all\r\n\t\t\r\n\t\tfor n in self.edges[edge].values():\r\n\t\t\tif param >= n.p1 and param <= n.p2:\r\n\t\t\t\treturn n;\r\n\t\t\r\n\t\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find vertex with a given vertex number vertexNumber Vertex number to look for | def findVertex(self, vertexNumber):
try:
return self.vertexIndex[vertexNumber]
except KeyError:
raise VertexError(vertexNumber, ErrorMessages.vertexNotFound) | [
"def get_vertex(self, n):\n #returns the vertex if it is in the graph\n if self.vert_list[n] != None:\n return self.vert_list[n]\n else:\n raise KeyError(\"It would appear the vertex you are searching for does not exist\")",
"def search_vertex(ls, vertex):\n for idx i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if vertex is present vertexNumber Vertex number of the vertex to check 0 if found. 1 if not found | def hasVertex(self, vertexNumber):
try:
rs = self.findVertex(vertexNumber)
return 0
except VertexError, e:
return 1 | [
"def findVertex(self, vertexNumber):\n try:\n return self.vertexIndex[vertexNumber]\n except KeyError:\n raise VertexError(vertexNumber, ErrorMessages.vertexNotFound)",
"def has_vertex(self, key):\n return key in self.vertex",
"def has_vertex(self, v) -> bool:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an extra keyword arguments dictionary that is used with the `add_item` call of the feed generator. Add the 'tags' field of the Page, to be used by the custom feed generator. | def item_extra_kwargs(self, obj):
result = {'tags':obj.get_meta_keywords(),
'short_description':obj.get_meta_description()[:90] if obj.get_meta_description() else '',
'image_url':''}
try:
page_rss_feed = PageRSSFeed.objects.get(page=obj)
result... | [
"def add_page_arg(args, page):\n if args is None:\n args = {}\n\n args['page'] = page\n return args",
"def page_content(self, **kwargs):\n return kwargs",
"def extraParameters(self): # real signature unknown; restored from __doc__\n return {}",
"def addPage(self, name, page, **at... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluate polynomial by inserting new values in to the indeterminants. Equaivalent to calling the polynomial or using the ``__call__`` method. | def call(poly, *args, **kwargs):
# Make sure kwargs contains all args and nothing but indeterminants:
for arg, indeterminant in zip(args, poly.names):
if indeterminant in kwargs:
raise TypeError(
"multiple values for argument '%s'" % indeterminant)
kwargs[indeterminan... | [
"def main():\n\n evaluate_polynomial()",
"def eval_polynomial(x, coeffs):\n pass",
"def evalPolynomial(n,a,b):\n return n**2 + a*n + b",
"def eval_poly(coeff, x):\n return reduce(lambda a, b: a*x+b, coeff[::-1])",
"def main():\r\n\r\n coef = [1,0,0,-1,-10]\r\n x = 2\r\n\r\n # The algorith... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Just pass table_widget object, and all rows will be deleted | def delete_all_rows(table_widget: QTableWidget):
row_count = table_widget.rowCount()
table_widget.setSelectionMode(QAbstractItemView.ExtendedSelection)
setSel(list(range(row_count)), table_widget)
remove_row_all_table(table_widget)
table_widget.setSelectionMode(QAbstractItemView.ExtendedSelection) | [
"def delete_all_rows(self) -> None:",
"def delete(self):\n\t\tself.table.delete()",
"def deleteAll(self, tableName, row, column, attributes):\r\n pass",
"def delete_button_clicked(self):\n if self.tableWidget.currentItem():\n current_row_number = self.tableWidget.currentItem().row()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Normalize facecolor values by vmin/vmax and return rgbcolor strings This function takes a tuple color along with a colormap and a minimum (vmin) and maximum (vmax) range of possible mean distances for the given parametrized surface. It returns an rgb color based on the mean distance between vmin and vmax | def map_face2color(face, colormap, scale, vmin, vmax):
if vmin >= vmax:
raise exceptions.PlotlyError(
"Incorrect relation between vmin "
"and vmax. The vmin value cannot be "
"bigger than or equal to the value "
"of vmax."
)
if len(colormap) == 1:
... | [
"def norm_cmap(values, cmap, vmin=None, vmax=None):\n mn = vmin or min(values)\n mx = vmax or max(values)\n norm = Normalize(vmin=mn, vmax=mx)\n n_cmap = plt.cm.ScalarMappable(norm=norm, cmap=cmap)\n\n rgb_colors = [n_cmap.to_rgba(value) for value in values]\n\n return n_cmap, rgb_colors",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Refer to FigureFactory.create_trisurf() for docstring | def trisurf(
x,
y,
z,
simplices,
show_colorbar,
edges_color,
scale,
colormap=None,
color_func=None,
plot_edges=False,
x_edge=None,
y_edge=None,
z_edge=None,
facecolor=None,
):
# numpy import check
if not np:
raise ImportError("FigureFactory._trisur... | [
"def qp(F, V):\n import matplotlib.pyplot\n from mpl_toolkits.mplot3d import Axes3D\n #\n # Plot the surface\n fig = matplotlib.pyplot.figure()\n axs = fig.add_subplot(1,1,1, projection=\"3d\")\n axs.plot_trisurf(V[:,0], V[:,1], V[:,2], triangles=F)\n #\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convenience function to report some broadcasted EphIDs | def report_broadcasted_ephids(name, app):
ephids = [ephid.hex() for ephid in app.current_ephids]
print("{} broadcasts [{}, {}, ...]".format(name, ephids[0], ephids[1])) | [
"def report_broadcasted_ephids(name, app):\n reporting_time = app.start_of_today + timedelta(hours=10)\n ephid = app.get_ephid_for_time(reporting_time)\n print(\"At {}: {} broadcasts {}\".format(reporting_time.time(), name, ephid.hex()))",
"def get_experiment_phn_info():\n phone_list = ['##', 'aa', 'a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the builder for the target class, what you want to predict | def target_builder(self):
return object_loader.get('target_builder') | [
"def __class__(self):\n return _Builder",
"def build(self) -> \"Learner\":\n return self.learner_class(**self.get_params_dict())",
"def _get_model_builder(use_t2t_decoder=True):\n config_json = {\n \"hidden_size\": 4,\n \"intermediate_size\": 8,\n \"max_position_embeddings\": 8,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Consume lines upon matching a criterion. Returns (consensuswithoutfirstline, firstline) if end_of_field(firstline) returns True, else returns (consensuswithfirstline, None) | def scrap(consensus, end_of_field):
if b'\n' not in consensus:
return consensus, None
line, remaining = consensus.split(b'\n', 1)
if end_of_field(line):
return consensus, None
return remaining, line | [
"def process_line(self, line):\n columns = line.split('|')\n\n if len(line) == 0 or len(columns) < 16:\n return None # empty line or malformed line\n\n cmte_id, name, zip_code = columns[0], columns[7], columns[10][:5]\n transaction_dt, transaction_amt = columns[13], columns... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take Torformatted named ranges, then returns a keywordbased dictionary of list of integers or mix of integers and range tuples (as returned by parse_range_once), expanded or not. | def parse_ranges(ranges, expand=True):
pairs = ranges.split(' ')
content = {}
for key, value in [pair.split('=') for pair in pairs if '=' in pair]:
content[key] = parse_range_once(value, expand)
return content | [
"def range_resolver(atoms_range: list, atom_names: list) -> List[str]:\n # dict with lists of positions of the > or < sign:\n rightleft = {'>': [], '<': []}\n for rl in rightleft:\n for num, i in enumerate(atoms_range):\n i = i.upper()\n if rl == i:\n # fill the ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take Torformatted parameters, then returns a keywordbased dictionary of integers. | def parse_params(params):
pairs = params.split(' ')
content = dict()
for key, value in [pair.split('=') for pair in pairs]:
content[key] = int(value)
return content | [
"def _cmd_params_to_dict(params):\n return {t[0]: t[1] for t in params}",
"def paramDetails(cls):\n return {\n 'dim': (10, 20, 2, 20),\n 'nIter': (1, 10, 2, 5),\n 'lamb': (.1, 1., .1, .05),\n 'alph': (30, 50, 5, 40)\n }",
"def enumerate_params(params:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Consume consensus headers if present, then returns the remaining input to be further processed and a set of headers (or None, if none present). | def consume_headers(consensus, flavor='unflavored', sanity=True):
if flavor not in ['unflavored', 'microdesc']:
raise NotImplementedError(
'Consensus flavor "{}" not supported.'.format(flavor))
whitelist = [
b'network-status-version', b'vote-status', b'consensus-method',
b'v... | [
"def _parse_header(self, source):\n\t\tif self.log: self.log.debug('Parsing header')\n\t\tCONTAINERS = {'OBJECT':'END_OBJECT', 'GROUP':'END_GROUP'}\n\t\tCONTAINERS_START = CONTAINERS.keys()\n\t\tCONTAINERS_END = CONTAINERS.values()\n\t\t\n\t\troot = ParserNode({}, None)\n\t\tcurrentNode = root\n\t\texpectedEndQueue... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Consume consensus footer if present, then returns the remaining input to be further processed and a set of footers (or None, if none present). | def consume_footer(consensus, flavor='unflavored', sanity=True):
if flavor not in ['unflavored', 'microdesc']:
raise NotImplementedError(
'Consensus flavor "{}" not supported.'.format(flavor))
whitelist = [
b'directory-footer', b'bandwidth-weights', b'directory-signature']
def ... | [
"def footer(*p):\n def process(pipe):\n for item in pipe:\n yield item\n for item in p:\n yield item\n return process",
"def get_footer(self):\n return None",
"def scrap(consensus, end_of_field):\n if b'\\n' not in consensus:\n return consensus, None\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse a raw consensus with the given flavor, then returns a sanitized JSONified version (or an equivalent python dictionary if needed). | def jsonify(consensus, flavor='unflavored', encode=True, sanity=True):
fields = dict(flavor=flavor)
consensus, http = consume_http(consensus)
if http is not None:
fields['http'] = http
consensus, headers = consume_headers(consensus, flavor, sanity)
if headers is not None:
fields['h... | [
"def consume_headers(consensus, flavor='unflavored', sanity=True):\n if flavor not in ['unflavored', 'microdesc']:\n raise NotImplementedError(\n 'Consensus flavor \"{}\" not supported.'.format(flavor))\n\n whitelist = [\n b'network-status-version', b'vote-status', b'consensus-method'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
More tests for save and reload | def test_save_reload(self):
base = BaseModel()
idd = base.id
base.name = "betty"
base.save()
storage.reload()
key = "BaseModel.{}".format(idd)
objs = storage.all()[key]
self.assertTrue(hasattr(objs, "name"))
self.assertTrue(objs.name == "betty")
... | [
"def test_save_reload(self):\n base2 = BaseModel()\n base_s = base2.save()\n self.assertTrue(os.path.isfile('BaseModel.json'))\n tmp_obj = BaseModel()\n tmp_id = 'BaseModel.' + tmp_obj.id\n tmp_obj.save()\n del storage._FileStorage__objects[tmp_id]\n storage.r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use the estimate for A to construct analytic model. | def analytic_model(ell,A_est,slope):
return total_Cl_noise(ell)+A_est*ell**(-slope) | [
"def __anova__(self):\n\t\tif self.got_residuals == False:\n\t\t\tself.__residuals__()\n\t\tdy = self.Y - sp.stats.tmean(self.Y)\n\t\tdfy = self.fitted - sp.stats.tmean(self.Y)\n\t\tRSS = float(np.dot(self.residuals.transpose(), self.residuals).reshape(1))\n\t\tMSS = float(np.dot(dfy.transpose(),dfy).reshape(1))\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given two sets of ra/dec's return median difference in degrees. The first is the reference. | def check_astrometry(ra1,dec1,ra2,dec2,pt_size=0.3):
ra_diff = ra2-ra1
dec_diff = dec2-dec1
ra_med_diff = np.median(ra_diff)
dec_med_diff = np.median(dec_diff)
return ra_med_diff, dec_med_diff | [
"def Median_Separation(RA,Dec):\r\n\r\n # author Gary Mamon\r\n\r\n separation_squared = np.array(0.) #Commentaire -> ne faut-il pas l'enlever a la fin (fausse la mediane) ?\r\n i_gal = np.arange(0,len(RA)) #Commentaire -> i_gal pas utilisees\r\n i_gal2 = np.arange(0,len(RA)-1)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a list [g,r,z] magnitudes, apply the cut and return an indexing boolean vector. | def FDR_cut(grz):
g,r,z=grz; yrz = (r-z); xgr = (g-r)
ibool = (r<23.4) & (yrz>.3) & (yrz<1.6) & (xgr < (1.15*yrz)-0.15) & (xgr < (1.6-1.2*yrz))
return ibool | [
"def get_response_weights_vector(zenith,azimuth,binsize=5,cut=57.4):\n\n # assuming useful input:\n # azimuthal angle is periodic in the range [0,360[\n # zenith ranges from [0,180[ \n\n # check which pixel (index) was hit on regular grid\n hit_pixel_zi = np.floor(zenith/binsize)\n hit_pixel_ai = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return indices of cat1 (e.g., DR3) and cat2 (e.g., DEE2) cross matched to tolerance. | def crossmatch_cat1_to_cat2(ra1, dec1, ra2, dec2, tol=1./(deg2arcsec+1e-12)):
# Match cat1 to cat2 using astropy functions.
idx_cat1_to_cat2, d2d = match_cat1_to_cat2(ra1, dec1, ra2, dec2)
# Indicies of unique cat2 objects that were matched.
cat2matched = np.unique(idx_cat1_to_cat2)
# For each cat2 object ma... | [
"def crossmatch_cat1_to_cat2(ra1, dec1, ra2, dec2, tol=1./(deg2arcsec+1e-12)):\n \n # Match cat1 to cat2 using astropy functions.\n idx_cat1_to_cat2, d2d = match_cat1_to_cat2(ra1, dec1, ra2, dec2)\n \n # Indicies of unique cat2 objects that were matched.\n cat2matched = np.unique(idx_cat1_to_cat2)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
converting ra dec to position on a unit sphere. ra, dec are in degrees. | def radec2pos(ra, dec):
pos = np.empty(len(ra), dtype=('f8', 3))
ra = ra * (np.pi / 180)
dec = dec * (np.pi / 180)
pos[:, 2] = np.sin(dec)
pos[:, 0] = np.cos(dec) * np.sin(ra)
pos[:, 1] = np.cos(dec) * np.cos(ra)
return pos | [
"def radec2pos(ra, dec):\n pos = numpy.empty(len(ra), dtype=('f8', 3))\n ra = ra * (numpy.pi / 180)\n dec = dec * (numpy.pi / 180)\n pos[:, 2] = numpy.sin(dec)\n pos[:, 0] = numpy.cos(dec) * numpy.sin(ra)\n pos[:, 1] = numpy.cos(dec) * numpy.cos(ra)\n return pos",
"def radec_to_xyz(ra, dec, r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a veto mask for coord. any coordinate within R of center is vet. | def veto(coord, center, R):
from sklearn.neighbors import KDTree
pos_stars = radec2pos(center[0], center[1])
R = 2 * np.sin(np.radians(R) * 0.5)
pos_obj = radec2pos(coord[0], coord[1])
tree = KDTree(pos_obj)
vetoflag = ~np.zeros(len(pos_obj), dtype='?')
arg = tree.query_radius(pos_stars, r=R)
arg = np.concatena... | [
"def veto(coord, center, R):\n from kdcount import KDTree\n\n pos = radec2pos(center[0], center[1])\n tree = KDTree(pos)\n \n if numpy.isscalar(R):\n #print('This is the value of R =%g'%(R))\n R = center[0]*0 + R\n \n R = 2 * numpy.sin(numpy.radians(R) * 0.5) \n\n pos = rad... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search for a conda virtual environment. | def search_conda():
conda_prefix = os.environ.get("CONDA_PREFIX")
if conda_prefix is not None:
conda_include = join(conda_prefix, 'include')
conda_lib = join(conda_prefix, 'lib')
else:
conda_include = ""
conda_lib = ""
return conda_include, conda_lib | [
"def contains_venv(_dir, **kargs):\n kargs.update(max_venvs=1)\n venvs = find_venvs(_dir, **kargs)\n return venvs and venvs[0]",
"def conda_list_environments():\n conda = '{0}/bin/conda'.format(utils.home('apps', 'miniconda'))\n\n run('{conda} info --envs'.format(conda=conda))",
"def find_env(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a boolean indicating whether a flag name is supported on the specified compiler. As of Python 3.6, CCompiler has a `has_flag` method. | def has_flag(compiler, flagname):
import tempfile
with tempfile.NamedTemporaryFile('w', suffix='.cc') as f:
f.write('int main (int argc, char **argv) { return 0; }')
try:
compiler.compile([f.name], extra_postargs=[flagname])
except setuptools.distutils.errors.CompileError:
... | [
"def has_flag(compiler, flag, ext=None):\n return try_compile(compiler, flags=[flag], ext=ext)",
"def _has_flag(compiler: CCompiler, flagname: str) -> bool:\n import tempfile\n from distutils.errors import CompileError\n\n extra = [\"-stdlib=libc++\"] if sys.platform == \"darwin\" else []\n\n with ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add variant to list of variants in descending order of pos | def add_variant(self, variant):
self.__variants.append(variant)
self.__variants.sort(reverse=True) | [
"def add(self, seq, diff):\n # Insert into sorted list using linear search because it will almost always be the front\n new = (seq, diff)\n for i, curr in enumerate(reversed(self.list)):\n if new > curr:\n self.list.insert(len(self.list) - i, new)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Define location and size of large deletions 100bp5000bp in length | def define_deletions(genome, num):
start = []
end = []
for n in range(num):
start_pos, end_pos = get_del_pos(genome)
# add deletion Variants to genome list
var = Variant("deletion", start_pos, end_pos, start_pos-end_pos)
genome.add_variant(var)
# add to unavail list
... | [
"def test_delete_updates_size(small_tree):\n small_tree.delete(40, autobalance=False)\n assert small_tree.size() == 5",
"def estimated_lookup_memory(self):\n return 60 * len(self.docvecs.offset2doctag) + 140 * len(self.docvecs.doctags)",
"def _process_delete(self, pos, length, read_name, mapping_qu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function. Deletion position generator | def get_del_pos(genome):
start_pos = random.randint(100,len(genome.seq)-5100) # positions 100bp from start or end will not be variable
end_pos = start_pos + random.randint(100,5000)
unavail = False
for n in range(start_pos, end_pos):
if n in genome.unavail_pos:
unavail = True
... | [
"def define_deletions(genome, num):\n start = []\n end = []\n for n in range(num):\n start_pos, end_pos = get_del_pos(genome)\n # add deletion Variants to genome list\n var = Variant(\"deletion\", start_pos, end_pos, start_pos-end_pos)\n genome.add_variant(var)\n # add to... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Define the translocation variants plus deletions in the case on nonconservative translocations | def define_translocations(genome, num, nc):
start = []
end = []
for n in range(num):
start_pos = random.randint(100,len(genome.seq)-5100) # positions 100bp from start or end will not be variable
end_pos = start_pos + random.randint(500,5000)
start.append(start_pos)
end.append... | [
"def define_deletions(genome, num):\n start = []\n end = []\n for n in range(num):\n start_pos, end_pos = get_del_pos(genome)\n # add deletion Variants to genome list\n var = Variant(\"deletion\", start_pos, end_pos, start_pos-end_pos)\n genome.add_variant(var)\n # add to... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mutates the reference sequence with variants | def mutate_seq(genome):
for var in genome.get_variants():
if var.type == "snp":
mutate_snp(genome, var)
elif var.type == "indel":
mutate_indel(genome, var)
elif var.type == "deletion":
mutate_deletion(genome, var)
elif var.type == "translocation or... | [
"def _replace_reference(self, var):\n\n if var.type not in \"cgmnr\":\n raise HGVSUnsupportedOperationError(\"Can only update references for type c, g, m, n, r\")\n\n if var.posedit.edit.type in (\"ins\", \"con\"):\n # these types have no reference sequence (zero-width), so retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mutate reference with snp | def mutate_snp(genome, var):
nt_options = {'A':['T','G','C'], 'T':['A','G','C'], 'G':['A','T','C'], 'C':['A','T','G']}
n = random.randint(0,2)
nt = nt_options.get(genome.seq[var.start])[n]
genome.mut_seq[var.start] = nt
var.ref = genome.seq[var.start]
var.alt = nt | [
"def genome_mod(reference, snps):\r\n reference_arr = list(reference)\r\n for snp in snps:\r\n original, snp, position = snp\r\n reference_arr[position] = snp\r\n reference = \"\".join(reference_arr)\r\n return reference",
"def _replace_reference(self, var):\n\n if var.type not in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mutation reference with small indel | def mutate_indel(genome, var):
if var.size > 0: # insertion
if var.size <= 10:
new_seq = small_insert(var)
if var.size > 10:
new_seq = large_insert(var)
for nt in new_seq:
genome.mut_seq.insert(var.start,nt)
var.ref = "."
var.alt = "".join... | [
"def mutation(self, individual):\n pass",
"def _mutation(self, chromosome):\n return chromosome.mutate()",
"def new_mutation(self):\n raise NotImplementedError(\"Should have implemented this\")",
"def resolve(self) -> Mutation:\n return Mutation(self.is_delete, self.col, self.value... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write vcf of introduced mutations | def write_vcf(file, ref, genome):
vcf = open(file, "w")
vcf.write("##fileformat=VCFv4.2\n")
vcf.write("##fileDate={}\n".format(datetime.datetime.today().strftime('%Y%m%d')))
vcf.write("##source={}\n".format(os.path.basename(__file__)))
vcf.write("##reference={}\n".format(ref))
vcf.write("##conti... | [
"def write_vcf(self, output='/dev/stdout'):\n vcf_writer = vcf.Writer(open(output, 'w'), self.reader)\n for record in self.records:\n vcf_writer.write_record(record)",
"def write_vcf(self, output='/dev/stdout'):\n self.__vcf.write_vcf(output)",
"def write_metadata(args, vcf_file)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Install InfluxDBGrafana plugin and check it exists | def install_influxdb_grafana(self):
self.env.revert_snapshot("ready_with_3_slaves")
self.prepare_plugin()
self.helpers.create_cluster(name=self.__class__.__name__)
self.activate_plugin() | [
"def _is_plugin_installed(self):",
"def installPlugin():\n if _master_checks() and not _check_plugin('MYSQL_FIREWALL'):\n if _check_if_localhost():\n _install_firewall_plugin(shell.parse_uri(shell.get_session().get_uri())['user'])\n else:\n print(\"\\n\\033[1mERROR:\\033[0m ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deploy a cluster with the InfluxDBGrafana plugin | def deploy_influxdb_grafana(self):
self.check_run("deploy_influxdb_grafana")
self.env.revert_snapshot("ready_with_3_slaves")
self.prepare_plugin()
self.helpers.create_cluster(name=self.__class__.__name__)
self.activate_plugin()
self.helpers.deploy_cluster(self.base_no... | [
"def deploy(self, log_cli_level='DEBUG'):\n logger.info(\"Deploying OCP cluster\")\n logger.info(\n f\"Openshift-installer will be using loglevel:{log_cli_level}\"\n )\n run_cmd(\n f\"{self.installer} create cluster \"\n f\"--d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deploy a cluster with the InfluxDBGrafana plugin in HA mode | def deploy_ha_influxdb_grafana(self):
self.check_run("deploy_ha_influxdb_grafana")
self.env.revert_snapshot("ready_with_9_slaves")
self.prepare_plugin()
self.helpers.create_cluster(name=self.__class__.__name__)
self.activate_plugin()
self.helpers.deploy_cluster(self.f... | [
"def deploy_influxdb_grafana(self):\n self.check_run(\"deploy_influxdb_grafana\")\n self.env.revert_snapshot(\"ready_with_3_slaves\")\n\n self.prepare_plugin()\n\n self.helpers.create_cluster(name=self.__class__.__name__)\n\n self.activate_plugin()\n\n self.helpers.deploy_c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uninstall the InfluxDBGrafana plugin with a deployed environment | def uninstall_deployed_influxdb_grafana(self):
self.env.revert_snapshot("deploy_influxdb_grafana")
self.check_uninstall_failure()
self.fuel_web.delete_env_wait(self.helpers.cluster_id)
self.uninstall_plugin() | [
"def uninstall():\n log.info(\"Deregistering NukeStudio plug-ins..\")\n pyblish.deregister_host(\"nukestudio\")\n pyblish.deregister_plugin_path(PUBLISH_PATH)\n avalon.deregister_plugin_path(avalon.Loader, LOAD_PATH)\n avalon.deregister_plugin_path(avalon.Creator, CREATE_PATH)",
"def disintegrate()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creating the layer structure (3 convolutional layers). | def setup_layer_structure(self):
self.page_rank_convolution_1 = self.layer(self.feature_number, self.args.layers[0], self.args.iterations, self.args.alpha)
self.page_rank_convolution_2 = self.layer(self.args.layers[0], self.args.layers[1], self.args.iterations, self.args.alpha)
self.page_rank_co... | [
"def _build_conv_nets_3D(self):\n kwargs = {\n '_input_shape': (self.batch_size, *self.lattice.links.shape),\n 'links_shape': self.lattice.links.shape,\n 'x_dim': self.lattice.num_links, # dimensionality of target space\n 'factor': 2.,\n 'spatial_size':... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Classifies crop time series over 7 years into crop sequence types based on the sum of transitions from one crop to another and on the number of different crops that are in the time series. If there are more than two years no data, arable grass or any class from the skip list, then the crop type is set to 255. Crop typi... | def identifyMainTypes(ts, no_data_value, arable_grass_value, skip_lst):
## first set all values in the sequence that also occur in the skip list to the no data value
ts_calc = ts.copy()
for value in skip_lst:
ts_calc[ts_calc == value] = no_data_value
## now count the transitions between values... | [
"def cover_crop_added(self):\n\n ## getting input parameter\n crop_input = self.soil_inputs.crop_cover.values[0]\n if pd.isnull(crop_input):\n crop_input = \"nan\"\n #climate_input = self.soil_inputs.climate.values[0]\n years_cropcover_tech = self.soil_inputs.time_using... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Root view of the package index, handle incoming actions from distutils or redirect to a more user friendly view | def root(request, fallback_view=None, **kwargs):
if request.method == 'POST':
if request.META['CONTENT_TYPE'] == 'text/xml':
log.debug('XMLRPC request received')
return parse_xmlrpc_request(request)
log.debug('Distutils request received')
parse_distutils_request(reque... | [
"def index(self, packagename = None):\n package = self._get_package(packagename)\n\n c.session = session\n c.constants = constants\n c.outcomes = [\n (constants.PACKAGE_COMMENT_OUTCOME_UNREVIEWED, _('Unreviewed')),\n (constants.PACKAGE_COMMENT_OUTCOME_NEEDS_WORK, _(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a scenery class file. | def create_class_file(self, template, class_name, property_map):
class_array = class_name.split('::')
if len(class_array) < 2:
return None
# Check to see if output directory exists; create it if not
output_dir = os.path.join(CURRENT_DIR, 'output', class_array[1])
fi... | [
"def createClassFile( p ):\n create_modules( p[\"package\"] )\n name = p[\"protocol\"][\"name\"]\n name.lower()\n path = os.path.join( *p[\"package\"].split( \".\" ) )\n with open( \"./%s/%s.py\" % ( path, name ), \"w\" ) as f:\n for i in p[\"imports\"]:\n createClassFile( i )\n\n c = Klass( packag... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recommended way of creating a `GridArray` from arraylike object. The arguments are used to for initialization but their validity is only checked at the initialization and not during call of `.from_array`. | def from_array(
cls,
data: Any,
*,
name: str = "unnamed",
label: str = "unlabeled",
unit: str = "",
axes: Optional[Sequence[Any]] = None,
time: Optional[Union[Axis, int, float]] = None,
) -> "GridArray":
if not isinstance(data, da.Array):
... | [
"def test_grid_field_as_array():\n fields = ModelDataFields()\n fields.new_field_location(\"grid\", 1)\n\n fields.at_grid[\"const\"] = [1.0, 2.0]\n assert_array_equal(fields.at_grid[\"const\"], [[1.0, 2.0]])\n\n val = np.array([1.0, 2.0])\n fields.at_grid[\"const\"] = val\n assert np.shares_mem... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This generates returns a query_batch object that holds the logic for creating aggregators for the queries, and also contains the logic for processing the results and printing the query | def produce_query_batches(self):
pass | [
"def buildQuery():",
"def aggregate_query(self):\n raise NotImplementedError",
"def run(self):\n query = self.query\n\n # count before filtering\n # self.cardinality = query.add_columns(self.columns[0].sqla_expr).count()\n\n self._set_column_filter_expressions()\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generic handler for errors. We respond in json if the request contenttype is JSON. The ui package can also define how it wants to render HTML errors, by setting a function. | def error_handling_router(error: HTTPException):
log_error(error, getattr(error, "description", str(error)))
http_error_code = 500 # fallback
if hasattr(error, "code"):
try:
http_error_code = int(error.code)
except ValueError:
pass
error_text = getattr(
... | [
"def set_error_handler():\n @current_app.errorhandler(Exception)\n def handle_invalid_usage(e: Exception):\n \"\"\"\n handle invalid message\n \"\"\"\n\n if isinstance(e, FlaskBaseError):\n response = jsonify(e.to_dict())\n response.status_code = e.status_code... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print full SQLAlchemy query with compiled parameters. Recommended use as developer tool only. | def print_query(query: Query) -> str:
regex = re.compile(r":(?P<name>\w+)")
params = query.statement.compile().params
sql = regex.sub(r"'{\g<name>}'", str(query.statement)).format(**params)
from flexmeasures.data.config import db
print(f"\nPrinting SQLAlchemy query to database {db.engine.url.databa... | [
"def print_query(self):\n if self.sql_query is None:\n raise Exception(\"print_query failed: The query needs first to be defined!!! \")\n else:\n self.logger.info(\n self.sql_query.compile(compile_kwargs={\"literal_binds\": True}))\n return",
"def print_sq... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Detect LF or CRLF newlines in a string by looking at the end of the first line | def detect_newline(string: str) -> str:
first_lf_pos = string.find("\n")
if first_lf_pos > 0 and string[first_lf_pos - 1] == "\r":
return "\r\n"
return "\n" | [
"def _detect_line_ending(content: str) -> Literal[\"\\r\", \"\\n\", \"\\r\\n\", None]: # noqa: F722\n cr = content.count(\"\\r\")\n lf = content.count(\"\\n\")\n crlf = content.count(\"\\r\\n\")\n if cr + lf == 0:\n return None\n if crlf == cr and crlf == lf:\n return \"\\r\\n\"\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |