code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def get_instance_dict_from_attrs(obj, attr_names): <NEW_LINE> <INDENT> d = {} <NEW_LINE> for attr_name in attr_names: <NEW_LINE> <INDENT> nested_attrs = attr_name.split('.') <NEW_LINE> attr = obj <NEW_LINE> for nested_attr in nested_attrs: <NEW_LINE> <INDENT> attr = getattr(attr, nested_attr) <NEW_LINE> <DEDENT> if cal... | Given a model instance and a list of attributes, returns a dict | 625941c257b8e32f52483433 |
def p_principal(p): <NEW_LINE> <INDENT> p[0] = Tree('principal', [p[6]]) | principal : VAZIO PRINCIPAL ABRE_PAR FECHA_PAR NOVA_LINHA sequencia_decl FIM | 625941c28e71fb1e9831d744 |
def debconf_progress_stop(self): <NEW_LINE> <INDENT> return | Stop the current progress bar. | 625941c2a8ecb033257d3067 |
def get_coordinate_systems_for_filters(self, galaxy_name, filters): <NEW_LINE> <INDENT> coordinate_systems = [] <NEW_LINE> for fltr in filters: coordinate_systems.append(self.get_coordinate_system_for_filter(galaxy_name, fltr)) <NEW_LINE> return coordinate_systems | This function ...
:param galaxy_name:
:param filters:
:return: | 625941c27047854f462a13a5 |
def test_display_current_time_at_current_time(self): <NEW_LINE> <INDENT> production_code_time_provider = ProductionCodeTimeProvider() <NEW_LINE> class_under_test = TimeDisplay() <NEW_LINE> current_time = datetime.datetime.now() <NEW_LINE> expected_time = "<span class=\"tinyBoldText\">{}:{}</span>".format(current_time.h... | Just as justification for working example with the time provider used in
production. (Will always pass.) | 625941c271ff763f4b549621 |
def getState(self): <NEW_LINE> <INDENT> return self.__state | @types: -> AvailabilityZone.State | 625941c232920d7e50b28168 |
@register.tag <NEW_LINE> def is_registered_user(parser, token): <NEW_LINE> <INDENT> bits = token.split_contents() <NEW_LINE> if len(bits) != 5: <NEW_LINE> <INDENT> message = '%s tag requires 5 arguments' % bits[0] <NEW_LINE> raise TemplateSyntaxError(_(message)) <NEW_LINE> <DEDENT> user = bits[1] <NEW_LINE> event = bit... | Example: {% is_registered_user user event as registered_user %} | 625941c20a50d4780f666e2a |
def get_path(self): <NEW_LINE> <INDENT> return super(DynamicStorageDownloadView, self).get_path().upper() | Return uppercase path. | 625941c2cc0a2c11143dce2a |
def create_feed_dict(self, image=None): <NEW_LINE> <INDENT> image = np.expand_dims(image, axis=0) <NEW_LINE> feed_dict = {self.tensor_name_input_image: image} <NEW_LINE> return feed_dict | Create and return a feed-dict with an image.
:param image:
The input image is a 3-dim array which is already decoded.
The pixels MUST be values between 0 and 255 (float or int).
:return:
Dict for feeding to the Inception graph in TensorFlow. | 625941c24e4d5625662d4374 |
def has_no_title(self, title, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.assert_no_title(title, **kwargs) <NEW_LINE> return True <NEW_LINE> <DEDENT> except ExpectationNotMet: <NEW_LINE> <INDENT> return False | Checks if the page doesn't have the given title.
Args:
title (str | RegexObject): The string that the title should include.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
bool: Whether it doesn't match. | 625941c2bde94217f3682d8c |
def from_str( self, text: str, *, interpolate: bool = True, overrides: Dict[str, Any] = {} ) -> "Config": <NEW_LINE> <INDENT> config = get_configparser(interpolate=interpolate) <NEW_LINE> if overrides: <NEW_LINE> <INDENT> config = get_configparser(interpolate=False) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> config.r... | Load the config from a string. | 625941c245492302aab5e25b |
def write_deps(self, filename, fileids=None): <NEW_LINE> <INDENT> f = open(filename, 'w') <NEW_LINE> for t in self.parsed_sents(fileids): <NEW_LINE> <INDENT> f.write(' '.join(str(d[1]) for d in t.depset.deps)+'\n') <NEW_LINE> <DEDENT> f.close() | Writes the dependencies to a text file, one sentence per line.
| 625941c2f548e778e58cd516 |
def walk(self,root=None): <NEW_LINE> <INDENT> if root: <NEW_LINE> <INDENT> yield root <NEW_LINE> for item in root.next: <NEW_LINE> <INDENT> self.walk(item) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for item in self.firsts: <NEW_LINE> <INDENT> self.walk(item) | if root is none, walks the whole tree,
otherwise starts at the given root,
recursive depth tree traverse | 625941c2adb09d7d5db6c72a |
def format_weekday(self, char='E', num=4): <NEW_LINE> <INDENT> if num < 3: <NEW_LINE> <INDENT> if char.islower(): <NEW_LINE> <INDENT> value = 7 - self.locale.first_week_day + self.value.weekday() <NEW_LINE> return self.format(value % 7 + 1, num) <NEW_LINE> <DEDENT> num = 3 <NEW_LINE> <DEDENT> weekday = self.value.weekd... | Return weekday from parsed datetime according to format pattern.
>>> format = DateTimeFormat(date(2016, 2, 28), Locale.parse('en_US'))
>>> format.format_weekday()
u'Sunday'
'E': Day of week - Use one through three letters for the abbreviated day name, four for the full (wide) name,
five for the narrow name, or s... | 625941c2a79ad161976cc0df |
def get_duplicated_rows(df): <NEW_LINE> <INDENT> grouped = df.groupby(['Date', 'Trap', 'Species']) <NEW_LINE> num=grouped.count().Latitude.to_dict() <NEW_LINE> df['N_Dupl']=-999 <NEW_LINE> for idx in df.index: <NEW_LINE> <INDENT> d = df.loc[idx, 'Date'] <NEW_LINE> t = df.loc[idx, 'Trap'] <NEW_LINE> s = df.loc[idx, 'Spe... | Calculates number of duplicated rows by Date, Trap, Species | 625941c2bde94217f3682d8d |
def test_add_staff_successfully(self): <NEW_LINE> <INDENT> self.dojo.create_room("office", ["Blue", "Green", "Pink"]) <NEW_LINE> self.dojo.create_room("living_space", ["A", "B", "C"]) <NEW_LINE> initial_staff_count = len(self.dojo.all_staff) <NEW_LINE> staff = self.dojo.add_staff("Donna") <NEW_LINE> self.assertTrue(sta... | Tests that a staff is created successfully | 625941c24f88993c3716c003 |
def extractConceptSet(rdfOntology): <NEW_LINE> <INDENT> concepts = set() <NEW_LINE> concepts = concepts.union( [ s for s, p, o in extractSPO(rdfOntology) ] ) <NEW_LINE> concepts = concepts.union( [ o for s, p, o in extractSPO(rdfOntology) ] ) <NEW_LINE> return concepts | extracts a set of all concepts present in the given ontology
@param[in] rdfOntology the rdflib.Graph object representing the ontology
@returns a set of all concepts present in the given ontology | 625941c2293b9510aa2c3232 |
def t_ID(self, token): <NEW_LINE> <INDENT> global reserved <NEW_LINE> token.type = reserved.get(token.value, 'IDENTIFIER') <NEW_LINE> return token | [a-zA-Z_][-a-zA-Z_0-9]* | 625941c292d797404e304123 |
def check_page_content(fullpage): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if len(parse_page(fullpage)) == 6: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return False | Takes a string with a full page. If it is valid, returns True | 625941c2e76e3b2f99f3a7a8 |
def find_node(self, **kwargs): <NEW_LINE> <INDENT> for child in kwargs['parent'].children(): <NEW_LINE> <INDENT> if child.type().name() == kwargs['node_type']: <NEW_LINE> <INDENT> if kwargs['node_type'] == 'geo': <NEW_LINE> <INDENT> shop_geometrypath_parm = child.evalParm('shop_geometrypath') <NEW_LINE> if shop_geometr... | Find a specific node in the node graph. | 625941c24f6381625f1149d6 |
def img_code_overdue_decode(token): <NEW_LINE> <INDENT> obj = decrypt(token) <NEW_LINE> if int(obj['_time']) + obj['ex'] <= time.time(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return obj | 解析图片验证码的对象 | 625941c263b5f9789fde707f |
def nodes(self): <NEW_LINE> <INDENT> nodes = [] <NEW_LINE> for vmware_vm in self._vmware_vms.values(): <NEW_LINE> <INDENT> nodes.append( {"class": VMwareVM.__name__, "name": vmware_vm["name"], "server": vmware_vm["server"], "symbol": vmware_vm["symbol"], "categories": [vmware_vm["category"]]} ) <NEW_LINE> <DEDENT> retu... | Returns all the node data necessary to represent a node
in the nodes view and create a node on the scene. | 625941c28a349b6b435e810d |
def Geman_McClure(x, a=1.0): <NEW_LINE> <INDENT> return (x**2) / (1 + (x**2 / a**2)) | a = outlier threshold | 625941c2baa26c4b54cb10bb |
def check_router_transport(transport): <NEW_LINE> <INDENT> if not isinstance(transport, dict): <NEW_LINE> <INDENT> raise InvalidConfigException("'transport' items must be dictionaries ({} encountered)\n\n{}".format(type(transport), pformat(transport))) <NEW_LINE> <DEDENT> if 'type' not in transport: <NEW_LINE> <INDENT>... | Check router transports.
https://github.com/crossbario/crossbardocs/blob/master/pages/docs/administration/router/Router-Transports.md
:param transport: Router transport item to check.
:type transport: dict | 625941c25f7d997b87174a30 |
def test_get_recognizer_multiplier(self): <NEW_LINE> <INDENT> url = self.get_server_url() + "/settings/recognizer_multiplier" <NEW_LINE> headers = {"Content-Type": "application/json"} <NEW_LINE> self.settings.options.recognizer_multiplier = 3000 <NEW_LINE> result = self.client.get(url, headers=headers) <NEW_LINE> expec... | Test for api get recognizer_multiplier. | 625941c276d4e153a657eaca |
def delete(self, obj_id): <NEW_LINE> <INDENT> return self._get_wrapper( obj_id ).deleteModel() | Remove a dataset series identified by the ``obj_id`` parameter.
:param obj_id: the EOID of the object to be deleted
:rtype: no output returned | 625941c267a9b606de4a7e55 |
def is_empty(self): <NEW_LINE> <INDENT> return self.num_items == 0 | returns True if the heap is empty, False otherwise | 625941c285dfad0860c3adf4 |
def increment_key(dictionary,key): <NEW_LINE> <INDENT> if dictionary.has_key(key): <NEW_LINE> <INDENT> dictionary[key] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dictionary[key] = 1 | If the dictionary has the key, increment the value,
otherwise initialize the key with value 1. | 625941c201c39578d7e74dd5 |
def create_app(config="src.config.DevConfig", test_config=None): <NEW_LINE> <INDENT> from src.general import general_bp <NEW_LINE> from src.cli import admin_bp <NEW_LINE> from src.auth.blueprint import auth_bp <NEW_LINE> from src.links.blueprint import link_bp <NEW_LINE> from src.importer.blueprint import importer_bp <... | The application factory for Espresso. Sets up configuration
parameters, sets up the database connection and hooks up the view
blueprints for all the API routes.
Arguments:
- config: The class object to configure Flask from
- test_config: Key-value mappings to override common configuration (i.e. for
running unit tests ... | 625941c291f36d47f21ac48a |
@implicit_stochastic <NEW_LINE> @scope.define <NEW_LINE> def GMM1(weights, mus, sigmas, low=None, high=None, q=None, rng=None, size=()): <NEW_LINE> <INDENT> weights, mus, sigmas = list(map(np.asarray, (weights, mus, sigmas))) <NEW_LINE> assert len(weights) == len(mus) == len(sigmas) <NEW_LINE> n_samples = np.prod(size)... | Sample from truncated 1-D Gaussian Mixture Model | 625941c296565a6dacc8f666 |
def select_menu() -> Menu: <NEW_LINE> <INDENT> s = [f'({m.value}){m.name}' for m in Menu] <NEW_LINE> while True: <NEW_LINE> <INDENT> print(*s, sep=' ', end='') <NEW_LINE> n = int(input(':')) <NEW_LINE> if 1 <= n <= len(Menu): <NEW_LINE> <INDENT> return Menu(n) | 메뉴 선택 | 625941c266673b3332b9202b |
def do_exploit(self): <NEW_LINE> <INDENT> if self.current_plugin: <NEW_LINE> <INDENT> rn = self.exec_plugin() <NEW_LINE> if (rn == 'Cookie is required!'): <NEW_LINE> <INDENT> return ["", 'Cookie is required!', ""] <NEW_LINE> <DEDENT> if not rn[0]: <NEW_LINE> <INDENT> logger.error(rn[1]) <NEW_LINE> <DEDENT> return rn <N... | 执行插件
:return: | 625941c2d99f1b3c44c6752e |
def test_edit_state_same(self): <NEW_LINE> <INDENT> self.assertEditValueNoop( "state", IncidentState.on_scene, IncidentState.on_scene ) | Edit incident state to same value is a no-op. | 625941c2287bf620b61d39ff |
def _satisfied_by(t, o): <NEW_LINE> <INDENT> return t.satisfied_by(o) | Pickleable type check function. | 625941c238b623060ff0ad88 |
def update(self): <NEW_LINE> <INDENT> self.y += (self.random_rain_drop_rate) <NEW_LINE> self.rect.y = self.y | Move the raindrops down the screen | 625941c24527f215b584c3f3 |
@cli.command() <NEW_LINE> @click.option("--force", "-f", is_flag=True, help="Drop existing database and user.") <NEW_LINE> def init_test_db(force=False): <NEW_LINE> <INDENT> db.init_db_connection(config.POSTGRES_ADMIN_URI) <NEW_LINE> if force: <NEW_LINE> <INDENT> res = db.run_sql_script_without_transaction(os.path.join... | Same as `init_db` command, but creates a database that will be used to
run tests and doesn't import data (no need to do that).
the `PG_CONNECT_TEST` variable must be defined in the config file. | 625941c2c432627299f04bdf |
def complist(self): <NEW_LINE> <INDENT> ans = [] <NEW_LINE> for comp in (self.component1, self.component2): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ans.extend(comp.complist()) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> ans.append(comp) <NEW_LINE> <DEDENT> <DEDENT> return ans | Return a list of all components and sub-components. | 625941c21f5feb6acb0c4aed |
def extract_hashtags(entities): <NEW_LINE> <INDENT> tags = [t['text'] for t in entities["hashtags"]] <NEW_LINE> tags = cat(tags) <NEW_LINE> return tags if is_ascii(tags) else "" | gets tags tweet by tweet returning their names seperated by spaces. | 625941c2956e5f7376d70e08 |
def process_file(f): <NEW_LINE> <INDENT> data = [] <NEW_LINE> info = {} <NEW_LINE> with open("{}/{}".format(datadir, f), "r") as html: <NEW_LINE> <INDENT> soup = BeautifulSoup(html, "lxml") <NEW_LINE> t = soup.find(id="DataGrid1").find_all("tr") <NEW_LINE> for i in range(1, len(t)): <NEW_LINE> <INDENT> info["courier"],... | This function extracts data from the file given as the function argument in
a list of dictionaries. This is example of the data structure you should
return:
data = [{"courier": "FL",
"airport": "ATL",
"year": 2012,
"month": 12,
"flights": {"domestic": 100,
"inte... | 625941c2442bda511e8be3b5 |
def quit(self): <NEW_LINE> <INDENT> self.running = False | Exits the ui and the run wrapper | 625941c2d6c5a10208143fe3 |
def __update_service_query(self): <NEW_LINE> <INDENT> if self.service_query['status'] == u'OK': <NEW_LINE> <INDENT> self.__status_update(u"Updating") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> status_no = self.status_dict[self.service_query['status']] <NEW_LINE> if not status_no == 15: <NEW_LINE> <INDENT> update_quer... | Update Service Query | 625941c23539df3088e2e2e5 |
def run_algorithm(self, generations): <NEW_LINE> <INDENT> for _ in range(generations): <NEW_LINE> <INDENT> self.selection() <NEW_LINE> self.crossover() <NEW_LINE> self.mutate() <NEW_LINE> self.compare_best_gene() <NEW_LINE> <DEDENT> print("Final best value: {}".format(self.best_dist)) | Runs genetic algorithm for # generations | 625941c29b70327d1c4e0d6e |
def merge(self, other_range): <NEW_LINE> <INDENT> logging.info("Merging time ranges:\n\t%s\n\t%s" % (self, other_range)) <NEW_LINE> self.length = self.length + other_range.length <NEW_LINE> other_range.length = 0 <NEW_LINE> logging.info("Resulting time range: %s" % (self,)) | Merge the two ranges together, resulting in that the other range will have a
length of zero once this method returns | 625941c2be383301e01b5424 |
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(DetectObjectRequest, self).__init__(*args, **kwds) | Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
:param args: complete set of fie... | 625941c2187af65679ca50b8 |
def rewrite_url(self, matches): <NEW_LINE> <INDENT> text_before = matches.groups()[0] <NEW_LINE> url = matches.groups()[1] <NEW_LINE> text_after = matches.groups()[2] <NEW_LINE> quotes_used = '' <NEW_LINE> if url[:1] in '"\'': <NEW_LINE> <INDENT> quotes_used = url[:1] <NEW_LINE> url = url[1:] <NEW_LINE> <DEDENT> if url... | Rewrite found URL pattern. | 625941c273bcbd0ca4b2c011 |
def __plot_corrected_maps__(self): <NEW_LINE> <INDENT> if self.verbose == True: print('... plotting corrected maps') <NEW_LINE> for dsName in self.dsNames: <NEW_LINE> <INDENT> fig, axes = plt.subplots(figsize=(12,7), ncols=3) <NEW_LINE> plot_raster(self.velMaps[dsName], extent=self.extent, mask=self.masks[dsName], cmap... | Plot corrected maps. | 625941c23539df3088e2e2e6 |
def start(self, source): <NEW_LINE> <INDENT> vote = self.VOTE <NEW_LINE> minLineLength = self.MIN_LINE_LENGTH <NEW_LINE> maxLineGap = self.MAX_LINE_GAP <NEW_LINE> lines = cv2.HoughLinesP(source, 1, np.pi / 180., vote, minLineLength, maxLineGap) <NEW_LINE> return lines | @return: lines | 625941c23317a56b86939bf7 |
def to_pixel(self, wcs): <NEW_LINE> <INDENT> return PixelPolygonRegion.from_sky(self, wcs) | Thisn function ...
:param wcs:
:return: | 625941c21b99ca400220aa4b |
def realms(self, region=None): <NEW_LINE> <INDENT> url = f'{self.base}/realms/{region}.json' <NEW_LINE> r = requests.get(url) <NEW_LINE> return r | Get realm data.
Newest version endpoints for different static data.
Parameters
----------
region : str
na, euw, jp, kr...
Returns
-------
Response | 625941c2bd1bec0571d905c9 |
def write_control_point(self, C, filename): <NEW_LINE> <INDENT> with open(filename, 'wb') as f: <NEW_LINE> <INDENT> pickle.dump(C, f) | Output control point
Parameters
----------
C : dict
control point
filename : str(file path and name)
write data file name
Returns
----------
None | 625941c2a8370b771705283b |
def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'soc_parent_type': 'str', 'parent_controller': 'str', 'parent_esm': 'str', 'parent_drawer': 'str' } <NEW_LINE> self.attribute_map = { 'soc_parent_type': 'socParentType', 'parent_controller': 'parentController', 'parent_esm': 'parentEsm', 'parent_drawer': 'p... | SocParent - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition. | 625941c2a934411ee375162e |
def update_log(username, op): <NEW_LINE> <INDENT> log_file = os.path.join(server.app.root_path, 'uploads', '.admin.log') <NEW_LINE> with open(log_file, 'a') as log: <NEW_LINE> <INDENT> log.write('%s\t%s\t%s\n' % (username, ' ', op)) | Updates the admin log | 625941c2091ae35668666efc |
def phinorm2v(self, phinorm, t, **kwargs): <NEW_LINE> <INDENT> return self._phinorm2Quan(self._getVSpline, phinorm, t, **kwargs) | Calculates the flux surface volume corresponding to the passed phinorm (normalized toroidal flux) values.
By default, EFIT only computes this inside the LCFS.
Args:
phinorm (Array-like or scalar float): Values of the normalized
toroidal flux to map to v.
t (Array-like or scalar float): Times to perfor... | 625941c2d8ef3951e32434d8 |
def test_title_oneline(): <NEW_LINE> <INDENT> t = h.Title("PythonClass - Session 6 example blah blah I'm so long blaaaaaaah") <NEW_LINE> f = cStringIO.StringIO() <NEW_LINE> t.render(f) <NEW_LINE> f.reset() <NEW_LINE> assert f.read() == "<title>PythonClass - Session 6 example blah blah I'm so long blaaaaaaah</title>\n" | Test that the title tag displays on one line (implicitly tests inline performance) | 625941c2d18da76e2353246e |
def check(self): <NEW_LINE> <INDENT> with self.mutex: <NEW_LINE> <INDENT> enabled = self.safetyEnabled <NEW_LINE> stopTime = self.safetyStopTime <NEW_LINE> <DEDENT> if not enabled or RobotState.isDisabled() or RobotState.isTest(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if stopTime < Timer.getFPGATimestamp(): <N... | Check if this motor has exceeded its timeout.
This method is called periodically to determine if this motor has
exceeded its timeout value. If it has, the stop method is called,
and the motor is shut down until its value is updated again. | 625941c2379a373c97cfaadf |
def isSwear(self, swearlist): <NEW_LINE> <INDENT> for word in self.contents.split(): <NEW_LINE> <INDENT> if word.lower() in swearlist: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | checks if the message contains a swear | 625941c26e29344779a625ae |
def tearDown(self): <NEW_LINE> <INDENT> db.session.remove() <NEW_LINE> db.drop_all() | Remove all test suite utilities. | 625941c2187af65679ca50b9 |
def test_empty_repo(): <NEW_LINE> <INDENT> pass | Empty repos have no branch pristine-tar branch
Methods tested:
- L{gbp.deb.git.DebianGitRepository.has_pristine_tar_branch}
- L{gbp.deb.pristinetar.DebianPristineTar.has_commit}
>>> import gbp.deb.git
>>> repo = gbp.deb.git.DebianGitRepository(repo_dir)
>>> repo.has_pristine_tar_branch()
False
>>> repo.pris... | 625941c22ae34c7f2600d0cc |
def __download_single(self, item_id, request): <NEW_LINE> <INDENT> query = '/'.join([request, str(item_id)]) <NEW_LINE> res = requests.get(query) <NEW_LINE> res = res.json() <NEW_LINE> attr_json[res.get('id')] = res | Downloads 1 item's worth of detail and load into dict | 625941c2aad79263cf3909d9 |
@get.command(name='members') <NEW_LINE> def get_members(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> results = api.get_members() <NEW_LINE> <DEDENT> except DkronException as ex: <NEW_LINE> <INDENT> print('Error while fetching: %s' % str(ex)) <NEW_LINE> exit(1) <NEW_LINE> <DEDENT> print(json.dumps(results)) | Get system members | 625941c255399d3f0558864e |
def grant_request(self): <NEW_LINE> <INDENT> path = "/oauth/v2/auth" <NEW_LINE> params = { "response_type": "code", "client_id": self.client_id, "scope": self.scope, "redirect_uri": self.redirect, } <NEW_LINE> query = urllib.parse.urlencode(params, True) <NEW_LINE> grant_access_url = urllib.parse.urlunsplit( (self.SCHE... | Opens a Web Browser to log in and grant access. This first step
creates a grant token to use in requesting the access token. | 625941c25e10d32532c5eec2 |
def invert(self): <NEW_LINE> <INDENT> return _({self[k]: k for k in self._}) | invert dict's key and value
@param : none
@return : _(dict)
e.g.
_({"k1": "v1", "k2": "v2"}).invert()._
{"v1": "k1", "v2": "k2"} | 625941c263d6d428bbe4448a |
def ui_acct_list(browser_session, ui_loginpage, ui_user): <NEW_LINE> <INDENT> selenium = browser_session <NEW_LINE> if 'Welcome to Cloud Meter' in selenium.page_source: <NEW_LINE> <INDENT> browser = Browser(selenium) <NEW_LINE> return browser, LoginView(browser) <NEW_LINE> <DEDENT> elif 'Login to Your Account' in selen... | Tool to navigate to the account list by logging in. | 625941c25510c4643540f384 |
def merge(a, b): <NEW_LINE> <INDENT> from copy import deepcopy <NEW_LINE> if not isinstance(b, dict): <NEW_LINE> <INDENT> return b <NEW_LINE> <DEDENT> result = deepcopy(a) <NEW_LINE> for k, v in b.iteritems(): <NEW_LINE> <INDENT> if k in result and isinstance(result[k], dict): <NEW_LINE> <INDENT> result[k] = merge(resu... | recursively merges dict's. not just simple a['key'] = b['key'], if
both a and bhave a key who's value is a dict then dict_merge is called
on both values and the result stored in the returned dictionary. | 625941c2f8510a7c17cf9696 |
def parse_datetime(s): <NEW_LINE> <INDENT> dt, tm = _split_datetime(s) <NEW_LINE> return parse_date(dt) + parse_time(tm) | Parses ISO-8601 compliant timestamp and returns a tuple (year, month,
day, hour, minute, second).
Formats accepted are those listed in the descriptions of parse_date() and
parse_time() with ' ' or 'T' used to separate date and time parts. | 625941c2097d151d1a222df6 |
def _json_routing_tables(self): <NEW_LINE> <INDENT> with FecTimer(MAPPING, "Json routing tables") as timer: <NEW_LINE> <INDENT> if timer.skip_if_cfg_false( "Reports", "write_json_routing_tables"): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> write_json_routing_tables(self._router_tables, self._json_folder) | Write, time and log the routing tables as json if requested | 625941c2046cf37aa974cce4 |
def suffix_replace(original, old, new): <NEW_LINE> <INDENT> return original[:-len(old)] + new | Replaces the old suffix of the original string by a new suffix | 625941c2dc8b845886cb54cf |
def request_all_artist_toptags(self): <NEW_LINE> <INDENT> for track in self.tracks: <NEW_LINE> <INDENT> artist = track.metadata["artist"] <NEW_LINE> if settings.ENABLE_IGNORE_FEAT_ARTISTS: <NEW_LINE> <INDENT> artist = strip_feat_artist(artist) <NEW_LINE> <DEDENT> params = dict( method="artist.gettoptags", artist=artist... | request toptags of all artists in the album (via artist) | 625941c232920d7e50b28169 |
def __eq__(self, conversion_electrode): <NEW_LINE> <INDENT> if len(self) != len(conversion_electrode): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for pair1 in conversion_electrode: <NEW_LINE> <INDENT> found = False <NEW_LINE> rxn1 = pair1.rxn <NEW_LINE> all_formulas1 = set([rxn1.all_comp[i].reduced_formula fo... | Check if two electrodes are exactly the same: | 625941c215fb5d323cde0aa8 |
def create_report_header(self): <NEW_LINE> <INDENT> header = '{:20}|{:^15}|{:^15}|{:>15}'.format("Donor Name", "Total Given", "Num Gifts", "Average Gift") + '\n' <NEW_LINE> header += ("-" * len(header)) <NEW_LINE> return header | Generate formatted header for report | 625941c22ae34c7f2600d0cd |
def _load_predaily(daily_path: str, abs_path: str, ps_cache_path: str, identifier: Identifier, current: MutableMapping[Identifier, int], first: MutableMapping[Identifier, date], cache_path: Optional[str] = None, cf_cache: Optional[_CF_PersistentIndex] = None) -> List[Event]: <NEW_LINE> <INDENT> events: List[Even... | Generate inferred events prior to daily.log based on abs files.
Approach:
- v1 announced date is the v1 submission date
- if there are multiple versions:
- scan the daily.log for all replacements of that e-print
- align from the most recent version, backward
- if there are any remaining versions between v1 and ... | 625941c245492302aab5e25c |
def log_process_ngr_line(self, log): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> if log != '': <NEW_LINE> <INDENT> if log[0] == '[': <NEW_LINE> <INDENT> if log[0:12] == '[DoS attack:': <NEW_LINE> <INDENT> network_log = self.log_process_parse_ngr_log(self.dos_inc_type, log) <NEW_LINE> count = self.sql_server.sql_execute(ne... | process a single log record. | 625941c2e5267d203edcdc3a |
def test_cim_element_contract(test_case): <NEW_LINE> <INDENT> for required in test_case.valid_metadata: <NEW_LINE> <INDENT> invalid = dict(test_case.valid_metadata) <NEW_LINE> del invalid[required] <NEW_LINE> test_case.assertRaises( DaoContractException, test_case.element.cim_element, invalid, []) | Standard method to test contract enforced. | 625941c2046cf37aa974cce5 |
def read(handle): <NEW_LINE> <INDENT> record = Record(handle) <NEW_LINE> record.comment_line = str(handle.readline()).rstrip() <NEW_LINE> sample_loci_line = str(handle.readline()).rstrip().replace(',', '') <NEW_LINE> all_loci = sample_loci_line.split(' ') <NEW_LINE> record.loci_list.extend(all_loci) <NEW_LINE> line = h... | Parses a handle containing a GenePop file.
handle is a file-like object that contains a GenePop record. | 625941c28c3a873295158353 |
def predict(self, testFeatures): <NEW_LINE> <INDENT> if(not self._fitCalled): <NEW_LINE> <INDENT> print('The fit method has not been called yet') <NEW_LINE> return None <NEW_LINE> <DEDENT> preProcTestFeatures = self.pp.preProc(testFeatures) <NEW_LINE> w = self.w <NEW_LINE> X= add_ones(preProcTestFeatures) <NEW_LINE> b ... | Method that calculates the predicted outputs given the input features.
testFeatures: l x d 2D numpy array
where d is the data dimension and l is the number of points to make predictions about
returns an l dimensional 1D numpy array composed of the predictions | 625941c267a9b606de4a7e56 |
def valid_configfile(s): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(s, 'r') as f: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise argparse.ArgumentTypeError('{} ({})'.format(e.strerror, s)) <NEW_LINE> <DEDENT> return s | Validate that specified argument is a file path that can be opened | 625941c25166f23b2e1a50f4 |
def __init__(self, action_id, next_state_symbol): <NEW_LINE> <INDENT> super(ATPAction, self).__init__(action_id) <NEW_LINE> self._next_state_symbol = next_state_symbol | Deterministic actions for activity-travel MDP.
Args:
action_id ():
next_state_symbol (): | 625941c2eab8aa0e5d26daf3 |
def test_connection(self): <NEW_LINE> <INDENT> return [x for x in self.current_session.query(Site)] | Returns all site. | 625941c2bd1bec0571d905ca |
def Z_Tensor_1D(resistivities, thicknesses, frequencies): <NEW_LINE> <INDENT> if len(resistivities) != len(thicknesses) + 1: <NEW_LINE> <INDENT> print("Length of inputs incorrect!") <NEW_LINE> return <NEW_LINE> <DEDENT> mu = 4*np.pi*1E-7; <NEW_LINE> n = len(resistivities); <NEW_LINE> master_Z, master_absZ, master_phase... | Calculate 1D Z-Tensor for given ground resistivity profile.
Parameters
-----------
resistivities = array or list of resistivity values in Ohm.m
thicknesses = array or list of thicknesses in m.
**len(resistivities) must be len(thicknesses) + 1**
frequencies = array or list of frequencies to get response of
Retur... | 625941c263b5f9789fde7080 |
def testEventMissingEventWithSnmpTrapVersionV1(self): <NEW_LINE> <INDENT> self.log.info('\n\n\n ***** Test case : testEventMissingEventWithSnmpTrapVersionV1 *****') <NEW_LINE> self.log.info('Set the EventType value as snmp-trap using snmpset for EventMissingEvent') <NEW_LINE> self.event_table.set_event('polatisEventT... | Test case that verifies, logs are not returned in the polatisLogTable and
V1 trap is received in the configured trap receiver against the event -
'EventMissing' | 625941c2be7bc26dc91cd59f |
def _toggle_help(history): <NEW_LINE> <INDENT> help_buffer_control = history.history_layout.help_buffer_control <NEW_LINE> if history.app.layout.current_control == help_buffer_control: <NEW_LINE> <INDENT> history.app.layout.focus_previous() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> history.app.layout.current_contro... | Display/hide help. | 625941c210dbd63aa1bd2b3f |
def playerStandings(): <NEW_LINE> <INDENT> DB = connect() <NEW_LINE> c = DB.cursor() <NEW_LINE> c.execute("SELECT * FROM win") <NEW_LINE> c.execute("SELECT * FROM loss") <NEW_LINE> c.execute("SELECT * FROM matchesplayed") <NEW_LINE> c.execute("SELECT * FROM standings") <NEW_LINE> players_standings = c.fetchall() <NEW_L... | Returns a list of the players and their win records, sorted by wins.
The first entry in the list should be the player in first place, or a player
tied for first place if there is currently a tie.
Returns:
A list of tuples, each of which contains (id, name, wins, matches):
id: the player's unique id (assigned by... | 625941c2435de62698dfdbe7 |
def test_required_agreement_submit(self): <NEW_LINE> <INDENT> kwargs = { "initial": {"person": self.neville}, "widgets": {"person": HiddenInput()}, } <NEW_LINE> terms = RequiredConsentsForm(**kwargs).get_terms() <NEW_LINE> data = { term.slug: term.options[0].pk for term in terms.exclude(required_type=Term.PROFILE_REQUI... | Make sure the form passes only when required terms are set. | 625941c256ac1b37e626416e |
def show_rankings(y_true, y_score=None): <NEW_LINE> <INDENT> if y_score is not None: <NEW_LINE> <INDENT> y_true = y_true[np.argsort(y_score)[::-1]] <NEW_LINE> <DEDENT> BLOCK_W, BLOCK_H = (10, 10) <NEW_LINE> NEG_BLOCK = np.zeros((BLOCK_W, BLOCK_H, 3), 'uint8') <NEW_LINE> NEG_BLOCK[2:-2, 2:-2, :] = 100 <NEW_LINE> POS_BLO... | Input:
`y_true` - binary labels
`y_score` - the scores used to rank the samples of X, optional
if not given, will assume that y_true is already sorted in order from highest ranked to lowest | 625941c263f4b57ef00010b9 |
def __str__(self): <NEW_LINE> <INDENT> return repr(self.colname) | String representation. | 625941c2d99f1b3c44c6752f |
def _get_button_boundaries(button_list): <NEW_LINE> <INDENT> button_boundaries = [] <NEW_LINE> for button in button_list: <NEW_LINE> <INDENT> if button.active or button.number > 199: <NEW_LINE> <INDENT> button_coords = button.field_coords <NEW_LINE> boundary_x_small, boundary_y_small = button_coords[0] <NEW_LINE> bound... | returns the button boundaries of the one button list's buttons
:param button_list: list[Button, ...]; list that holds buttons
:return: lsit[list[list[int, int], list[int, int]], list, ...]; list that holds the button boundaries | 625941c2b545ff76a8913db2 |
def update_vehicle_profile(spawn_profile, new_vehicle): <NEW_LINE> <INDENT> return spawn_profile.update_vehicle_profile(new_vehicle) | Updates the vehicle profile of the spawning profile
:param new_vehicle: new vehicle profile
:param spawn_profile: spawning profile
:type spawn_profile: SpawningProfile
:type new_vehicle: VehicleProfile
:return: updated spawning profile | 625941c2b57a9660fec3381d |
def get_city(): <NEW_LINE> <INDENT> url = 'http://map.amap.com/subway/index.html?&1100' <NEW_LINE> response = requests.get(url=url, headers=headers) <NEW_LINE> html = response.text <NEW_LINE> html = html.encode('ISO-8859-1') <NEW_LINE> html = html.decode('utf-8') <NEW_LINE> soup = BeautifulSoup(html, 'lxml') <NEW_LINE>... | 城市信息获取 | 625941c28e71fb1e9831d745 |
def ride_details(self, ride_id): <NEW_LINE> <INDENT> sql = "SELECT origin, meet_point, contribution, free_spots, start_date, " "finish_date, driver_id, destination, terms FROM carpool_rides WHERE id=%s" % ride_id <NEW_LINE> self.cursor.execute(sql) <NEW_LINE> result = self.cursor.fetchall() <NEW_LINE> if n... | Returns the details of a ride offer with the ride_id provided
Also contains the driver information | 625941c2004d5f362079a2d0 |
def servicios_cliente_get_data(request): <NEW_LINE> <INDENT> datos = {'data':[]} <NEW_LINE> servid = request.GET.get('servicio_id', None) <NEW_LINE> if(servid): <NEW_LINE> <INDENT> for serv in ServicioCliente.objects.filter(servicio_id=servid).all(): <NEW_LINE> <INDENT> lista = [] <NEW_LINE> lista.append(serv.servicio.... | !
Metodo que extrae los datos de los clientes relacionados con el servicio y la muestra en una url ajax como json
@author Rodrigo Boet (rboet at cenditel.gob.ve)
@copyright GNU/GPLv2
@date 25-10-2016
@param request <b>{object}</b> Recibe la peticion
@return Retorna el json con las subunidades que consiguió | 625941c294891a1f4081ba44 |
def test_entropy_is_zero_for_unimodal_function(): <NEW_LINE> <INDENT> def func_one_min(x): <NEW_LINE> <INDENT> return x**2 <NEW_LINE> <DEDENT> initial_models = 2*random_sample(100) - 1 <NEW_LINE> entropy = estimate_entropy(func_one_min, initial_models, 1e-8, 1e5) <NEW_LINE> assert entropy == 0 | Test that the entropy of a function with one extremum is zero. | 625941c263f4b57ef00010ba |
@bp.route('/<int:competition_id>/next-stage-teams', methods=['GET']) <NEW_LINE> def next_stage_teams(competition_id): <NEW_LINE> <INDENT> teams_per_group = int(request.args.get('teams_per_group', '2')) <NEW_LINE> stage = int(request.args.get('stage')) <NEW_LINE> competition = models.Competition.from_cache_by_id(competi... | 获取该赛事下的晋级下一阶段的参赛队伍 | 625941c2a8ecb033257d3069 |
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(Object, self).__init__(*args, **kwds) <NEW_LINE> if self.n is None: <NEW_LINE> <INDENT> self.n = 0 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.n = 0 | Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
n
:param args: complete set of fi... | 625941c26aa9bd52df036d3e |
def items(self): <NEW_LINE> <INDENT> return Organisation.objects.all() | Return published entries. | 625941c2627d3e7fe0d68dea |
def urlize(text, trim_url_limit=None, nofollow=False, target=None): <NEW_LINE> <INDENT> trim_url = lambda x, limit=trim_url_limit: limit is not None and (x[:limit] + (len(x) >=limit and '...' or '')) or x <NEW_LINE> words = _word_split_re.split(text_type(escape(text))) <NEW_LINE> nofollow_attr =... | Converts any URLs in text into clickable links. Works on http://,
https:// and www. links. Links can have trailing punctuation (periods,
commas, close-parens) and leading punctuation (opening parens) and
it'll still do the right thing.
If trim_url_limit is not None, the URLs in link text will be limited
to trim_url_li... | 625941c2ff9c53063f47c190 |
def requires_auth(endpoint_class): <NEW_LINE> <INDENT> def fdec(f): <NEW_LINE> <INDENT> @wraps(f) <NEW_LINE> def decorated(*args, **kwargs): <NEW_LINE> <INDENT> if args: <NEW_LINE> <INDENT> resource_name = args[0] <NEW_LINE> resource = app.config['DOMAIN'][args[0]] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> resource... | Enables Authorization logic for decorated functions.
:param endpoint_class: the 'class' to which the decorated endpoint belongs
to. Can be 'resource' (resource endpoint), 'item'
(item endpoint) and 'home' for the API entry point.
.. versionchanged:: 0.0.7
Passing the ... | 625941c2cc40096d615958ed |
def snapshot_get(repository, snapshot, ignore_unavailable=False, hosts=None, profile=None): <NEW_LINE> <INDENT> es = _get_instance(hosts, profile) <NEW_LINE> try: <NEW_LINE> <INDENT> return es.snapshot.get(repository=repository, snapshot=snapshot, ignore_unavailable=ignore_unavailable) <NEW_LINE> <DEDENT> except elasti... | .. versionadded:: 2017.7.0
Obtain snapshot residing in specified repository.
repository
Repository name
snapshot
Snapshot name, use _all to obtain all snapshots in specified repository
ignore_unavailable
Ignore unavailable snapshots
CLI example::
salt myminion elasticsearch.snapshot_get testrepo tes... | 625941c20a50d4780f666e2c |
def lstm_step_backward(dnext_h, dnext_c, cache): <NEW_LINE> <INDENT> f, g, i, o, prev_h, prev_c, next_c, x, Wh, Wx = cache <NEW_LINE> N, H = dnext_h.shape <NEW_LINE> do = dnext_h * np.tanh(next_c) <NEW_LINE> dnext_c += dnext_h * o * (1 - np.tanh(next_c)**2) <NEW_LINE> dprev_c = dnext_c * f <NEW_LINE> di = dnext_c * g <... | Backward pass for a single timestep of an LSTM.
Inputs:
- dnext_h: Gradients of next hidden state, of shape (N, H)
- dnext_c: Gradients of next cell state, of shape (N, H)
- cache: Values from the forward pass
Returns a tuple of:
- dx: Gradient of input data, of shape (N, D)
- dprev_h: Gradient of previous hidden sta... | 625941c23c8af77a43ae373a |
def get_best_model(dataset): <NEW_LINE> <INDENT> best_model = 0 <NEW_LINE> rd.shuffle(dataset) <NEW_LINE> features = [] <NEW_LINE> for i in dataset: <NEW_LINE> <INDENT> i = i[:-1] <NEW_LINE> features.append(i) <NEW_LINE> <DEDENT> labels = [] <NEW_LINE> for i in dataset: <NEW_LINE> <INDENT> labels.append(i[-1]) <NEW_LIN... | Creates the dataset and trains the model,
optimises it with the genetic algorithm
and returns the model and its accuracy | 625941c26fece00bbac2d6d9 |
def spotify_scope(scope_name: str) -> Spotify: <NEW_LINE> <INDENT> scope = Spotify(auth_manager=SpotifyOAuth(scope=scope_name)) <NEW_LINE> scope.trace = False <NEW_LINE> return scope | Create a Spotify object with a particular scope.
:param scope_name: name of the scope
:return: Spotify object at a specific scope | 625941c2656771135c3eb808 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.