query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Return current scene title
def get_current_scene_title(self): self.log.info("Execute method get_current_scene_title") sceneTitle = self.driver.find_element_by_css_selector("div[id='titleDiv']").text self.log.info("Current scene title is={}".format(sceneTitle)) return sceneTitle
[ "def get_current_title(self):\n latest_position = self.get_latest_position()\n if latest_position is not None:\n return latest_position.title\n else:\n return None", "def default_scene_name():\n return \"scene\"", "def get_window_title(self):\n return self.gl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if hotSpot is in center of view. And it shows to scene title=goingToScene. If hotSpot is not found or hotSpot is not in center exception is raised.
def _check_hotSpot_in_center(self, goingToScene, view=False): self.log.info("Execute method _check_hotSpot_in_center with gointTo scene parameter={}".format(goingToScene)) for hotSpot in get_hotSpots(self.log, self.driver): try: hotSpotLocation = hotSpot.get_attribute("style"...
[ "def _check_hotSpot_on_view(self):\n self.log.info(\"Execute method _check_hotSpot_on_view\")\n for hotSpot in get_hotSpots(self.log, self.driver):\n try:\n hotSpotLocation = hotSpot.get_attribute(\"style\")\n translate = hotSpotLocation.split(\"translate(\")[1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if hotSpot is in center of view. And it shows to scene title=goingToScene. If hotSpot is not found or hotSpot is not in center exception is raised.
def _check_hotSpot_on_view(self): self.log.info("Execute method _check_hotSpot_on_view") for hotSpot in get_hotSpots(self.log, self.driver): try: hotSpotLocation = hotSpot.get_attribute("style") translate = hotSpotLocation.split("translate(")[1].split("px")[0]...
[ "def _check_hotSpot_in_center(self, goingToScene, view=False):\n self.log.info(\"Execute method _check_hotSpot_in_center with gointTo scene parameter={}\".format(goingToScene))\n for hotSpot in get_hotSpots(self.log, self.driver):\n try:\n hotSpotLocation = hotSpot.get_attrib...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check hotSpots for given scenes for location and scene that it shows to
def check_arrows(self, scenes, view=False): self.log.info("Execute method check_arrows with parameter={}".format("".join(scenes.__repr__()))) cst = ConnectScenesTour(self.driver) connect_scene = ConnectScenesTour(self.driver) for scene in scenes: time.sleep(1) sel...
[ "def _check_hotSpot_on_view(self):\n self.log.info(\"Execute method _check_hotSpot_on_view\")\n for hotSpot in get_hotSpots(self.log, self.driver):\n try:\n hotSpotLocation = hotSpot.get_attribute(\"style\")\n translate = hotSpotLocation.split(\"translate(\")[1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resolve partial indirections to get to the first function. Useful when the docstring of original function is required.
def resolve_partials(func: Callable) -> Callable: while isinstance(func, functools.partial): func = func.func return func
[ "def find_docstring(self):\n #The docstrings for the interface are compiled from the separate docstrings\n #of the module procedures it is an interface for. We choose the first of these\n #procedures by convention and copy its docstrings over.\n #Just use the very first embedded method t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the function with name `func_name` from context of `redirect_from`. The module of `redirect_from` is searched for `func_name`
def get_func_for_redirect(func_name: str, redirect_from: Callable) -> Optional[Callable]: global global_modules try: func = exec_and_return(func_name, {**global_modules, **globals()}) return func except Exception: pass try: func = exec_and_return(".".join([redirect_from._...
[ "def GetOrigFn( module, fnName ):\n return DictGet( orig_fns, ( module, fnName ), getattr( module, fnName ) )", "def function_lookup(pymod_path):\n module_name, func_name = pymod_path.rsplit('.', 1)\n module = importlib.import_module(module_name)\n shell_function = getattr(module, func_name)\n asse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Infer an OpenAPI request body from function annotations. The annotations are converted to a `BaseModel` and schema is extracted from it.
def infer_request_from_annotations(func: Callable) -> Optional[Type[BaseModel]]: annot = {x: y for x, y in func.__annotations__.items() if x != "return"} if annot: class Annot(BaseModel): pass for x, y in annot.items(): Annot.__fields__[x] = ModelField(name=x, type_=y, cl...
[ "def infer_response_from_annotations(func: Callable) ->\\\n Tuple[MimeTypes, Union[str, BaseModel, Dict[str, str]]]:\n annot = func.__annotations__\n if 'return' not in annot:\n raise AttributeError(f\"'return' not in annotations for {func}\")\n ldict: Dict[str, Any] = {}\n # TODO: Parse a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Infer an OpenAPI response schema from function annotations. The annotations are converted to a `BaseModel` and schema is extracted from it.
def infer_response_from_annotations(func: Callable) ->\ Tuple[MimeTypes, Union[str, BaseModel, Dict[str, str]]]: annot = func.__annotations__ if 'return' not in annot: raise AttributeError(f"'return' not in annotations for {func}") ldict: Dict[str, Any] = {} # TODO: Parse and add example...
[ "def infer_request_from_annotations(func: Callable) -> Optional[Type[BaseModel]]:\n annot = {x: y for x, y in func.__annotations__.items() if x != \"return\"}\n if annot:\n class Annot(BaseModel):\n pass\n for x, y in annot.items():\n Annot.__fields__[x] = ModelField(name=x...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate OpenAPI compliant responses from a given `func`. `func` would necessarily be a `flask` view function and should contain appropriate sections in its docstring. What we would normally be looking for is `Requests`, `Responses` and `Maps`. In case, the Request or Response is processed or sent by another function,
def generate_responses(func: Callable, rulename: str, redirect: str) -> Dict[int, Dict]: if func.__doc__ is None: return {} doc = docstring.GoogleDocstring(func.__doc__) responses = {} # if "config_file" in rulename: # import ipdb; ipdb.set_trace() def remove_description(schema): ...
[ "def responsify(func: Callable[[], bool]) -> Callable[[], Response]:\n @wraps(func)\n def _wrapper() -> Response:\n try:\n success = func()\n response = jsonify({\n \"status\": \"ok\" if success else \"error\",\n \"msg\": \"\"\n })\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert schema to `query` parameters list compatible with OpenAPI.
def schema_to_query_params(schema: Dict[str, Any]) -> List[Dict[str, Any]]: retval = [] for k, w in schema["properties"].items(): temp = {} w.pop("title") if "required" in w: temp["required"] = w.pop("required") temp["name"] = k temp["in"] = "query" te...
[ "def parameter_schema(self):\n # TODO: Test\n return self.bus_client.schema.get_event_or_rpc_schema(self.api_name, self.name)['parameters']", "def schema_from_params(params_snippet):\r\n if params_snippet:\r\n return dict((n, Schema.from_parameter(p)) for n, p\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the `tags` section of a function's docstring
def get_tags(func: Callable) -> List[str]: if func.__doc__ is None: return [] doc = docstring.GoogleDocstring(func.__doc__) if not hasattr(doc, "tags"): return [] else: tags = re.sub(r' +', '', doc.tags) tags = re.sub(r',+', ',', tags) if tags: return tags.spl...
[ "def docstring(self):\n docs = []\n for key, func in self.items():\n sig = getattr(key, 'sig', '')\n doc = func.__doc__ or ''\n docs.append(f'{func.__name__}{sig}\\n {doc}')\n return '\\n\\n'.join(docs)", "def _describe_function(self) -> Tuple[List[str], Di...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the first found instance of a summary_writer, or None.
def get_summary_writer(self) -> Optional[tensorboard.SummaryWriter]: for c in self._collectors: if c.has_summary_writer(): return c.summary_writer return None
[ "def get_summary_writer(logdir):\n return summary_io.SummaryWriterCache.get(logdir)", "def get_first_scan(self):\n if self.scans is None:\n return None\n return self.scans[0]", "def one(self):\n try:\n return self.results[0]\n except IndexError:\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get iqdb thumb url.
def iqdb_thumb(self) -> str: return urljoin("https://iqdb.org", self.thumb)
[ "def thumbprint(self) -> str:\n return pulumi.get(self, \"thumbprint\")", "def thumb_url(self, episode, timestamp):\n return u'{base}/img/{episode}/{timestamp}/small.jpg'.format(base=self.base, episode=episode,\n timestamp=timestamp)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get verbose search place.
def search_place_verbose(self) -> str: return dict(ImageMatch.SP_CHOICES)[self.search_place]
[ "def kw_print_found(self):\n print('%s keyword %s found in %s' % (self.need, self.name,\n self.found_loc))", "def help_search_requests_city():\n get_search_requests_city_parser().print_help()", "def help_search_rides():\n get_search_for_ride_parse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get tags from match result.
def get_tags_from_match_result( match_result: Match, browser: Optional[mechanicalsoup.StatefulBrowser] = None, scraper: Optional[cfscrape.CloudflareScraper] = None, ) -> List[Tag]: filtered_hosts = ["anime-pictures.net", "www.theanimegallery.com"] res = MatchTagRelationship.select().where(MatchTagRe...
[ "def tags(self) -> List:", "def get_all_tag(self, response):\n\t\tall_tag = [] # only open tag, not have content in tag \n\t\tall_tag = re.findall('(<[^<]+>)', response)\n\n\t\tfor tag in all_tag:\n\t\t\tif re.match(\"<a\", tag):\n\t\t\t\tself.tag_a.append(tag)\n\t\t\telif re.match(\"<link\", tag):\n\t\t\t\tself....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Default argument is something mutable.
def default_mutable_arg(node, db): if any( isinstance(default, MUTABLE_TYPE) for default in node.args.defaults ): return node.args
[ "def no_mutable_default_args(logical_line):\n msg = \"S360: Method's default argument shouldn't be mutable!\"\n if RE_MUTABLE_DEFAULT_ARGS.match(logical_line):\n yield (0, msg)", "def set_defaults( ):\n __param=__default", "def defaultarg(f):\n @functools.wraps(f)\n def g(self, args):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether or not given string is "exit"
def check_not_exit(check_str): return check_str.lower() != "exit"
[ "def test_check_input_exit(self):\n self.assertTrue(self.utils.check_input('X', 'X'))\n self.assertTrue(self.utils.check_input('x', 'X'))\n self.assertTrue(self.utils.check_input('Exit', 'X'))\n self.assertTrue(self.utils.check_input('eXiT', 'X'))\n self.assertTrue(self.utils.chec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt user for choice to save previously printed text to drive.
def save_to_dir(save_name, save_text): save_txt = " " while save_txt not in ['y', 'n', '']: print("Would you like to save previously displayed text" " to a file [y/n]?") save_txt = user_input() if save_txt == 'y': write_dir = input_dir() if write_dir: ...
[ "def prompt_user_to_save(forecast_report):\r\n\r\n export_required = input(\"Would you like to save this weather report as a .txt file? (Y/N) \")\r\n if export_required == \"y\" or export_required == \"Y\":\r\n print()\r\n file_name = input(\"Enter a name for the file (or leave this empty to can...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert string to given conv_type. If it's unable to convert, return original string.
def conv_str(conv_str, conv_type=int): try: conv_yes = conv_type(conv_str) return conv_yes except ValueError: return None
[ "def str2type(type, string):\n if type in {'B', 'b', 'H', 'h', 'l', 'L'}:\n return int(string, 0)\n elif type in {'f', 'd'}:\n return float(string)\n raise ValueError('Type is not in accepted types. ')", "def check_convert(\n variable: Any,\n conv_type: Any,\n name: Tex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt user for existing names in dict or 'all'.
def input_challenge_name(d_dict=d): donor_list = [] while True: more_donors = None challenge_donor = None while challenge_donor not in (d_dict.names + ["", "all"]): print("Which donor would like to alter their donations?") print("Enter 'all' to alter all donors' d...
[ "def user_input():\n person = ''\n print(\"Input people to database:\")\n while person is not 'quit':\n person = input('Name: ')\n if person == 'quit' or person == 'q': \n break\n elif person == 'print' or person == 'p':\n count = input('How many: ')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt user to save donor dict before exiting program.
def mr_exit(): print("Before exiting would you like to save the donor info?[y/n]") save_confirm = "" while save_confirm not in ['y', 'n']: save_confirm = input('>').lower() if save_confirm == 'y': print(write_txt_to_dir("dict_init", d.dict_to_txt(), os.getcwd())) sys.exit()
[ "def saveAndExit(save : dict):\n if savesengine.validateSave(save):\n result = savesengine.writeSave(save)\n if result: exit(0)\n if result==False:\n print(\"Save wasn't saved somewhy, exit anyway? (Y/n)\")\n prompt = userChoice(\"\", [\"y\", \"n\"])\n if pro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cuts unnessecary connections that are already visited in another train
def cut(solution): trains = solution["trains"] # Delete first/last connections for train in trains: # While the train exists while train.travel_time > 0: first_connection = train.connections[0] last_connection = train.connections[-1] # Delete the first c...
[ "def remove_nodes(self):\n n = self.minLinks\n linkCount = {}\n keepers = []\n index = {}\n g.newLinks=[]\n # count the number of links per source node\n for node in self.links:\n linkCount[node['source']] = linkCount.get(node['source'],0)+1\n # gen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract csrf token from the page content.
def get_csrf_token(request): soup = BeautifulSoup(request.text) csrf_tag = soup.find('input', attrs={'name': 'csrfmiddlewaretoken'}) if not csrf_tag: raise WebException("csrf tag could not be found on %s" % request.url, request) return csrf_tag['value']
[ "def csrf_token(self):\n r=Loader.capi.cppcms_capi_session_get_csrf_token(self.d).decode()\n self.check()\n return r;", "def _get_csrftoken():\n # logging.getLogger(__name__).error(request.headers)\n # logging.getLogger(__name__).error(request.cookies)\n if 'csrftoken' not in request...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST data to given url along with csrf token extracted from the same page.
def smart_post(conn, url, data): request = conn.get(url, verify=False) data['csrfmiddlewaretoken'] = get_csrf_token(request) logging.debug('csrf=' + data['csrfmiddlewaretoken']) post_request = conn.post(url, data=data, headers={'referer': url}, verify=False) if post_request.status_code == 302: ...
[ "def _session_post(self, url, data=None, **kwargs):\n return self.session.request(\n method='post', url=url, data=data, **kwargs\n )", "def send_post_request(url, data):\n post_data = {\n 'data': data\n }\n return requests.post(url, data=post_data)", "def post(self, quer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get form URL for the given set of building codes.
def get_form_url(building_code): return DATA_FORM.format(meter_id=building_code)
[ "def getFormURL(form_id):\n return 'https://docs.google.com/forms/d/%s/viewform' % (form_id, )", "def _getEnrollmentFormUrl(self, validated=False):\n url = '/gsoc/student_forms/enrollment/' + self.gsoc.key().name()\n return url if not validated else url + '?validated'", "def build_url(self, check_box_l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the rounded hour of the given Datetime object.
def rounded_hour(dt): return dt.hour if dt.minute < 30 else dt.hour + 1
[ "def get_rounded_hours(self, time_step: int) -> Decimal:\n minutes = self.hours * 60\n return Decimal(ceil(minutes / time_step) * time_step) / 60", "def get_hour_of_day(time: datetime) -> float:\n # Round times to nearest minute by adding seconds component to times\n rounded_time = time + time...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the log likelihood log p(X) under current parameters. To compute this you can first call the function compute_yz_joint
def compute_log_likelihood(X, params): m, n, _ = X.shape likelihood = 0. for i in range(m): p_y_0 = p_y(0, params) p_y_1 = p_y(1, params) for j in range(n): x = X[i,j] p_y_0 += log_sum_exp(p_x_z(x,0,params) + p_z_y(0,0,params), p_x_z(x,1,params) + p_z_y(1,0,pa...
[ "def calculateLogJointProbabilities(self, datum):\n logJoint = util.Counter()\n\n for label in self.legalLabels:\n logJoint[label] = math.log(self.prior[label])\n for feat, value in datum.items():\n if value > 0:\n logJoint[label] += math.log(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calls vcfsfs.build_sfs(), to which most arguments are simply passed vcffile is a vcf, or bgzipped vcf file, with SNP data model_file is a model file model is the name of a population in the model basename is the basename of the zip archive and the basename of the sfs files dimfiletypes is a string that takes the value ...
def make_fscmsfs_file(vcffile,model_file,model, basename, dimfiletypes, downsampsizes, folded,outgroup_fasta,BEDfilename,randomsnpprop,seed): sfs = vcfsfs.build_sfs(vcffile,model_file,model,BEDfilename=BEDfilename, altreference = outgroup_fasta,folded = folded, ...
[ "def gen_fs_scf_obj(**kwargs):\n return fs_scf_obj", "def parse_vcfs(args, db):\n for sid in db[\"samples\"]:\n for mode in [\"SNV\", \"INDEL\"]:\n parse_vcf(args, db, sid, mode)", "def get_svtype_to_svfile_and_df_gridss_from_call_SVs_outdir(outdir, reference_genome):\n\n # define the...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return PetriNetData object that contains the petri net specifications in matrix form.
def petri_net_data(self): return self._pn_data
[ "def read_petri_net(file_path):\n from pm4py.objects.petri.importer import importer as pnml_importer\n net, im, fm = pnml_importer.apply(file_path)\n return net, im, fm", "def create_petri_net_data_backup(self):\n self._prev_pn_data = self._pn_data.clone()", "def petri_net_data(self, data):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set PetriNetData object that contains the petri net specifications in matrix form.
def petri_net_data(self, data): self._pn_data = data
[ "def petri_net_data(self):\n return self._pn_data", "def create_petri_net_data_backup(self):\n self._prev_pn_data = self._pn_data.clone()", "def _set_tensor(self, indata):\n\n if isinstance(indata, np.ndarray):\n if indata.ndim == 2 or indata.ndim == 3:\n self.data...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return dictionary of places (dictionary key is the key of the component).
def places(self): return self._places
[ "def get_all_places():\n places = {'places': []}\n\n conn = sqlite3.connect('places.db')\n cursor = conn.cursor()\n\n sql = 'SELECT local_name, full_address, latitude, longitude, place_id FROM places'\n\n for place in cursor.execute(sql):\n place_modal = {}\n place_modal['local_name'] =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set dictionary of places (dictionary key is the key of the component).
def places(self, data): self._places = data
[ "def add_place(self, component):\n # check if component is valid\n if component == None:\n return False\n # check if key is valid\n if component.key != \"\" and not self._places.has_key(component.key):\n # check object type\n if type(component) == place.P...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return dictionary of arcs (dictionary key is the key of the component).
def arcs(self): return self._arcs
[ "def map_ac(self, nodes='all'):\n if nodes == 'all':\n nodes = self.nodes\n \n acmap = {}\n for node in nodes:\n acmap[node] = self.compute_node_centrality(node)\n return acmap", "def get_bonds_dict(spc: ARCSpecies) -> Dict[str, int]:\n bond_dict = d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set dictionary of arcs (dictionary key is the key of the component).
def arcs(self, data): self._arcs = data
[ "def __setitem__(self, key: str, value: float) -> None:\n if key == 'x':\n self.x = value\n elif key == 'y':\n self.y = value\n elif key == 'z':\n self.z = value", "def set_assets(self, asset_dict):\n self._assets = asset_dict", "def addArmatureKey(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new component to the petri net. It is not necessary to define the component type because it will be determined automatically. TRUE will be returned if the component could be added and otherwise FALSE.
def add(self, component): # check if component is valid if component == None: return False # according to the object type the component will be added if type(component) == place.Place: return self.add_place(component) if type(component) == transition.Trans...
[ "def add_component(self, component):\n self.components.append(component)", "def test_component_add_ok(self):\n self.execute('component add new_component')\n rv, output = self.execute('component list')\n self.assertEqual(0, rv, output)\n self.assertExpectedResult(output)", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new place to the petri net. TRUE will be returned if the component could be added and otherwise FALSE.
def add_place(self, component): # check if component is valid if component == None: return False # check if key is valid if component.key != "" and not self._places.has_key(component.key): # check object type if type(component) == place.Place: ...
[ "def add(self, component):\n # check if component is valid\n if component == None:\n return False\n # according to the object type the component will be added\n if type(component) == place.Place:\n return self.add_place(component)\n if type(component) == tran...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new transition to the petri net. TRUE will be returned if the component could be added and otherwise FALSE.
def add_transition(self, component): # check if component is valid if component == None: return False # check if key is valid if component.key != "" and not self._transitions.has_key(component.key): # check object type if type(component) == transition....
[ "def addTransition(self, transition: 'ScXMLTransitionElt') -> \"void\":\n return _coin.ScXMLParallelElt_addTransition(self, transition)", "def addTransition(self, transition: 'ScXMLTransitionElt') -> \"void\":\n return _coin.ScXMLStateElt_addTransition(self, transition)", "def add_flow(self,flow):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new arc to the petri net. TRUE will be returned if the component could be added and otherwise FALSE.
def add_arc(self, component): # check if component is valid if component == None: return False # check if key is valid if component.key != "" and not self._arcs.has_key(component.key): # check object type if type(component) == arc.Arc or type(component...
[ "def add_arc(self, start_node, goal_node):\n\t\tif start_node not in self.get_nodes():\n\t\t\traise ValueError(\"node {0} not in network\".format(start_node))\n\t\tif goal_node not in self.get_nodes():\n\t\t\traise ValueError(\"node {0} not in network\".format(goal_node))\n\t\telse:\n\t\t\tadd_arc(self.network, sta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update an existing component or the petri net. It is not necessary to define the component type because it will be determined automatically. TRUE will be returned if the component could be updated and otherwise FALSE.
def update(self, component, key): # check if component is valid if component == None: return False # update component according to its object type if type(component) == place.Place: return self.update_place(component, key) if type(component) == transition....
[ "def isComponent(self):\n\tif self.__componentMode__ and self.__component__:\n\t buffer = '%s.%s'%(self.mNode,self.__component__)\n\t if mc.objExists(buffer):return True\n\t else:log.warning(\"Component no longer exists: %s\"%self.__component__)\n\t return False\n\treturn False", "def check_component_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove an existing place of the petri net. TRUE will be returned if the component could be removed and otherwise FALSE.
def remove_place(self, component): # check if component is valid if component != None: # check object type if type(component) == place.Place: # remove place del self._places[component.key] return True return False
[ "def removePiece(self,piece):\n try:\n self.pieces.remove(piece)\n return True\n except ValueError:\n return False", "def setNetPath(self, net):\n toremove = net.path[1:-1]\n for i, (x, y, z) in enumerate(toremove):\n if not self.setElementAt(net, x, y, z):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove an existing transition of the petri net. TRUE will be returned if the component could be removed and otherwise FALSE.
def remove_transition(self, component): # check if component is valid if component != None: # check object type if type(component) == transition.Transition: # remove transition del self._transitions[component.key] return True ...
[ "def removeTransition(self, transition: 'ScXMLTransitionElt') -> \"void\":\n return _coin.ScXMLParallelElt_removeTransition(self, transition)", "def removeTransition(self, transition: 'ScXMLTransitionElt') -> \"void\":\n return _coin.ScXMLStateElt_removeTransition(self, transition)", "def remove_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove an existing arc of the petri net. TRUE will be returned if the component could be removed and otherwise FALSE.
def remove_arc(self, component): # check if component is valid if component != None: # check object type if type(component) == arc.Arc or type(component) == inhibitory_arc.InhibitoryArc or type(component) == test_arc.TestArc: # remove arc del self....
[ "def remove(self, components):\n del_comp = True\n # remove all arcs from the list if one of its components will be removed (origin or target)\n for comp in components:\n # go through the available arcs\n for key, item in self._arcs.items():\n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a list of existing components of the petri net. It will be determined automatically from which dictionary the component needs to be removed. TRUE will be returned if the component could be removed and otherwise FALSE.
def remove(self, components): del_comp = True # remove all arcs from the list if one of its components will be removed (origin or target) for comp in components: # go through the available arcs for key, item in self._arcs.items(): try: ...
[ "def unfreeze_components(self, components: List[str]):\n for component in components:\n for param in self.components[component].parameters():\n param.requires_grad = True", "def test_component_remove_ok(self):\n self.execute('component remove component1')\n rv, outpu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove an existing place of the petri net according to its key. TRUE will be returned if the component could be removed and otherwise FALSE.
def remove_place_key(self, key): # check if key is valid if key != "" and self._places.has_key(key): # remove place del self._places[key] return True return False
[ "def remove_key(self, key):\n # check if key is valid\n if key != \"\":\n # according to the key it will be determined which list contains this key and the component will be removed\n if self._places.has_key(key):\n return self.remove_place_key(key)\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove an existing transition of the petri net according to its key. TRUE will be returned if the component could be removed and otherwise FALSE.
def remove_transition_key(self, key): # check if key is valid if key != "" and self._transitions.has_key(key): # remove transition del self._transitions[key] return True return False
[ "def remove_key(self, key):\n # check if key is valid\n if key != \"\":\n # according to the key it will be determined which list contains this key and the component will be removed\n if self._places.has_key(key):\n return self.remove_place_key(key)\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove an existing arc of the petri net according to its key. TRUE will be returned if the component could be removed and otherwise FALSE.
def remove_arc_key(self, key): # check if key is valid if key != "" and self._arcs.has_key(key): # remove arc del self._arcs[key] return True return False
[ "def remove_arc(self, component):\n # check if component is valid\n if component != None:\n # check object type\n if type(component) == arc.Arc or type(component) == inhibitory_arc.InhibitoryArc or type(component) == test_arc.TestArc:\n # remove arc\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove an existing component of the petri net according to its key. It will be determined automatically from which dictionary the component needs to be removed. TRUE will be returned if the component could be removed and otherwise FALSE.
def remove_key(self, key): # check if key is valid if key != "": # according to the key it will be determined which list contains this key and the component will be removed if self._places.has_key(key): return self.remove_place_key(key) if self._transi...
[ "def remove_place(self, component):\n # check if component is valid\n if component != None:\n # check object type\n if type(component) == place.Place:\n # remove place\n del self._places[component.key]\n return True\n return Fal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a place according to the defined key and if it cannot be found None will be returned.
def get_place(self, key): # check if key is valid if key != "" and self._places.has_key(key): # return place return self._places[key] return None
[ "def find(self, key):\n _, current, _ = self._linear_search(key)\n\n if current is None:\n value = None\n else:\n value = copy.deepcopy(current._value)\n return value", "def get_elem(self, key):\n\n the_hash = self._hash(key)\n\n for index in self._i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a transition according to the defined key and if it cannot be found None will be returned.
def get_transition(self, key): # check if key is valid if key != "" and self._transitions.has_key(key): # return transition return self._transitions[key] return None
[ "def successor_by_key(self,key) -> Node:\r\n return self.successor(self.search(key))", "def __find_current_state_transition(self, symbol):\n for transition in self.__dfa_dict['transitions']:\n if transition['from'] == self.__current_state and symbol in transition['symbols']:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an arc according to the defined key and if it cannot be found None will be returned.
def get_arc(self, key): # check if arc is valid if key != "" and self._arcs.has_key(key): # return arc return self._arcs[key] return None
[ "def find_arc(self, src, ilabel=None, olabel=None, dst=None):\n\n assert src < len(self.states)\n for arc in reversed(self.states[src].arcs):\n if ((ilabel is None) or (arc.ilabel == ilabel)) and\\\n ((olabel is None) or (arc.olabel == olabel)) and\\\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a component (place, transition or arc) according to the defined key and if it cannot be found None will be returned.
def get_component(self, key): component = self.get_place(key) if component == None: component = self.get_transition(key) if component == None: component = self.get_arc(key) return component
[ "def get_arc(self, key):\n # check if arc is valid\n if key != \"\" and self._arcs.has_key(key):\n # return arc\n return self._arcs[key]\n return None", "def get_place(self, key):\n # check if key is valid\n if key != \"\" and self._places.has_key(key):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine which component is the nearest to the define position (x and ydimension) under regarding of a virtual buffer/tolerance zone around the components that the user does not have to define exactly a position within the component. If no component can be identified None will be returned.
def get_nearest_component(self, position): # the minimal distance to a component comp_dist = -1 # the nearest component comp = None # the buffer zone around a place is 10 # check if the nearest component is a place for key, value in self._places.items(): ...
[ "def componentsPosition(x, y):\n return int(solution[x + y * self._width])", "def find_winner(self):\n distance_matrix = np.array([node.distance for node in self.__get_map_element(\n self.model.map,\n self.model.dimensions\n )])\n distance_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a position is on a virtual line between the start and endposition under regarding a buffer/tolerance zone around the line. If the position is on the line TRUE will be returned and otherwise FALSE.
def __is_on_virtual_line(self, position, start_position, end_position): # difference between end- and start-position in x-dimension dx = float(int(end_position[0] - start_position[0])) # difference between end- and start-position in y-dimension dy = float(int(end_position[1] - start_pos...
[ "def _is_on_line(x, y, ax, ay, bx, by):\n return ((bx - ax) * (y - ay) == (x - ax) * (by - ay) and\n ((ax <= x <= bx or bx <= x <= ax) if ax != bx else\n (ay <= y <= by or by <= y <= ay)))", "def line_in_region(vcf_line, chrom, start, end):\n variant_chrom, variant_start = vcf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine all components except arc within a rectangular area defined through a start and endposition. If components are included a list with those will be returned and otherwise an empty list.
def get_selected_components_without_arcs(self, start_position, end_position): # list of selected components components = [] # change start- and end-position if necessary for i in range(len(start_position)): if start_position[i] > end_position[i]: h = end_po...
[ "def get_selected_components_with_arcs(self, start_position, end_position):\n\n components = []\n tolerance = 20\n tolerance_place = 10\n\n for i in range(len(start_position)):\n if start_position[i] > end_position[i]:\n h = end_position[i]\n end_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine all components within a rectangular area defined through a start and endposition. An arc will only be added if its origin and target are also within the defined area. If components are included a list with those will be returned and otherwise an empty list.
def get_selected_components_with_arcs(self, start_position, end_position): components = [] tolerance = 20 tolerance_place = 10 for i in range(len(start_position)): if start_position[i] > end_position[i]: h = end_position[i] end_position[i] = ...
[ "def get_selected_components_without_arcs(self, start_position, end_position):\n\n # list of selected components \n components = []\n\n # change start- and end-position if necessary\n for i in range(len(start_position)):\n if start_position[i] > end_position[i]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a dictionary which also will be returned containing all positions of each component. The key of the dictionary is the key of the component.
def get_positions(self): # dictionary that stores positions of the components pos = dict() # read the positions of the places for key, value in self._places.items(): pos[value.key] = value.position # read the positions of the transitions for key, valu...
[ "def getPositionsDict(self):\n return {ID: self.elements[ID].getPosition() for ID in self.elements}", "def calculate_positions(self):\n positions = {}\n row_number = 0\n for row in self.board.board:\n cell_number = 0\n number_of_cells = len(row)\n for c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the positions of the single components. The key of the dictionary positions is the key of the components.
def set_positions(self, positions): # iteration through all positions for key, value in positions.items(): # read component component = self.get_component(key) # check if component could be read if component != None: # assign position ...
[ "def set_initial_state(self, positions: List[list]):\n for pos in positions:\n self.grid[pos[0]][pos[1]] = 1", "def setPos(self, x1,y1=None ):\n if type(x1) == list or type(x1) == tuple:\n y1=x1[1]\n x1=x1[0]\n if self.getCubeTiles()[3]:\n self.cube...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the components onto the defined GraphicsContext ctx.
def draw(self, ctx): ctx.set_source_rgb(1., 1., 1.) ctx.paint() # draw the places onto the referenced surface for key, item in self._places.items(): item.draw(ctx) # draw the transitions onto the referenced surface for key, item in self._transitions.items()...
[ "def draw(self, canvas): \n self.draw_grid(canvas)", "def draw(self, canvas):\n pass", "def draw(self) -> None:\n\n \"\"\"\n TODO: Add logic for handling multiple draw functions\n \"\"\"\n pass", "def Draw(self, dc, withChildren=False):\n if self._visibl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine the paths which are used for a transition to fire and only standard arcs will be regarded.
def get_detailed_paths(self, transition_component = None): # multi-dimensional list that contains all possible paths from the origin to the target component via the defined tarnsition path_collection = [] # check if an origin and target are defined # read input arcs of the target ...
[ "def find_coarse_paths(self, current_state, path_so_far):\n if len(path_so_far) == self.num_steps:\n if current_state == self.final_state:\n self.coarse_paths.append(path_so_far[:])\n return\n # Try Pour\n for i in range(len(current_state)):\n for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine the path from an origin place to a target place via a transition. Only standard arcs will be regarded and at least a target or origin place with a transition need to be defined otherwise the input is invalid and no path can be determined. A multidimensional array with valid paths will be returned. Dimension o...
def get_detailed_path(self, target_component = None, transition_component = None, origin_component = None): # multi-dimensional list that contains all possible paths from the origin to the target component via the defined tarnsition path_collection = [] # check if an origin and target are defin...
[ "def get_detailed_paths(self, transition_component = None):\n\n # multi-dimensional list that contains all possible paths from the origin to the target component via the defined tarnsition\n path_collection = []\n # check if an origin and target are defined\n\n # read input arcs of the t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine the input arcs of a component and a list containing those will be returned. The weight parameter is optional and if it is defined only input arcs with the defined weight will be regarded. If the defined component does not have any an empty list will be returned.
def get_input_arcs(self, component, weight = None): # list of input arcs inputs = [] # iteration through all arcs for key, value in self._arcs.items(): # check if the target component is equal to the defined one if component.is_equal(value.target): ...
[ "def get_output_arcs(self, component, weight = None):\n\n # list of output arcs\n outputs = []\n # iteration through all arcs\n for key, value in self._arcs.items():\n # check if the origin component is equal to the defined one\n if component.is_equal(value.origin):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine the output arcs of a component and a list containing those will be returned. The weight parameter is optional and if it is defined only output arcs with the defined weight will be regarded. If the defined component does not have any an empty list will be returned.
def get_output_arcs(self, component, weight = None): # list of output arcs outputs = [] # iteration through all arcs for key, value in self._arcs.items(): # check if the origin component is equal to the defined one if component.is_equal(value.origin): ...
[ "def get_input_arcs(self, component, weight = None):\n\n # list of input arcs\n inputs = []\n # iteration through all arcs\n for key, value in self._arcs.items():\n # check if the target component is equal to the defined one\n if component.is_equal(value.target):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return TRUE if a connection defined through an arc component is valid.
def valid_connection(self, component): # check the object type if type(component) == arc.Arc: # check if the origin and target are correct defined if (type(component.origin) == place.Place and type(component.target) == transition.Transition) or (type(component.origin) == transit...
[ "def has_arc(self) -> bool:\n if self.is_2d_polyline:\n return any(\n v.dxf.hasattr(\"bulge\") and bool(v.dxf.bulge) for v in self.vertices\n )\n else:\n return False", "def can_be_connected(a_direction, b_direction):\n if a_direction == Direction.I...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a backup of the current PetriNetData object. Only one backup can be stored.
def create_petri_net_data_backup(self): self._prev_pn_data = self._pn_data.clone()
[ "def create_backup(self, instance, name, description=None):\r\n return instance.create_backup(name, description=description)", "def clone(self):\n return Savepoint('',\n impl=invoke(lib.serialboxSavepointCreateFromSavepoint, self.__savepoint))", "def create_backup(self, nam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Restore the previous markings.
def reset(self): for i in range(len(self._prev_pn_data.places)): for key, item in self._places.items(): if item.label == self._prev_pn_data.places[i]: self._places[key].marking = self._prev_pn_data.initial_marking[i]
[ "def restore(self):\n\n # Restore the sets\n try:\n self.mr.master_atoms_mapped.discard(self.mr.last_mapped[1])\n self.mr.sub_atoms_mapped.discard(self.mr.last_mapped[0])\n self.mr.atom_mapping.discard(self.mr.last_mapped)\n except IndexError:\n # hap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configure webhooks and create requestbin.
def setup(requestbin, request, threescale): threescale.webhooks.setup("Applications", requestbin.url) request.addfinalizer(threescale.webhooks.clear)
[ "def setup(requestbin, request, threescale):\n threescale.webhooks.setup(\"Keys\", requestbin.url)\n request.addfinalizer(threescale.webhooks.clear)", "def setup(self):\n # Listen for all updates\n self._init_webhooks()", "def create(self, webhook):\n raise NotImplementedError('create...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if webhook response for user key updated
def test_user_key_updated(): # TODO - Missing API endpoint # https://issues.redhat.com/browse/THREESCALE-5347
[ "def webhook():\n update = Update.de_json(request.get_json(), bot)\n dp.process_update(update)\n return \"ok\"", "def validate_request(self, hmac_key, request):\n\n hash_ = hmac.new(self.HMAC[hmac_key], request.data, sha256)\n\n # check if from phabricator\n if hash_.hexdigest() == r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CI will run test_circular_dependencies in test/test_testing.py which tries to import all modules found. Enclosing the imports in a function so CI that does not have torch_xla installed will not break.
def import_torchxla(): global torch_xla, xm, metrics import torch_xla import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as metrics
[ "def test_circular_dependencies():\n venv = make_venv()\n\n out, err = run(\n venv.join('bin/pip-faster').strpath,\n 'install',\n '-vv', # show debug logging\n 'circular-dep-a',\n )\n err = strip_pip_warnings(err)\n assert err.strip() == (\n 'Circular dependency! c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find a kq to put
def _kq_toput(self, key=None): return self._next_kq(key=key, next=self._nextput, notfound_exc=Empty)
[ "def addque(self, qkey, queue, update=False):\n if update or (qkey not in self.kqmap):\n self.kqmap[qkey] = queue", "def find(self, key):\n if key not in self.data:\n self.data[key] = key\n return key\n elif key == self.data[key]:\n return key\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Directly add queue to the current queue group. If update is False, the queue will not be updated if it already exists in the kqmap. This is a low level interface, use it cautiously
def addque(self, qkey, queue, update=False): if update or (qkey not in self.kqmap): self.kqmap[qkey] = queue
[ "def _add_queue(self, name, register_event):\n q = queue.Queue()\n register_event(q.put)\n self._queues[name] = q", "def add_queue(self, pycl_object=None, name=None, data=None,\n metadata=None, json_string=None):\n return self.cluster_queue_manager.add_object(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return material of the element
def GetElementMaterial(self): return self._ElementMaterial
[ "def material(self):\n return self.edb_padstack.GetData().GetMaterial()", "def _nativeMaterial( self ):\r\n\t\treturn self._nativePointer.material", "def material(self):\n\t\tnativeMaterial = self._nativeMaterial()\n\t\tif (nativeMaterial):\n\t\t\tfrom cross3d import SceneMaterial\n\t\t\treturn SceneMate...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the Location Matrix of the element
def GetLocationMatrix(self): return self._LocationMatrix
[ "def location(s, (x,y)):\n\t\treturn s.matrix[x][y]", "def get_location(self):\n ret = _pal.Mat4x4()\n _pal.lib.body_base_get_location(self._body_base, ret)\n return [x for x in ret]", "def get_element_location(element):\n element_coord = element.location\n return int(element_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the size of the element stiffness matrix (stored as an array column by column)
def SizeOfStiffnessMatrix(self): pass
[ "def size(self, matrix):\r\n return matrix.shape", "def mat_size(self):\n\n # Length of the linear array\n l = self.size\n\n # Total number of elements in the corresponding bi-dimensional symmetric matrix\n n = int((1 + math.sqrt(1 + 8 * l)) / 2)\n\n return n", "def __l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scalar is transformed to a vector of length lg with a 1 at position scalar and zeros otherwise
def vectorize(scalar, lg): vec = np.zeros(lg) vec[scalar] = 1 return vec
[ "def log_with_zeros(x):\n x = torch.max(x, torch.tensor(1e-10))\n return torch.log(x)", "def testLogLinearlyScaledIsZero(self):\n self.assertEqual(lmath.LOG_ONE, feature.LogLinearlyScaled(0., _MAXIMUM))", "def scalarProject(self, vec):\n return self.dot(vec) / vec.magnitude()", "def relu(z):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the lines of the file, removing all lines consisting of symbols.
def generate_lines(file): symbol_lines = re.compile(r'^[\d\W]+$') return [line for line in file.readlines() if not symbol_lines.search(line)]
[ "def _cleanlines(textfile):\n result = []\n with open(textfile, 'r') as f:\n for line in f:\n ix = line.find('#')\n if ix >= 0:\n line = line[:ix]\n line = line.strip()\n if line:\n result.append(line)\n return result", "def read_and_strip_text_file(pathin):\n f = open(p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The function creates a dictionary with Variable and value. If Variable has "." separated keys then the value is updated at appropriate level of the nested dictionary.
def get_dict_to_update(var, val): dic = {} if '.' in var: [key, value] = var.split('.', 1) dic[key] = get_dict_to_update(value, val) else: dic[var] = val return dic
[ "def insert_to_dict_at_level(dictionary, dict_key_path, dict_value):\n\n dictionary_nested_in = dictionary\n\n for key in dict_key_path[:-1]:\n if key not in dictionary_nested_in:\n dictionary_nested_in[key] = {}\n dictionary_nested_in = dictionary_nested_in[key]\n\n dictionary_nes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run board, invokes setup() and loop() methods.
def run(self): # First setup board self.setup() # Loop forever self.loop()
[ "def board_negotiation_run(self):\n print \"Negotiating board...\"\n self.decided_board = self.run_public_shuffle(range(19), board.board_shuffle_and_encrypt, board.board_decrypt)\n time.sleep(3)\n print \"Negotiating board roll values...\"\n self.decided_board_roll_values = self.r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implement this method to read your custom file
def __readfile(self): raise NotImplementedError
[ "def _read_file(self):\n with open(self.file, 'r') as the_file:\n content = the_file.read()\n return content", "def readin(self):\n \n if self.filename.endswith('.fits'):\n # Assumes Science Verification data\n self.read_SV_fits()\n elif self.filename.endswith('.npz')...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts the interactions into a graph object
def _convert_to_graph(self) -> nx.Graph: graph = nx.Graph() graph.add_edges_from(self.interactions) graph.remove_edges_from(graph.selfloop_edges()) return graph
[ "def graph(self):\n pass", "def interactions(self):\n return self.__graph.labels()", "def _to_graph(self) -> Graph:\n self._add_concept_to_graph()\n\n return self._g", "async def make_graph(self, args):\n return self._graph", "def graph_representation(\n self,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the nx.graph object of the network
def get_network(self) -> nx.Graph: return self.graph
[ "def get_network_object(self):\n return self.g", "def gen_networkx_graph(self):\n\n\t\tgraph = nx.DiGraph()\n\n\t\t# add each node into the graph - node number used to map the nodes\n\t\t# in CPPN to the corresponding nodes in the graph\n\t\tfor node in self.nodes:\n\t\t\tgraph.add_node(node.getNodeNum())\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the data of the gmt file
def get_data(self) -> dict: return self.gmt_data
[ "def datagram_filetime(datagram):\n d = datagram.dgheader.datetime\n return filetime(d)", "def read_timetolive(filename):\n if not os.path.isfile(filename):\n return {}\n ttl_file = open(filename, 'r')\n data = json.load(ttl_file)\n ttl_file.close()\n return data", "def read_data_ext...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This command will update bloggercli if you have installed it with custom installation.
def cli(version, force, accept_all): custom = [False for i in [".blogger_cli", "venv"] if i not in ROOT_DIR] if False in custom: click.secho( "blogger-cli was not installed by recommended method", "Use pip install --upgrade blogger-cli instead to upgrade", bold=True,...
[ "def upgrade_cmd(ctx, to_version):\n logger = logging.getLogger('populus.cli.upgrade')\n project_dir = ctx.obj['PROJECT_DIR']\n\n upgrade_configs(project_dir, logger, to_version)", "def update(args) -> int:\n _update_cache()\n print(\"Listing upgradable packages...\")\n _list_upgradable\n pri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a value in USD to equivalent CAD given a date
def USD_CAD_rate(date: datetime.datetime) -> float: # ToDo: Figure out why this isn't working # c = CurrencyRates() #rate = c.get_rate('USD', 'CAD', date) rate = 1.3 return rate
[ "def yenToDollars(yen):\n # complete the function ", "def convert(value, from_, to, date):\n\trate = get_rate_as_at(date, from_, to)\n\tconverted_value = flt(value) / (rate or 1)\n\treturn converted_value", "def to_euro(self, cid):\n query = sql.SQL(\"SELECT currency_value FROM currency WHERE id={cid}...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if tbl_data is list of lists
def is_list_of_lists(tbl_data): if not isinstance(tbl_data, list): return False return all(isinstance(item, list) for item in tbl_data)
[ "def is_list(x):\n return type(x) == list", "def _check_is_list(obj):\n return isinstance(obj, (list, List))", "def _is_list(e):\n return isinstance(e, LIST_TYPE)", "def is_list(obj):\n return isinstance(obj, list)", "def is_list(val):\n return isinstance(val, list)", "def isList(obj):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[2, 7, 8, 5, 1, 6, 3, 9, 4] find_peaks while peaks exist, remove minimal peaks
def deleteMinimalPeaks(numbers): def find_peaks(numbers): peaks=[] for idx, num in enumerate(numbers): peak = True if idx > 0: if num < numbers[idx-1]: peak = False if idx < len(numbers)-1: if n...
[ "def detect_peaks_1d(timeseries, delta_peak, threshold, peak_width=5):\n\n # Sort time series by magnitude.\n max_idx = np.squeeze(timeseries.argsort())[::-1]\n\n # Remove peaks within delta_peak to the array boundary\n max_idx = max_idx[max_idx > delta_peak]\n max_idx = max_idx[max_idx < np.size(tim...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A dynamic load balancing parallel implementation of itertools.starmap for IPython.parallel. The reason for it's existence was twofold. First, the desire to easily submit a 'map' onto inputs already grouped in tuples in IPython.parallel. Second was the ability to submit a 'map' onto very large sequences. Potentially inf...
def starmap(func, iterable, **kwargs): profile = kwargs.pop('profile', None) rc = kwargs.pop('client', None) max_fill = kwargs.pop('max_fill', 50000) wait = kwargs.pop('wait',1) if rc is None: rc = Client(profile=profile) elif not isinstance(rc, Client): raise ValueError('client ...
[ "def mapreduce (filename, setnum = 8192, cores = 20):\n\tfp = open(filename, 'r')\n\tshared = {}\n\tprivated = {}\n\taddrlist = []\n\tfor i in range(8192):\n\t\taddrlist.append([])\n\tfor line in fp:\n\t\ttry:\n\t\t\tword = line.split(\" \")\n\t\t\ttid = int(word[0], 0)\n\t\t\tinst = int(word[1], 0)\n\t\t\tadd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add the constraints to the error_log table.
def add_constraints(persister=None): persister.exec_stmt( ErrorLog.ADD_FOREIGN_KEY_CONSTRAINT_SERVER_UUID)
[ "def write_constraints(self, table):\n constraint_sql = super(PostgresDbWriter, self).write_constraints(table)\n for sql in constraint_sql:\n self.execute(sql)", "def _add_configuration_constraints(self) -> None:\n for (item_type, time_period) in product(range(self.prob_input.num_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a server's error log.
def add(server, reported, reporter, error, persister=None): from mysql.fabric.server import MySQLServer assert(isinstance(server, MySQLServer)) persister.exec_stmt(ErrorLog.INSERT_SERVER_ERROR_LOG, {"params": (str(server.uuid), reported, reporter, error)})
[ "def log_error(self, error, save=False):\n self.log[\"errors\"].append(f\"{error}\")\n if save:\n self.save_log()", "def _log_server_exception(self, e):\n template = \"\"\"Exception occurred:\n href: %(h)s\n method: %(m)s\n status: %(s)s\n err...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a ErrorLog object corresponding to the server.
def fetch(server, interval, now=None, persister=None): from mysql.fabric.server import MySQLServer assert(isinstance(server, MySQLServer)) now = now or get_time() (whens, reporters) = ErrorLog.compute( server.uuid, interval, now ) return ErrorLog(server, inte...
[ "def describe_dbinstance_error_log(\n self,\n request: gpdb_20160503_models.DescribeDBInstanceErrorLogRequest,\n ) -> gpdb_20160503_models.DescribeDBInstanceErrorLogResponse:\n runtime = util_models.RuntimeOptions()\n return self.describe_dbinstance_error_log_with_options(request, run...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the associated server's UUID.
def server_uuid(self): return self.__server_uuid
[ "def get_server_id():\n return getattr(seaserv, 'SERVER_ID', '-')", "def get_server_id(self):", "def uuid(self) -> str:\n self._logger.info(\"Retrieving device UUID...\")\n return self._device_info().get(\"uuid\")", "def get_uuid(self): # real signature unknown; restored from __doc__\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the start time provided in the request.
def get_time_start_from_request(request): time_start_ms = request.args.get("time_start", 0) time_start = datetime.fromtimestamp(int(time_start_ms)) return time_start
[ "def event_start_time(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"event_start_time\")", "def get_start_time(self):\n\n return self.time_vector[0]", "def event_start_time(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"event_start_time\")", "def utc_start_time...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the end time provided in the request.
def get_time_end_from_request(request): time_end_ms = request.args.get("time_end", 0) time_end = datetime.fromtimestamp(int(time_end_ms)) return time_end
[ "def end_time(self):\n ret = self._get_attr(\"endTime\")\n return ret", "def getEndTime(self):\n return self.endTime", "def frame_end_time(self) -> str:\n return pulumi.get(self, \"frame_end_time\")", "def get_endTime(trip):\n if not get_running(trip):\n trip_keys = trip....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the list of terms provided in the request.
def get_terms_from_request(request): terms = [] raw_terms = request.args.get("terms", "").split(",") # Sanitize terms, and add non-empty elements to the list for term in raw_terms: term = term.strip().lower() if not term == "": terms.append(term) return terms
[ "def getAvailableTerms():\n # type: () -> List[String]\n return [\"term1\", \"term2\"]", "def terms(self):\n return self._offr['terms'].keys()", "def get_terms(self):\n \n return self.overall_terms", "def get_query_terms(argv):\n if argv is None:\n argv = sys.argv\n arg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if request is for a download, false otherwise.
def get_is_download_from_request(request): is_download = request.args.get("download", "").strip().lower() return ("true" == is_download)
[ "def isDownloading(self) -> bool:\n return self._is_downloading", "def is_download(self) -> Optional[bool]:\n is_download = self._config.is_download or IS_DOWNLOAD\n return self._to_optional_bool_with_check(is_download, \"is_download\")", "def is_downloadable(url, auth=None):\n # Ends wi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get Raw Data of the Event
def GetEventRawData(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
[ "def getData(self):\n return bytes(self.rawData)", "def get_data_via_sse(self):\n cherrypy.response.headers[\"Content-Type\"] = \"text/event-stream;charset=utf-8\"\n cherrypy.response.headers[\"Cache-Control\"] = \"no-cache\"\n cherrypy.response.headers[\"Connection\"] = \"keep-alive\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get list of edges and the one or two adjacent faces in a list. also get center point of edge Each edge would be [pointnum_1, pointnum_2, facenum_1, facenum_2, center]
def get_edges_faces(input_points, input_faces): # will have [pointnum_1, pointnum_2, facenum] edges = [] # get edges from each face for facenum in range(len(input_faces)): face = input_faces[facenum] num_points = len(face) # loop over index into face for pointindex in...
[ "def _GetFaceGraph(faces, edges, vtoe):\n\n face_adj = [ [] for i in range(len(faces)) ]\n is_interior_edge = [ False ] * len(edges)\n for e, ((vs, ve), f) in enumerate(edges):\n for othere in vtoe[ve]:\n ((_, we), g) = edges[othere]\n if we == vs:\n # face g is adjacent to face f\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
for each point calculate the average of the face points of the faces the point belongs to (avg_face_points) create a list of lists of two numbers [facepoint_sum, num_points] by going through the points in all the faces. then create the avg_face_points list of point by dividing point_sum (x, y, z) by num_points
def get_avg_face_points(input_points, input_faces, face_points): # initialize list with [[0.0, 0.0, 0.0], 0] num_points = len(input_points) temp_points = [] for pointnum in range(num_points): temp_points.append([[0.0, 0.0, 0.0], 0]) # loop through faces updating temp_points f...
[ "def get_avg_mid_edges(input_points, edges_faces):\n \n # initialize list with [[0.0, 0.0, 0.0], 0]\n \n num_points = len(input_points)\n \n temp_points = []\n \n for pointnum in range(num_points):\n temp_points.append([[0.0, 0.0, 0.0], 0])\n \n # go through edges_faces using center updating e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the average of the centers of edges the point belongs to (avg_mid_edges) create list with entry for each point each entry has two elements. one is a point that is the sum of the centers of the edges and the other is the number of edges. after going through all edges divide by number of edges.
def get_avg_mid_edges(input_points, edges_faces): # initialize list with [[0.0, 0.0, 0.0], 0] num_points = len(input_points) temp_points = [] for pointnum in range(num_points): temp_points.append([[0.0, 0.0, 0.0], 0]) # go through edges_faces using center updating each point ...
[ "def get_bin_centers(edges):\n l = len(edges)\n centers = []\n for idx in range(l - 1):\n center = (edges[idx] + edges[idx + 1]) / 2\n center = float(\"{:.3f}\".format(center)) # limit to three decimals\n centers.append(center)\n\n return centers", "def midpoints(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the margin for each sample defined as logits(y) max_{y != t}[logits(t)]
def get_margin(self, epoch: int) -> np.ndarray: margin = np.full(self.num_samples, np.nan) logits = self.logits_per_sample[:, :, epoch] for i in range(self.num_samples): label = int(self.labels[i]) assigned_logit = logits[i, label] order = np.argsort(logits[i]...
[ "def test_margin_loss(self):\n scewl = tf.nn.softmax_cross_entropy_with_logits\n for variant in ['linear', 'cosine', 'sigmoid']:\n for margin in [1.5, 2, 2.5, 3, 3.5, 4]:\n with tf.Graph().as_default():\n with tf.Session() as sess:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Logs histogram of loss values of one of the coteaching models.
def log_loss_values(self, writer: SummaryWriter, loss_values: np.ndarray, epoch: int) -> None: writer.add_histogram('loss/all', loss_values, epoch)
[ "def log_losses(self):\n for loss_name, running_loss in self.running_losses.items():\n self.tensorboard_writer.add_scalar('Loss/' + loss_name, running_loss / self.running_loss_step, self.step)\n self.init_losses()", "def entropy_loss(policy_logits, masks):\n return np.mean(compute_over_a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }