code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def scaledb(c_1,c_2): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> d = c_1.data.max()-c_2.data.max() <NEW_LINE> a = Series(data=c_2.data.values+d,index=c_2.data.index) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> d = c_1.max()-c_2.max() <NEW_LINE> a = Series(data=c_2.values+d,index=c_2.index) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> return a
scale c_2 on c_1, max are then the same
625941c20c0af96317bb8184
def mask(array, mask): <NEW_LINE> <INDENT> masked = np.copy(array) <NEW_LINE> masked[mask == 0] = np.nan <NEW_LINE> return masked
utility function for masking an array :param array: 2d numpy array :param mask: 2d numpy pseudo-boolean array (1 and 0) :return: masked 2d numpy array (nan assigned to 0 values on mask)
625941c2cc0a2c11143dce2c
def __init__(self, k): <NEW_LINE> <INDENT> self.k = k
Initializes the KNN classifier with the k.
625941c2d164cc6175782ce9
def __init__(self, padding_x=0, padding_y=0, mask_bound_height=24, ): <NEW_LINE> <INDENT> gtk.DrawingArea.__init__(self) <NEW_LINE> self.padding_x = padding_x <NEW_LINE> self.padding_y = padding_y <NEW_LINE> self.mask_bound_height = mask_bound_height <NEW_LINE> self.add_events(gtk.gdk.ALL_EVENTS_MASK) <NEW_LINE> self.set_can_focus(True) <NEW_LINE> self.items = [] <NEW_LINE> self.focus_index = None <NEW_LINE> self.highlight_item = None <NEW_LINE> self.double_click_item = None <NEW_LINE> self.single_click_item = None <NEW_LINE> self.connect("realize", self.realize_icon_view) <NEW_LINE> self.connect("realize", lambda w: self.grab_focus()) <NEW_LINE> self.connect("expose-event", self.expose_icon_view) <NEW_LINE> self.connect("motion-notify-event", self.motion_icon_view) <NEW_LINE> self.connect("button-press-event", self.button_press_icon_view) <NEW_LINE> self.connect("button-release-event", self.button_release_icon_view) <NEW_LINE> self.connect("leave-notify-event", self.leave_icon_view) <NEW_LINE> self.connect("key-press-event", self.key_press_icon_view) <NEW_LINE> self.connect("lost-focus-item", lambda view, item: item.icon_item_lost_focus()) <NEW_LINE> self.connect("motion-notify-item", lambda view, item, x, y: item.icon_item_motion_notify(x, y)) <NEW_LINE> self.connect("highlight-item", lambda view, item: item.icon_item_highlight()) <NEW_LINE> self.connect("normal-item", lambda view, item: item.icon_item_normal()) <NEW_LINE> self.connect("button-press-item", lambda view, item, x, y: item.icon_item_button_press(x, y)) <NEW_LINE> self.connect("button-release-item", lambda view, item, x, y: item.icon_item_button_release(x, y)) <NEW_LINE> self.connect("single-click-item", lambda view, item, x, y: item.icon_item_single_click(x, y)) <NEW_LINE> self.connect("double-click-item", lambda view, item, x, y: item.icon_item_double_click(x, y)) <NEW_LINE> self.redraw_request_list = [] <NEW_LINE> self.redraw_delay = 100 <NEW_LINE> gtk.timeout_add(self.redraw_delay, self.update_redraw_request_list) <NEW_LINE> self.keymap = { "Home" : self.select_first_item, "End" : self.select_last_item, "Return" : self.return_item, "Up" : self.select_up_item, "Down" : self.select_down_item, "Left" : self.select_left_item, "Right" : self.select_right_item, "Page_Up" : self.scroll_page_up, "Page_Down" : self.scroll_page_down, }
Initialize IconView class. @param padding_x: Horizontal padding value. @param padding_y: Vertical padding value.
625941c24d74a7450ccd415f
def _post(self, endpoint, params, custompostfix=False, dwollaparse='dwolla'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> resp = requests.post((c.sandbox_host if c.sandbox else c.production_host) + (custompostfix if custompostfix else c.default_postfix) + endpoint, json.dumps(params, default=self._decimal_default), proxies=c.proxy, timeout=c.rest_timeout, headers={'User-Agent': 'dwolla-python/2.x', 'Content-Type': 'application/json'}) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> if c.debug: <NEW_LINE> <INDENT> print("dwolla-python: An error has occurred while making a POST request:\n" + '\n'.join(e.args)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return self._parse(resp.text, dwollaparse)
Wrapper for requests' POST functionality. :param endpoint: String containing endpoint desire :param params: Dictionary containing parameters for request. :param custompostfix: String containing custom OAuth postfix (for special endpoints). :param dwollaparse: Boolean deciding whether or not to call self._parse(). :return: Dictionary String containing endpoint desire containing API response.
625941c2167d2b6e31218b32
def to_url(self, value): <NEW_LINE> <INDENT> print("to_url方法被调用") <NEW_LINE> return value
使用url_for的方法的时候被调用
625941c25fc7496912cc391a
@bootstrap_setup('macbook') <NEW_LINE> def bootstrap_macbook(): <NEW_LINE> <INDENT> bin_path = (pathlib.Path.home() / 'bin') <NEW_LINE> if not bin_path.exists(): <NEW_LINE> <INDENT> bin_path.mkdir() <NEW_LINE> <DEDENT> batcharge = bin_path / 'batcharge' <NEW_LINE> batcharge.symlink_to(git_dir() / 'fenhl.net' / 'syncbin-private' / 'master' / 'bin' / 'batcharge-macbook')
Installs `batcharge` for MacBooks.
625941c2b7558d58953c4eb4
def create(self): <NEW_LINE> <INDENT> self.sysadmin = factories.Sysadmin() <NEW_LINE> self.org = factories.Organization() <NEW_LINE> self.public_records = factories.Dataset(**self._package_data()) <NEW_LINE> self._make_resource(self.public_records['id'], self._records) <NEW_LINE> self.public_no_records = factories.Dataset(**self._package_data()) <NEW_LINE> self._make_resource(self.public_no_records['id']) <NEW_LINE> self.private_records = factories.Dataset(**self._package_data(True)) <NEW_LINE> self._make_resource(self.private_records['id'], self._records) <NEW_LINE> self.reload_pkg_dicts()
Runs all the creation functions in the class, e.g. creating a test org and test datasets.
625941c2adb09d7d5db6c72c
def package_name_not_changed(key, data, errors, context): <NEW_LINE> <INDENT> package = context.get('package') <NEW_LINE> if data[key] == u'': <NEW_LINE> <INDENT> data[key] = package.name <NEW_LINE> <DEDENT> value = data[key] <NEW_LINE> if package and value != package.name: <NEW_LINE> <INDENT> raise Invalid('Cannot change value of key from %s to %s. ' 'This key is read-only' % (package.name, value))
Checks that package name doesn't change
625941c292d797404e304125
@marc21_holdings.over('date_and_time_of_latest_transaction', '^005') <NEW_LINE> def date_and_time_of_latest_transaction(self, key, value): <NEW_LINE> <INDENT> return value
Date and Time of Latest Transaction.
625941c24f6381625f1149d8
def id_or_maxval(self): <NEW_LINE> <INDENT> if self.id: <NEW_LINE> <INDENT> return int(self.id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return maxsize
Method used to compare 2 instances by 'id'-parameter. In case when some instance have empty 'id', method returns 'maxsize' const.
625941c22c8b7c6e89b3575e
def save_img(figure, country): <NEW_LINE> <INDENT> figure.savefig("Trend in number of confirmed cases for {}.png".format(country)) <NEW_LINE> tk.messagebox.showinfo(title="Alert", message='Saved as: "Trend in number of confirmed cases for {}.png"'.format(country))
Saves graph as image
625941c230c21e258bdfa438
def getsize(self,kk): <NEW_LINE> <INDENT> return str(self._ifgs[kk].width), str(self._ifgs[kk].length)
Return width and length IFG
625941c2460517430c394126
def begin_environment(χ=1): <NEW_LINE> <INDENT> return np.eye(χ, dtype=np.float64)
Initiate the computation of a left environment from two MPS. The bond dimension χ defaults to 1. Other values are used for states in canonical form that we know how to open and close.
625941c2e76e3b2f99f3a7ab
def sanitize_generated_module(generated_module_filepath: str): <NEW_LINE> <INDENT> with open(generated_module_filepath, 'r') as sip_module_orig: <NEW_LINE> <INDENT> module_code_orig = sip_module_orig.readlines() <NEW_LINE> <DEDENT> sanitized_code = [] <NEW_LINE> for line_orig in module_code_orig: <NEW_LINE> <INDENT> sanitized_code.append(THROW_SPEC_RE.sub('noexcept(false)', line_orig)) <NEW_LINE> <DEDENT> with open(generated_module_filepath, 'w') as sanitized_module: <NEW_LINE> <INDENT> sanitized_module.write(''.join(sanitized_code))
Takes the module code as generated by sip and sanitizes it to be compatible with the current standard. It replaces the original file. Currently: - removes all throw() specifications as they are not supported in C++ 17 :param generated_module_filepath:
625941c263b5f9789fde7081
def register(self, module): <NEW_LINE> <INDENT> assert not module.get_module_id() in self.modules <NEW_LINE> self.modules[module.get_module_id()] = module
Register a new module The only restriction is that the given class has to implement the static method get_module_id Args: module (Class): the module class to register
625941c2377c676e91272145
def main(args): <NEW_LINE> <INDENT> tab_printer(args) <NEW_LINE> model = Role2Vec(args) <NEW_LINE> model.do_walks() <NEW_LINE> model.create_structural_features() <NEW_LINE> model.learn_embedding() <NEW_LINE> model.save_embedding()
Role2Vec model fitting. :param args: Arguments object.
625941c2baa26c4b54cb10bd
@marc21.over('copy_and_version_identification_note', '^562..') <NEW_LINE> @utils.for_each_value <NEW_LINE> @utils.filter_values <NEW_LINE> def copy_and_version_identification_note(self, key, value): <NEW_LINE> <INDENT> return { 'identifying_markings': utils.force_list( value.get('a') ), 'version_identification': utils.force_list( value.get('c') ), 'copy_identification': utils.force_list( value.get('b') ), 'number_of_copies': utils.force_list( value.get('e') ), 'presentation_format': utils.force_list( value.get('d') ), 'materials_specified': value.get('3'), 'institution_to_which_field_applies': value.get('5'), 'linkage': value.get('6'), 'field_link_and_sequence_number': utils.force_list( value.get('8') ), }
Copy and Version Identification Note.
625941c221bff66bcd6848f0
def read_person(): <NEW_LINE> <INDENT> with open(filedialog.askopenfilename(defaultextension='.csv' , filetypes=[('CSV', '*.csv')] , title=PICK_FILE_TEXT), 'r', newline='') as base_file: <NEW_LINE> <INDENT> reader = csv.DictReader(base_file) <NEW_LINE> person = [] <NEW_LINE> for line in reader: <NEW_LINE> <INDENT> if person: <NEW_LINE> <INDENT> a_person = [a_person for a_person in person if a_person.person_id == line['Person ID']] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> a_person = [] <NEW_LINE> <DEDENT> if a_person: <NEW_LINE> <INDENT> a_person[0].add_activity(a.Activity(line['Location'], line['Activity Type'] , line['Activity ID'] , line['Start Date'] , line['End Date'])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_person = p.Person(line['Person ID'], line['Person Name']) <NEW_LINE> new_person.add_activity(a.Activity(line['Location'], line['Activity Type'] , line['Activity ID'] , line['Start Date'] , line['End Date'])) <NEW_LINE> person.append(new_person) <NEW_LINE> <DEDENT> <DEDENT> return person
Reads in person and their activities from the external file
625941c27d43ff24873a2c3b
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, PlaybackNearlyFinishedRequest): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941c2a219f33f34628908
def get(self, request, format=None): <NEW_LINE> <INDENT> an_apiview = [ 'Uses HTTP methods as function (get, post, patch, put, delete)', 'Is similar to a traditional Django View', 'Gives you the most control over your application logic', 'Is mapped manually to URLs', ] <NEW_LINE> return Response({'message':'Hello!','an_apiview':an_apiview})
Returns a list of APIView features.
625941c267a9b606de4a7e57
def WriteOutput( output, options ): <NEW_LINE> <INDENT> if options.global_sort: <NEW_LINE> <INDENT> output.sort() <NEW_LINE> <DEDENT> for o in output: <NEW_LINE> <INDENT> options.stdout.write( "%s\t%s\t%s\t%s\t%f\t%s\t%f\t%5.2f\t%s\n" % o[1])
sort output.
625941c223e79379d52ee502
def _full_from_frags(self, frags): <NEW_LINE> <INDENT> full_line = '\n'.join([l for l, _ in frags]) <NEW_LINE> line_info = frags[-1][-1] <NEW_LINE> return full_line, line_info
Join partial lines to full lines
625941c2004d5f362079a2d1
def test_first_line(self): <NEW_LINE> <INDENT> content = "ho-hum 567\n" + get_directory_authority(content = True) <NEW_LINE> self.assertRaises(ValueError, DirectoryAuthority, content) <NEW_LINE> authority = DirectoryAuthority(content, False) <NEW_LINE> self.assertEqual("turtles", authority.nickname) <NEW_LINE> self.assertEqual(["ho-hum 567"], authority.get_unrecognized_lines())
Includes a non-mandatory field before the 'dir-source' line.
625941c296565a6dacc8f668
def __init__(self, x, y, w, h, colors, title=None, border=True, shadow=True): <NEW_LINE> <INDENT> self.frame = Rect(x, y, w, h) <NEW_LINE> self.colors = colors <NEW_LINE> self.title = title <NEW_LINE> self.has_border = border <NEW_LINE> self.has_shadow = shadow <NEW_LINE> if border: <NEW_LINE> <INDENT> self.bounds = Rect(x + 1, y + 1, w - 2, h - 2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.bounds = self.frame.copy() <NEW_LINE> <DEDENT> if self.has_shadow: <NEW_LINE> <INDENT> self.rect = Rect(x, y, w + 2, h + 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.rect = self.frame.copy() <NEW_LINE> <DEDENT> self.background = None <NEW_LINE> self.flags = 0
initialize
625941c2462c4b4f79d1d66c
def regression_signature_fn(examples, unused_features, predictions): <NEW_LINE> <INDENT> if examples is None: <NEW_LINE> <INDENT> raise ValueError('examples cannot be None when using this signature fn.') <NEW_LINE> <DEDENT> default_signature = exporter.regression_signature( input_tensor=examples, output_tensor=predictions) <NEW_LINE> return default_signature, {}
Creates regression signature from given examples and predictions. Args: examples: `Tensor`. unused_features: `dict` of `Tensor`s. predictions: `Tensor`. Returns: Tuple of default regression signature and empty named signatures. Raises: ValueError: If examples is `None`.
625941c20383005118ecf580
def _grow_bin(self, bin_id, trajs, target_pop): <NEW_LINE> <INDENT> while len(trajs) < target_pop: <NEW_LINE> <INDENT> traj_split = max(trajs) <NEW_LINE> clones = traj_split.clone(self.clone_num) <NEW_LINE> for clone in clones: <NEW_LINE> <INDENT> heappush(trajs, clone)
Split trajectories to increase the population of a bin.
625941c207d97122c4178824
def export_ca_certs_file(self, cafile, ca_is_configured, conn=None): <NEW_LINE> <INDENT> if conn is None: <NEW_LINE> <INDENT> conn = api.Backend.ldap2 <NEW_LINE> <DEDENT> ca_certs = None <NEW_LINE> try: <NEW_LINE> <INDENT> ca_certs = certstore.get_ca_certs( conn, self.suffix, self.realm, ca_is_configured) <NEW_LINE> <DEDENT> except errors.NotFound: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> with open(cafile, 'wb') as fd: <NEW_LINE> <INDENT> for cert, _unused, _unused, _unused in ca_certs: <NEW_LINE> <INDENT> fd.write(cert.public_bytes(x509.Encoding.PEM))
Export the CA certificates stored in LDAP into a file :param cafile: the file to write the CA certificates to :param ca_is_configured: whether IPA is CA-less or not :param conn: an optional LDAP connection to use
625941c2be383301e01b5426
def get_cluster_info_by_id(self, region, id): <NEW_LINE> <INDENT> raise Exception("Unimplemented")
Given a region and cluster id, return more information about that cluster. :param region: Region name (str) :param id: Cluster ID (str) :return: Return a Cluster instance
625941c28c0ade5d55d3e955
def config_to_templates(project: Config) -> ProjectTemplates: <NEW_LINE> <INDENT> iam_template = iam.build(project) <NEW_LINE> inputs_template = inputs.build(project) <NEW_LINE> pipeline_templates = codepipeline.build(project) <NEW_LINE> core_template = core.build( project=project, inputs_template=inputs_template, iam_template=iam_template, pipeline_templates=pipeline_templates, ) <NEW_LINE> return ProjectTemplates( core=core_template, inputs=inputs_template, iam=iam_template, pipeline=pipeline_templates.template, codebuild=pipeline_templates.stage_templates, )
Construct all standalone templates from project. :param project: Source project :return: Constructed templates
625941c2187af65679ca50ba
def test_serialize(self): <NEW_LINE> <INDENT> attr_spec_dict = PRES_PREVIEW.attributes[0].serialize() <NEW_LINE> assert attr_spec_dict == { "name": "player", "cred_def_id": CD_ID, "value": "Richie Knucklez" }
Test serialization.
625941c2a8ecb033257d306a
def global_subscribe(bot, event, *args): <NEW_LINE> <INDENT> if not args: <NEW_LINE> <INDENT> raise commands.Help('Missing keyword and/or conversation!') <NEW_LINE> <DEDENT> if len(args) == 2 and (bot.call_shared('alias2convid', args[0]) or args[0] in bot.conversations): <NEW_LINE> <INDENT> conv_id = bot.call_shared('alias2convid', args[0]) or args[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> conv_id = event.conv_id <NEW_LINE> <DEDENT> alias = bot.call_shared('convid2alias', conv_id) or conv_id <NEW_LINE> keyword = args[-1].lower() <NEW_LINE> if keyword in _GLOBAL_KEYWORDS: <NEW_LINE> <INDENT> current = _GLOBAL_KEYWORDS[keyword] <NEW_LINE> if alias in current: <NEW_LINE> <INDENT> return _('The conversation "{alias}" already receives messages ' 'containing "{keyword}".').format(alias=alias, keyword=keyword) <NEW_LINE> <DEDENT> current.append(alias) <NEW_LINE> text = _('These conversation will receive messages containing ' '"{keyword}":\n{conv_ids}').format(keyword=keyword, conv_ids=', '.join(current)) <NEW_LINE> <DEDENT> elif keyword != 'show': <NEW_LINE> <INDENT> _GLOBAL_KEYWORDS[keyword] = [alias] <NEW_LINE> text = _('The conversation "{alias}" is the only one with a subscribe ' 'on "{keyword}"').format(alias=alias, keyword=keyword) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> subscribes = [] <NEW_LINE> for keyword_, conversations in _GLOBAL_KEYWORDS.copy().items(): <NEW_LINE> <INDENT> if alias in conversations: <NEW_LINE> <INDENT> subscribes.append(keyword_) <NEW_LINE> <DEDENT> <DEDENT> keywords = ', '.join('"%s"' % item for item in subscribes) or _('None') <NEW_LINE> return _('The conversation "{alias}" has subscribed to {keywords}' ).format(alias=alias, keywords=keywords) <NEW_LINE> <DEDENT> bot.memory['hosubscribe'] = _GLOBAL_KEYWORDS <NEW_LINE> bot.memory.save() <NEW_LINE> return text
subscribe keywords globally with a custom conversation as target Args: bot (hangupsbot.core.HangupsBot): the running instance event (hangupsbot.event.ConversationEvent): a message container args (str): the query for the command Returns: str: a status message Raises: commands.Help: the keyword to subscribe is missing
625941c23539df3088e2e2e8
def has_dwarf_info(self): <NEW_LINE> <INDENT> return bool(self.get_section_by_name('.debug_info'))
Check whether this file appears to have debugging information. We assume that if it has the debug_info section, it has all theother required sections as well.
625941c2956e5f7376d70e0b
def tearDown(self): <NEW_LINE> <INDENT> for image_creator in self.image_creators: <NEW_LINE> <INDENT> image_creator.clean() <NEW_LINE> <DEDENT> if os.path.exists(self.tmp_dir) and os.path.isdir(self.tmp_dir): <NEW_LINE> <INDENT> shutil.rmtree(self.tmp_dir) <NEW_LINE> <DEDENT> super(self.__class__, self).__clean__()
Cleans the images and downloaded image file
625941c29f2886367277a82b
def deserialize_numpy(self, str, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> end = 0 <NEW_LINE> _x = self <NEW_LINE> start = end <NEW_LINE> end += 12 <NEW_LINE> (_x.y, _x.x, _x.z,) = _struct_3i.unpack(str[start:end]) <NEW_LINE> return self <NEW_LINE> <DEDENT> except struct.error as e: <NEW_LINE> <INDENT> raise genpy.DeserializationError(e)
unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module
625941c2090684286d50ec80
def _is_raising(body: List) -> bool: <NEW_LINE> <INDENT> return any(isinstance(node, nodes.Raise) for node in body)
Return whether the given statement node raises an exception.
625941c24a966d76dd550faa
def test_write_int(self): <NEW_LINE> <INDENT> self.assertEqual(_write_int(0x00), b'\x00') <NEW_LINE> self.assertEqual(_write_int(-0x01), b'\xff') <NEW_LINE> self.assertEqual(_write_int(0x80), b'\x80') <NEW_LINE> self.assertEqual(_write_int(0xffff), b'\xff\xff') <NEW_LINE> self.assertEqual(_write_int(0xffffffff), b'\xff\xff\xff\xff') <NEW_LINE> self.assertEqual(_write_int(0xffffffffff), b'\xff\xff\xff\xff\xff')
Test _write_int
625941c215baa723493c3f10
def ContextSetupDisplay( self, node): <NEW_LINE> <INDENT> super( SelectRenderPass, self).ContextSetupDisplay( node ) <NEW_LINE> self.PickProjection()
Customization point calls PickProjection after standard setup
625941c20fa83653e4656f59
def input_boss_name(self, boss_name): <NEW_LINE> <INDENT> self.driver.find_element(*createcustomer.SHOP_BOSS).send_keys(boss_name) <NEW_LINE> handler.logger.info('输入老板名称') <NEW_LINE> return self
输入老板名称
625941c26fb2d068a760f038
def test__build_keys_weekly_week_starts_monday(self): <NEW_LINE> <INDENT> test_settings = TEST_SETTINGS.copy() <NEW_LINE> test_settings['MONDAY_FIRST_DAY_OF_WEEK'] = True <NEW_LINE> with override_settings(REDIS_METRICS=test_settings): <NEW_LINE> <INDENT> d = datetime(2012, 4, 1) <NEW_LINE> keys = self.r._build_keys('test-slug', date=d, granularity='weekly') <NEW_LINE> self.assertEqual(keys, ['m:test-slug:w:2012-13'])
Tests ``R._build_keys``. with a *weekly* granularity.
625941c2cad5886f8bd26f76
def __init__(self, generator, **kwargs): <NEW_LINE> <INDENT> self.availableOptions.update({ 'replace': False, 'summary': None, 'text': 'Test', 'top': False, 'outpage': u'User:mastiBot/test', 'maxlines': 1000, 'testprint': False, 'negative': False, 'test': False, }) <NEW_LINE> super(BasicBot, self).__init__(site=True, **kwargs) <NEW_LINE> self._handle_dry_param(**kwargs) <NEW_LINE> self.generator = generator
Constructor. @param generator: the page generator that determines on which pages to work @type generator: generator
625941c2a8370b771705283d
def inv_line_characteristic_hashcode(self, invoice_line): <NEW_LINE> <INDENT> code = super().inv_line_characteristic_hashcode( invoice_line ) <NEW_LINE> hashcode = '%s-%s-%s' % ( code, invoice_line.get('start_date', 'False'), invoice_line.get('end_date', 'False'), ) <NEW_LINE> return hashcode
Add start and end dates to hashcode used when the option "Group Invoice Lines" is active on the Account Journal
625941c2a17c0f6771cbdfef
def test_make_procurement_order(self): <NEW_LINE> <INDENT> vals = { 'picking_type_id': self.env.ref('stock.picking_type_in').id, 'requested_by': SUPERUSER_ID, 'location_id': self.env['stock.location'].search([], limit=1).id, 'warehouse_id': self.env['stock.warehouse'].search([], limit=1).id, 'state': 'approved', } <NEW_LINE> purchase_request = self.purchase_request.create(vals) <NEW_LINE> vals = { 'request_id': purchase_request.id, 'product_id': self.env.ref('product.product_product_13').id, 'product_uom_id': self.env.ref('product.product_uom_unit').id, 'product_qty': 5.0, } <NEW_LINE> line = self.purchase_request_line.create(vals) <NEW_LINE> ctx = { 'active_ids': [line.id], 'active_id': line.id, 'active_model': 'purchase.request.line', } <NEW_LINE> wiz_mod = self.env['purchase.request.line.make.procurement.order'] <NEW_LINE> wiz_id = wiz_mod.with_context(ctx).create({}) <NEW_LINE> res = wiz_id.make_procurement_order() <NEW_LINE> procurement_ids = res['domain'][0][2] <NEW_LINE> self.assertEquals( line.procurement_id.id, procurement_ids[0], 'Should be the same procurement order id')
test generation of procurement order
625941c2379a373c97cfaae1
def __init__(self, dustmap, mapname, inmaps, scale=1., errorname='None',hpx=True): <NEW_LINE> <INDENT> self.dustmap = fits.open(dustmap) <NEW_LINE> self.mapname = mapname <NEW_LINE> self.scale = scale <NEW_LINE> self.errorname = errorname <NEW_LINE> self.hpx = hpx <NEW_LINE> self.gasmaps = [] <NEW_LINE> self.nreg = len(inmaps) <NEW_LINE> self.region = [] <NEW_LINE> for s, region in enumerate(inmaps): <NEW_LINE> <INDENT> for filename in region: <NEW_LINE> <INDENT> self.region.append(s) <NEW_LINE> self.gasmaps.append(fits.open(filename)[0])
Constructor for class to create extinction residuals from dust map and set of gas maps for given distance range. :param dustmap: `string` FITS file with dust map :param mapname: `string` name of column (HPX) or HDU (WCS) containing dust map :param inmaps: `list` FITS file with WCS map in first HDU (gas maps) :param scale: `float` scaling to apply to the extinction map (so that fitting coeff are O(1)) :param scale: `string` name of column containing error map, 'None' for no error
625941c24428ac0f6e5ba78e
def welcome_messages_rules_new(): <NEW_LINE> <INDENT> binding = {} <NEW_LINE> url = 'https://api.twitter.com/1.1/direct_messages/welcome_messages/rules/new.json' <NEW_LINE> return _TwitterRequest('POST', url, 'rest:direct_messages', 'post-direct-messages-welcome-messages-rules-new', binding)
Creates a new Welcome Message Rule that determines which Welcome Message will be shown in a given conversation. Returns the created rule if successful.
625941c224f1403a92600b05
def _get_closest_ontology_node(self, name): <NEW_LINE> <INDENT> if not self._ontology_regex: <NEW_LINE> <INDENT> nodes = self._session.query(OntologyNode).all() <NEW_LINE> def sort_function(x, y): <NEW_LINE> <INDENT> return cmp(len(y.name), len(x.name)) or cmp(y.depth, x.depth) <NEW_LINE> <DEDENT> nodes.sort(sort_function) <NEW_LINE> self._ontology_regex = re.compile('|'.join('\\b%s\\b' % n.name for n in nodes)) <NEW_LINE> <DEDENT> match = self._ontology_regex.match(name) <NEW_LINE> if match and match.group(0): <NEW_LINE> <INDENT> node_name = match.group(0) <NEW_LINE> ontology_node = (self._session .query(OntologyNode) .filter_by(name=node_name) .order_by(desc(OntologyNode.depth))).first() <NEW_LINE> return ontology_node <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
Find the ontlogy node that is the best match against the input string, or None if no node matches.
625941c28a349b6b435e8110
def numAtoms(self, flag=None): <NEW_LINE> <INDENT> return len(self._getSubset(flag)) if flag else len(self._indices)
Return number of atoms, or number of atoms with given *flag*.
625941c2fb3f5b602dac362e
def t_LBRACE(t): <NEW_LINE> <INDENT> t.lexer.paren_stack.append("}") <NEW_LINE> return OP(t, "{")
BUCKET\b
625941c2f7d966606f6a9f9f
def _main(args): <NEW_LINE> <INDENT> main_path = pathlib.Path(args.output_dir).resolve() <NEW_LINE> main_path.mkdir(exist_ok=True) <NEW_LINE> template_definition = args.template_definition <NEW_LINE> template_location = template_utilities.get_template_directory() <NEW_LINE> templates_path = template_utilities.install_template(template_location, template_definition) <NEW_LINE> settings = get_configuration() <NEW_LINE> settings.publishing.templates = str(templates_path.relative_to(main_path)) <NEW_LINE> configuration_file_path = main_path / 'config.yaml' <NEW_LINE> dump_configuration(configuration_file_path, settings) <NEW_LINE> for directory in settings.processing.inputs: <NEW_LINE> <INDENT> log_directory = main_path / directory <NEW_LINE> log_directory.mkdir(parents=True, exist_ok=True)
Generate the content for storage.
625941c2187af65679ca50bb
@main.route('/') <NEW_LINE> def index(): <NEW_LINE> <INDENT> entertainment_news = get_news('entertain') <NEW_LINE> title = 'Home - Welcome to The best news Review Website Online' <NEW_LINE> return render_template('index.html', title = title,entertain = entertainment_news)
View root page function that returns the index page and its data
625941c2b830903b967e98aa
def DA(self, n): <NEW_LINE> <INDENT> pass
R/W Modo de adquisicion de datos: si 'n' es omitido este comano devolvera el modo de adquisicion de datos que se esta utilizando. Si si el valor de 'n' es definido se ajustara el modo de adquisicion de datos a ese valor. (Ver Data Adquisitions Mode Section XVIII 1461's manual)
625941c255399d3f05588650
def get_node_type(order, csv_line_dict): <NEW_LINE> <INDENT> if order == str(0): <NEW_LINE> <INDENT> return consts.Consts.start_event <NEW_LINE> <DEDENT> if csv_line_dict[consts.Consts.csv_terminated] == 'yes': <NEW_LINE> <INDENT> return consts.Consts.end_event <NEW_LINE> <DEDENT> if csv_line_dict[consts.Consts.csv_subprocess] == 'yes': <NEW_LINE> <INDENT> return consts.Consts.subprocess <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return consts.Consts.task
:param order: :param csv_line_dict: :return:
625941c276e4537e8c35160d
@api.cache.memoize() <NEW_LINE> def get_solved_problems(tid=None, uid=None, category=None, show_disabled=False): <NEW_LINE> <INDENT> if uid is not None and tid is None: <NEW_LINE> <INDENT> team = api.user.get_team(uid=uid) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> team = api.team.get_team(tid=tid) <NEW_LINE> <DEDENT> members = api.team.get_team_uids(tid=team["tid"]) <NEW_LINE> submissions = get_submissions(tid=tid, uid=uid, category=category, correctness=True) <NEW_LINE> for uid in members: <NEW_LINE> <INDENT> submissions += get_submissions(uid=uid, category=category, correctness=True) <NEW_LINE> <DEDENT> pids = [] <NEW_LINE> result = [] <NEW_LINE> for submission in submissions: <NEW_LINE> <INDENT> if submission["pid"] not in pids: <NEW_LINE> <INDENT> pids.append(submission["pid"]) <NEW_LINE> problem = unlocked_filter(get_problem(pid=submission["pid"]), True) <NEW_LINE> problem["solve_time"] = submission["timestamp"] <NEW_LINE> if not problem["disabled"] or show_disabled: <NEW_LINE> <INDENT> result.append(problem) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return result
Gets the solved problems for a given team or user. Args: tid: The team id category: Optional parameter to restrict which problems are returned Returns: List of solved problem dictionaries
625941c2ad47b63b2c509f1c
def is_unused(name: str) -> bool: <NEW_LINE> <INDENT> return UNUSED_VARIABLE_REGEX.match(name) is not None
Checks whether the given ``name`` is unused. >>> is_unused('_') True >>> is_unused('___') True >>> is_unused('_protected') False >>> is_unused('__private') False
625941c2a219f33f34628909
def generate_random_name(): <NEW_LINE> <INDENT> return '{} {}'.format(random.choice(CSS_COLOR_NAMES), random.choice(ANIMAL_NAMES))
Return a random name generated from a list of colors and animals :return:
625941c263d6d428bbe4448c
def e_monossilabo(arg): <NEW_LINE> <INDENT> check_str(arg, 'e_monossilabo:argumento invalido') <NEW_LINE> return arg in monossilabo
Verifica se um objeto e um monossilabo Args: arg (object) Levanta: ValueError: Caso `arg` nao for uma string. Retorna: bool: True se `arg` for considerado um monossilabo. False caso o contrario.
625941c26fece00bbac2d6da
def hook_point(hooks): <NEW_LINE> <INDENT> def hook_point_dec(func): <NEW_LINE> <INDENT> hook_name = func.__name__ <NEW_LINE> if asyncio.iscoroutinefunction(func): <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> async def async_wrapped(*args, **kwargs): <NEW_LINE> <INDENT> return await run_async_hooks(hooks, hook_name, func, *args, **kwargs) <NEW_LINE> <DEDENT> return async_wrapped <NEW_LINE> <DEDENT> @functools.wraps(func) <NEW_LINE> def wrapped(*args, **kwargs): <NEW_LINE> <INDENT> return run_hooks(hooks, hook_name, func, *args, **kwargs) <NEW_LINE> <DEDENT> return wrapped <NEW_LINE> <DEDENT> return hook_point_dec
Define a function with pre and post hooks given a hooks dictionary.
625941c27d43ff24873a2c3c
def connect_JSON(config): <NEW_LINE> <INDENT> testnet = config.get('testnet', '0') <NEW_LINE> testnet = (int(testnet) > 0) <NEW_LINE> if not 'rpcport' in config: <NEW_LINE> <INDENT> config['rpcport'] = 19998 if testnet else 9998 <NEW_LINE> <DEDENT> connect = "http://%s:%s@127.0.0.1:%s"%(config['rpcuser'], config['rpcpassword'], config['rpcport']) <NEW_LINE> try: <NEW_LINE> <INDENT> result = ServiceProxy(connect) <NEW_LINE> if result.getmininginfo()['testnet'] != testnet: <NEW_LINE> <INDENT> sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n") <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> sys.stderr.write("Error connecting to RPC server at "+connect+"\n") <NEW_LINE> sys.exit(1)
Connect to a CryptoPlay Core JSON-RPC server
625941c215fb5d323cde0aaa
def test_post_apps_empty_body(self): <NEW_LINE> <INDENT> user = User.objects.create(username='ivan') <NEW_LINE> self.client.force_authenticate(user=user) <NEW_LINE> url = reverse('apps') <NEW_LINE> response = self.client.post(url, {}, format='json') <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
Ensure posting to apps when body is empty returns 400
625941c23c8af77a43ae373b
def getFileHandle(self, filePath): <NEW_LINE> <INDENT> import zipfile <NEW_LINE> import tarfile <NEW_LINE> if self.fileType == '.zip' or not self.fileType and zipfile.is_zipfile(filePath): <NEW_LINE> <INDENT> z = zipfile.ZipFile(filePath, 'r') <NEW_LINE> archiveContent = self.getArchiveContentName(z.namelist(), filePath) <NEW_LINE> return StringIO(z.read(archiveContent) .decode(self.ENCODING)) <NEW_LINE> <DEDENT> elif self.fileType in ('.tar', '.tar.bz2', '.tar.gz') or not self.fileType and tarfile.is_tarfile(filePath): <NEW_LINE> <INDENT> mode = '' <NEW_LINE> ending = self.fileType or filePath <NEW_LINE> if ending.endswith('bz2'): <NEW_LINE> <INDENT> mode = ':bz2' <NEW_LINE> <DEDENT> elif ending.endswith('gz'): <NEW_LINE> <INDENT> mode = ':gz' <NEW_LINE> <DEDENT> z = tarfile.open(filePath, 'r' + mode) <NEW_LINE> archiveContent = self.getArchiveContentName(z.getnames(), filePath) <NEW_LINE> fileObj = z.extractfile(archiveContent) <NEW_LINE> return StringIO(fileObj.read().decode(self.ENCODING)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> import gzip <NEW_LINE> z = gzip.open(filePath, 'r') <NEW_LINE> return StringIO(z.read().decode(self.ENCODING)) <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> if e.args[0] != 'Not a gzipped file': <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> import codecs <NEW_LINE> return codecs.open(filePath, 'r', self.ENCODING)
Returns a handle to the give file. The file can be either normal content, zip, tar, .tar.gz, tar.bz2 or gz. :type filePath: str :param filePath: path of file :rtype: file :return: handle to file's content
625941c2925a0f43d2549e12
def manifest_upload(org): <NEW_LINE> <INDENT> manifest_name = settings.fake_manifest.url.default.split('/')[-1] <NEW_LINE> try: <NEW_LINE> <INDENT> with open(f'{manifest_name}', 'rb') as manifest: <NEW_LINE> <INDENT> entities.Subscription(nailgun_conf, organization=org).upload( data={'organization_id': org.id}, files={'content': manifest} ) <NEW_LINE> <DEDENT> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> logger.warn(ex) <NEW_LINE> <DEDENT> entities.Subscription(nailgun_conf, organization=org).refresh_manifest( data={'organization_id': org.id}, timeout=5000 )
Use to download and upload the manifest file.
625941c207f4c71912b1141e
def exitonclick(self): <NEW_LINE> <INDENT> def exitGracefully(x, y): <NEW_LINE> <INDENT> self.bye() <NEW_LINE> <DEDENT> self.onclick(exitGracefully) <NEW_LINE> if _CFG["using_IDLE"]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> mainloop() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> exit(0)
『0027 中文說明』 在點擊時離開,進入主​​迴圈,直到鼠標點擊關閉視窗。 沒有參數。 在龜幕類點擊鼠標時綁定 再見() 函數。 如果"using_IDLE" - 在配置詞典值為 假(默認值), 並進入主循環。 如果在-n模式下的IDLE(無子程式)時 - 在 turtle.cfg 值設置為 真。 在這種情況下,客戶端腳本的IDLE進行主循環。 這是Screen-class的函數,在 龜幕類 沒有可用的實例。 範例: >>> 在點擊時離開() Go into mainloop until the mouse is clicked. No arguments. Bind bye() method to mouseclick on TurtleScreen. If "using_IDLE" - value in configuration dictionary is False (default value), enter mainloop. If IDLE with -n switch (no subprocess) is used, this value should be set to True in turtle.cfg. In this case IDLE's mainloop is active also for the client script. This is a method of the Screen-class and not available for TurtleScreen instances. Example (for a Screen instance named screen): >>> screen.exitonclick()
625941c28c3a873295158355
def remove(self, rule): <NEW_LINE> <INDENT> del self._rules[rule.condition]
Remove this classifier rule from the action set. (Does not affect numerosity.) A KeyError is raised if the rule is not present in the action set when this method is called. Usage: if rule in action_set: action_set.remove(rule) Arguments: rule: The ClassifierRule instance to be removed. Return: None
625941c25fcc89381b1e165a
def create_model_trainable(self): <NEW_LINE> <INDENT> outputs, reg = self.nn(self.input_placeholder) <NEW_LINE> self.predictions = outputs <NEW_LINE> self.q_vals = tf.reduce_sum(tf.mul(self.predictions, self.actions_placeholder), 1) <NEW_LINE> self.loss = tf.reduce_sum(tf.square(self.labels_placeholder - self.q_vals)) + reg <NEW_LINE> optimizer = tf.train.GradientDescentOptimizer(learning_rate = self.lr) <NEW_LINE> self.train_op = optimizer.minimize(self.loss)
The model definition.
625941c2377c676e91272146
def randstring(l): <NEW_LINE> <INDENT> tmp = [struct.pack("B", random.randrange(0, 256, 1)) for x in [""]*l] <NEW_LINE> return "".join(tmp)
Returns a random string of length l (l >= 0)
625941c2dd821e528d63b148
def auto_eat(self): <NEW_LINE> <INDENT> cur_player_species = self.player_state(self.current_player_index).species <NEW_LINE> hungry_herbivores = [species for species in cur_player_species if "carnivore" not in species.trait_names() and species.can_eat()] <NEW_LINE> hungry_carnivores = [species for species in cur_player_species if "carnivore" in species.trait_names() and species.can_eat()] <NEW_LINE> if len(hungry_herbivores) == 1 and len(hungry_carnivores) == 0: <NEW_LINE> <INDENT> eater = hungry_herbivores[0] <NEW_LINE> herbivore_index = cur_player_species.index(eater) <NEW_LINE> if "fat-tissue" in eater.trait_names(): <NEW_LINE> <INDENT> max_food = eater.body - eater.fat_storage <NEW_LINE> food_requested = min(self.watering_hole, max_food) <NEW_LINE> return [herbivore_index, food_requested] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return herbivore_index <NEW_LINE> <DEDENT> <DEDENT> if len(hungry_carnivores) == 1 and len(hungry_herbivores) == 0: <NEW_LINE> <INDENT> eater = hungry_carnivores[0] <NEW_LINE> carnivore_index = cur_player_species.index(eater) <NEW_LINE> targets = Dealer.carnivore_targets(eater, self.opponents()) <NEW_LINE> target_player = next(player for player in self.player_states() if targets[0] in player.species) <NEW_LINE> if len(targets) == 1 and target_player.species != cur_player_species: <NEW_LINE> <INDENT> defender_index = target_player.species.index(targets[0]) <NEW_LINE> target_index = self.opponents().index(target_player) <NEW_LINE> return [carnivore_index, target_index, defender_index] <NEW_LINE> <DEDENT> <DEDENT> return None
feeds a species when there is only one herbivore or one carnivore with one defender :param list_of_species: the current players species :return: A Feeding, or None if a feeding choice cannot be automatic.
625941c2d268445f265b4e0c
def HWIndex(session_id, top_N_size, refined_positive, refined_negative): <NEW_LINE> <INDENT> ret_pool_size = top_N_size * 5 <NEW_LINE> ordered_id_list = __hw_clip_ids[session_id].intersection(refined_positive).union( __hw_clip_ids[session_id].difference(refined_positive, refined_negative).union( __hw_clip_ids[session_id].intersection(refined_negative))) <NEW_LINE> ordered_id_list = sorted(tuple(ordered_id_list)) <NEW_LINE> assert len(ordered_id_list) == len(__hw_clip_ids[session_id]) <NEW_LINE> return ordered_id_list[:ret_pool_size]
:param session_id: The UUID of an initialized session. :type session_id: uuid.UUID :param top_N_size: The number of clips that are to have a high probability of being in the list of clip IDs that this function returns. :type top_N_size: int :param refined_negative: Iterable of clip IDs that are known to be positive. :type refined_negative: Iterable of int :param refined_positive: Iterable of clip IDs that are known to be negative. :type refined_positive: Iterable of int :raises KeyError: If session id given that wasn't initialized. :return: Pool of clip IDs that has a high probability of containing the top ``top_N_size`` videos. This dummy impl returns a number of IDs equal to 5 times the given N size. :rtype: tuple of int
625941c210dbd63aa1bd2b42
def patch(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'method':'Patch'})
patch request where pk is id with which only we are gonna update only the field that is given as input
625941c2b545ff76a8913db4
def chunks(lst, num): <NEW_LINE> <INDENT> for i in range(0, len(lst), num): <NEW_LINE> <INDENT> yield lst[i:i + num]
Yield successive n-sized chunks from l.
625941c2a05bb46b383ec7c1
def set_can_edit_billing_address(self, can_edit_billing_address): <NEW_LINE> <INDENT> self.can_edit_billing_address = can_edit_billing_address
Turns edit-ability of the billing address on/off.
625941c2090684286d50ec81
def on_click(self, int): <NEW_LINE> <INDENT> config.config.set('window.quitPrompt', self.checkbox.isChecked()) <NEW_LINE> config.config.save()
save checkbox state to config
625941c27cff6e4e81117923
def test_warp_reproject_bounds_crossup_fail(runner, tmpdir): <NEW_LINE> <INDENT> srcname = 'tests/data/shade.tif' <NEW_LINE> outputname = str(tmpdir.join('test.tif')) <NEW_LINE> out_bounds = [-11850000, 4810000, -11849000, 4812000] <NEW_LINE> result = runner.invoke(main_group, [ 'warp', srcname, outputname, '--dst-crs', 'EPSG:4326', '--res', 0.001, '--bounds'] + out_bounds) <NEW_LINE> assert result.exit_code == 2
Crossed-up bounds raises click.BadParameter.
625941c2ac7a0e7691ed406d
def unescape_html(text): <NEW_LINE> <INDENT> def fixup(m): <NEW_LINE> <INDENT> text = m.group(0) <NEW_LINE> if text[:2] == "&#": <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if text[:3] == "&#x": <NEW_LINE> <INDENT> return unichr(int(text[3:-1], 16)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return unichr(int(text[2:-1])) <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return text <NEW_LINE> <DEDENT> return re.sub("&#?\w+;", fixup, text)
Created by Fredrik Lundh (http://effbot.org/zone/re-sub.htm#unescape-html)
625941c2d53ae8145f87a210
def read_running_games(session): <NEW_LINE> <INDENT> rgs = session.query(RunningGame).all() <NEW_LINE> return [(rg.gameid, rg.situationid, rg.public_ranges, rg.current_userid, rg.next_hh, rg.board_raw, rg.total_board_raw, rg.current_round, rg.pot_pre, rg.increment, rg.bet_count, rg.current_factor, rg.last_action_time, rg.analysis_performed, rg.spawn_factor, rg.spawn_group, rg.spawn_finished) for rg in rgs]
Read RunningGame table from DB into memory
625941c26aa9bd52df036d40
def forward(self, x): <NEW_LINE> <INDENT> h_0 = Variable(torch.zeros( self.n_layers, x.size(0), self.hidden_size)) <NEW_LINE> c_0 = Variable(torch.zeros( self.n_layers, x.size(0), self.hidden_size)) <NEW_LINE> output, (hn, cn) = self.lstm(x, (h_0, c_0)) <NEW_LINE> return output
Train the model to fit the data
625941c263f4b57ef00010bc
def locateMark( mark, payload ): <NEW_LINE> <INDENT> index = payload.find(mark) <NEW_LINE> if index < 0: <NEW_LINE> <INDENT> log.debug("Could not find the mark just yet.") <NEW_LINE> return None <NEW_LINE> <DEDENT> if (len(payload) - index - const.MARK_LENGTH) < const.HMAC_SHA256_128_LENGTH: <NEW_LINE> <INDENT> log.debug("Found the mark but the HMAC is still incomplete.") <NEW_LINE> return None <NEW_LINE> <DEDENT> log.debug("Successfully located the mark.") <NEW_LINE> return index
Locate the given `mark' in `payload' and return its index. The `mark' is placed before the HMAC of a ScrambleSuit authentication mechanism and makes it possible to efficiently locate the HMAC. If the `mark' could not be found, `None' is returned.
625941c2cc40096d615958ee
def convert_params_dict_to_list(model_params_dict): <NEW_LINE> <INDENT> configs = list() <NEW_LINE> for encoding_dimension in model_params_dict["encoding_dimension"]: <NEW_LINE> <INDENT> for activation in model_params_dict["activation"]: <NEW_LINE> <INDENT> for loss in model_params_dict["loss"]: <NEW_LINE> <INDENT> for optimizer in model_params_dict["optimizer"]: <NEW_LINE> <INDENT> for epoch in model_params_dict["epochs"]: <NEW_LINE> <INDENT> cfg = [ encoding_dimension, activation, loss, optimizer, epoch ] <NEW_LINE> configs.append(cfg) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return configs
convert params dict to list :param model_params_dict: model params dict :return: model params dict to list
625941c285dfad0860c3adf7
def delete_lungroup_mapping_view(self, view_id, lungroup_id): <NEW_LINE> <INDENT> url = "/mappingview/REMOVE_ASSOCIATE" <NEW_LINE> data = json.dumps({"ASSOCIATEOBJTYPE": "256", "ASSOCIATEOBJID": lungroup_id, "TYPE": "245", "ID": view_id}) <NEW_LINE> result = self.call(url, data, "PUT") <NEW_LINE> self._assert_rest_result(result, _('Delete lungroup from mapping view ' 'error.'))
Remove lungroup associate from the mapping view.
625941c2be8e80087fb20be3
def test_cmd_write_piezo() -> None: <NEW_LINE> <INDENT> assert type(CMD_WRITE_PIEZO) is WriteCommand <NEW_LINE> assert CMD_WRITE_PIEZO.code == 8
Test that the CMD_WRITE_PIEZO.
625941c20a50d4780f666e2e
def calculate_max_drawdown(trades: pd.DataFrame, *, date_col: str = 'close_date', value_col: str = 'profit_percent' ) -> Tuple[float, pd.Timestamp, pd.Timestamp]: <NEW_LINE> <INDENT> if len(trades) == 0: <NEW_LINE> <INDENT> raise ValueError("Trade dataframe empty.") <NEW_LINE> <DEDENT> profit_results = trades.sort_values(date_col).reset_index(drop=True) <NEW_LINE> max_drawdown_df = pd.DataFrame() <NEW_LINE> max_drawdown_df['cumulative'] = profit_results[value_col].cumsum() <NEW_LINE> max_drawdown_df['high_value'] = max_drawdown_df['cumulative'].cummax() <NEW_LINE> max_drawdown_df['drawdown'] = max_drawdown_df['cumulative'] - max_drawdown_df['high_value'] <NEW_LINE> idxmin = max_drawdown_df['drawdown'].idxmin() <NEW_LINE> if idxmin == 0: <NEW_LINE> <INDENT> raise ValueError("No losing trade, therefore no drawdown.") <NEW_LINE> <DEDENT> high_date = profit_results.loc[max_drawdown_df.iloc[:idxmin]['high_value'].idxmax(), date_col] <NEW_LINE> low_date = profit_results.loc[idxmin, date_col] <NEW_LINE> return abs(min(max_drawdown_df['drawdown'])), high_date, low_date
Calculate max drawdown and the corresponding close dates :param trades: DataFrame containing trades (requires columns close_date and profit_percent) :param date_col: Column in DataFrame to use for dates (defaults to 'close_date') :param value_col: Column in DataFrame to use for values (defaults to 'profit_percent') :return: Tuple (float, highdate, lowdate) with absolute max drawdown, high and low time :raise: ValueError if trade-dataframe was found empty.
625941c2009cb60464c63351
def contribute_to_class(self, cls, name): <NEW_LINE> <INDENT> models.signals.pre_save.connect(self._pre_save, sender=cls) <NEW_LINE> models.signals.post_save.connect(self._post_save, sender=cls) <NEW_LINE> super(ObfuscatedIdField, self).contribute_to_class(cls, name)
We register against save signals, so that when this class tries to save, we can update its oid fields.
625941c297e22403b379cf37
def draw_schacht(name): <NEW_LINE> <INDENT> wasserstand = self.__simulation.get("schaechte").get(name) <NEW_LINE> self.__x += [self.__x_pointer, self.__x_pointer + self.__schacht_breite] <NEW_LINE> self.__y += [wasserstand, wasserstand] <NEW_LINE> self.__x_pointer += self.__schacht_breite
Zeichnet den maximalen Wasserstand des Schachts ein und geht dabei von einer festen Schachtbreite aus. :param name: Entspricht dem Namen des Schachts. :type name: str
625941c23c8af77a43ae373c
def test_intercompany_read(self): <NEW_LINE> <INDENT> self.env["res.partner"].with_user(self.user_x).browse(self.partner_y.id).name <NEW_LINE> self.env["res.partner"].with_user(self.user_y).browse(self.partner_x.id).name
Company contacts are readable by other companies
625941c2656771135c3eb80a
def __read_str(self, numchars=1, utf=None): <NEW_LINE> <INDENT> rawstr = np.asscalar(np.fromfile(self._fsrc, dtype='S%s' % numchars, count=1)) <NEW_LINE> if utf or (utf is None and PY_VER == 3): <NEW_LINE> <INDENT> return rawstr.decode('utf-8') <NEW_LINE> <DEDENT> return rawstr
Read a string of a specific length. This is compatible with python 2 and python 3.
625941c2cc0a2c11143dce2e
def delete(self, key): <NEW_LINE> <INDENT> if self.size > 1: <NEW_LINE> <INDENT> nodeToRemove = self._get(key, self.root) <NEW_LINE> if nodeToRemove: <NEW_LINE> <INDENT> self.remove(nodeToRemove) <NEW_LINE> self.size = self.size - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError('Error, key not in tree') <NEW_LINE> <DEDENT> <DEDENT> elif self.size == 1 and self.root.key == key: <NEW_LINE> <INDENT> self.root = None <NEW_LINE> self.size = self.size - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError('Error, key not in tree')
删除某个节点
625941c2d486a94d0b98e0e3
def decode_body(self): <NEW_LINE> <INDENT> self.body = self.body.decode(self.encoding)
Decode (and replace) self.body via the charset encoding specified in the content-type header
625941c23cc13d1c6d3c7319
def update_profile_network(uci, network_id, current_profile, new_profile): <NEW_LINE> <INDENT> reload_dropbear, reload_firewall = (False, False) <NEW_LINE> if new_profile["ssh"] != current_profile["ssh"]: <NEW_LINE> <INDENT> uci.set_option(SSH_PKG, network_id, "enable", "1" if new_profile["ssh"]["enabled"] else "0") <NEW_LINE> uci.persist(SSH_PKG) <NEW_LINE> reload_dropbear = True <NEW_LINE> <DEDENT> update_blocking = new_profile["deviceBlocking"] != current_profile["deviceBlocking"] <NEW_LINE> update_access = new_profile["deviceAccess"] != current_profile["deviceAccess"] <NEW_LINE> if update_blocking or update_access: <NEW_LINE> <INDENT> for rule in uci.get_package(FIREWALL_PKG): <NEW_LINE> <INDENT> if ".type" in rule and rule[".type"] == "rule" and "id" in rule and rule["id"]: <NEW_LINE> <INDENT> is_blocking_rule = update_blocking and "src_mac" in rule and "src" in rule and rule["src"] == network_id <NEW_LINE> is_access_rule = update_access and "set_mark" in rule and rule["set_mark"] == NETWORK_MARKS[network_id] <NEW_LINE> if is_blocking_rule or is_access_rule: <NEW_LINE> <INDENT> uci.delete_config(FIREWALL_PKG, rule["id"]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if new_profile["deviceBlocking"]["enabled"] or new_profile["deviceAccess"]["enabled"]: <NEW_LINE> <INDENT> all_devices = devices.get_devices(uci) <NEW_LINE> <DEDENT> if update_blocking and new_profile["deviceBlocking"]["enabled"]: <NEW_LINE> <INDENT> for device_id, rules in new_profile["deviceBlocking"]["deviceRules"].items(): <NEW_LINE> <INDENT> device = next(device for device in all_devices if device["id"] == device_id) <NEW_LINE> for rule in rules: <NEW_LINE> <INDENT> create_blocking_rule(uci, network_id, device["macAddress"], rule) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if update_access and new_profile["deviceAccess"]["enabled"]: <NEW_LINE> <INDENT> for device_id in sorted(set(new_profile["deviceAccess"]["devices"])): <NEW_LINE> <INDENT> device = next(device for device in all_devices if device["id"] == device_id) <NEW_LINE> create_device_access_rule(uci, network_id, device["macAddress"]) <NEW_LINE> <DEDENT> <DEDENT> uci.persist(FIREWALL_PKG) <NEW_LINE> reload_firewall = True <NEW_LINE> <DEDENT> if new_profile["siteBlocking"] != current_profile["siteBlocking"]: <NEW_LINE> <INDENT> rebuild_site_blocking(uci, network_id, new_profile) <NEW_LINE> <DEDENT> return reload_dropbear, reload_firewall
helper function which will change from the current profile to the new profile for a specific network
625941c2925a0f43d2549e13
def _create_overlay(server_id, backing, bitmap): <NEW_LINE> <INDENT> filenames = _find_bitmap(backing, bitmap) <NEW_LINE> if not filenames: <NEW_LINE> <INDENT> raise se.BitmapDoesNotExist(bitmap=bitmap) <NEW_LINE> <DEDENT> overlay = transientdisk.create_disk( server_id, OVERLAY, backing=backing, backing_format="qcow2")["path"] <NEW_LINE> try: <NEW_LINE> <INDENT> qemuimg.bitmap_add(overlay, bitmap).run() <NEW_LINE> for src_img in filenames: <NEW_LINE> <INDENT> qemuimg.bitmap_merge( src_img, bitmap, "qcow2", overlay, bitmap).run() <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> transientdisk.remove_disk(server_id, OVERLAY) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> log.exception("Error removing overlay: %s", overlay) <NEW_LINE> <DEDENT> raise <NEW_LINE> <DEDENT> return overlay
To export bitmaps from entire chain, we need to create an overlay, and merge all bitmaps from the chain into the overlay.
625941c2d58c6744b4257bfe
def test_is_suppressed(self): <NEW_LINE> <INDENT> self.assertFalse(SuppressorPipeLine().is_suppressed(incident=self.incident))
Expect false if incident is not suppressed :return:
625941c2c432627299f04be2
def parse_column(line): <NEW_LINE> <INDENT> line = line.rstrip(',') <NEW_LINE> words = line.split() <NEW_LINE> if len(words) < 2: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> column = words[0] <NEW_LINE> col_type = words[1] <NEW_LINE> nullable = "NOT NULL" not in line <NEW_LINE> column = dict(name=column, type=col_type, nullable=nullable) <NEW_LINE> try: <NEW_LINE> <INDENT> idx = words.index('DEFAULT') <NEW_LINE> column['default'] = words[idx + 1] <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return column
Try to parse column definition. Parameters ---------- line : str Line with column definition. Returns ------- None if line is not a column definition, otherwise returns a dict with column description.
625941c2e5267d203edcdc3d
def distance_matrix(sample_list: List[np.ndarray]) -> np.ndarray: <NEW_LINE> <INDENT> distance_matrix = np.nan * np.ones(shape=(len(sample_list), len(sample_list))) <NEW_LINE> for i in range(0, len(sample_list)): <NEW_LINE> <INDENT> for j in range(0, len(sample_list)): <NEW_LINE> <INDENT> distance_matrix[i, j] = compute_pair_distance( sample_list[i], sample_list[j] ) <NEW_LINE> <DEDENT> <DEDENT> return distance_matrix
Compute symmetric matrix of pair distances for a list of samples. Parameters ---------- sample_list Set of samples. Returns ------- distance_matrix Symmatric matrix of pair distances.
625941c2097d151d1a222df9
def WriteRSAPrivateKey(filepath, key): <NEW_LINE> <INDENT> with open(filepath, "wb") as key_file: <NEW_LINE> <INDENT> key_file.write(key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() ))
Writes a given private RSA key to a PEM file :param filepath: :param key:
625941c230c21e258bdfa43a
def numSubarrayProductLessThanK(self, nums, k): <NEW_LINE> <INDENT> length = len(nums) <NEW_LINE> res = [] <NEW_LINE> for i in range(length): <NEW_LINE> <INDENT> self.search(i, length, res, nums, k) <NEW_LINE> <DEDENT> return len(res)
:type nums: List[int] :type k: int :rtype: int
625941c28e05c05ec3eea311
@pytest.mark.slowtest <NEW_LINE> @testing.requires_testing_data <NEW_LINE> @requires_version('scipy', '0.11') <NEW_LINE> def test_add_source_space_distances(): <NEW_LINE> <INDENT> tempdir = _TempDir() <NEW_LINE> src = read_source_spaces(fname) <NEW_LINE> src_new = read_source_spaces(fname) <NEW_LINE> del src_new[0]['dist'] <NEW_LINE> del src_new[1]['dist'] <NEW_LINE> n_do = 19 <NEW_LINE> src_new[0]['vertno'] = src_new[0]['vertno'][:n_do].copy() <NEW_LINE> src_new[1]['vertno'] = src_new[1]['vertno'][:n_do].copy() <NEW_LINE> out_name = op.join(tempdir, 'temp-src.fif') <NEW_LINE> n_jobs = 2 <NEW_LINE> assert_true(n_do % n_jobs != 0) <NEW_LINE> add_source_space_distances(src_new, n_jobs=n_jobs) <NEW_LINE> write_source_spaces(out_name, src_new) <NEW_LINE> src_new = read_source_spaces(out_name) <NEW_LINE> for so, sn in zip(src, src_new): <NEW_LINE> <INDENT> v = so['vertno'][:n_do] <NEW_LINE> assert_array_equal(so['dist_limit'], np.array([-0.007], np.float32)) <NEW_LINE> assert_array_equal(sn['dist_limit'], np.array([np.inf], np.float32)) <NEW_LINE> do = so['dist'] <NEW_LINE> dn = sn['dist'] <NEW_LINE> ds = list() <NEW_LINE> for d in [do, dn]: <NEW_LINE> <INDENT> d.data[d.data > 0.007] = 0 <NEW_LINE> d = d[v][:, v] <NEW_LINE> d.eliminate_zeros() <NEW_LINE> ds.append(d) <NEW_LINE> <DEDENT> assert_true(np.sum(ds[0].data < 0.007) > 10) <NEW_LINE> d = ds[0] - ds[1] <NEW_LINE> assert_allclose(np.zeros_like(d.data), d.data, rtol=0, atol=1e-9)
Test adding distances to source space.
625941c244b2445a33932035
def GetClickForce(devicename): <NEW_LINE> <INDENT> return xswGet(devicename, "ClickForce")
Get the ClickForce of a device using xsetwacom. Values are in the range 1 - 21.
625941c28e7ae83300e4af6a
def numDistinct(self, S, T): <NEW_LINE> <INDENT> len_s = len(S) <NEW_LINE> len_t = len(T) <NEW_LINE> dp = [[-1 for _ in xrange(len_s+1)] for _ in xrange(len_t+1)] <NEW_LINE> for col in xrange(len_s+1): <NEW_LINE> <INDENT> dp[0][col] = 1 <NEW_LINE> <DEDENT> for row in xrange(1, len_t+1): <NEW_LINE> <INDENT> dp[row][0] = 0 <NEW_LINE> <DEDENT> for row in xrange(1, len_t+1): <NEW_LINE> <INDENT> for col in xrange(1, len_s+1): <NEW_LINE> <INDENT> if S[col-1]==T[row-1]: <NEW_LINE> <INDENT> dp[row][col] = dp[row][col-1]+dp[row-1][col-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dp[row][col] = dp[row][col-1] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return dp[-1][-1]
Algorithm: dp, sub-sequence and matching Let W(i, j) stand for the number of subsequences of S(0, i) in T(0, j). If S.charAt(i) == T.charAt(j), W(i, j) = W(i-1, j-1) + W(i-1,j); Otherwise, W(i, j) = W(i-1,j). reference: http://www.programcreek.com/2013/01/leetcode-distinct-subsequences-total-java/ - r a b b b i t - 1 1 1 1 1 1 1 1 r 0 1 1 1 1 1 1 1 a 0 0 1 1 1 1 1 1 b 0 0 0 1 2 3 3 3 b 0 0 0 0 1 3 3 3 i 0 0 0 0 0 0 3 3 t 0 0 0 0 0 0 0 3 Thought: (in this case, S as the vertical line, T as the horizontal line f[i][j] is the number of distant subsequences of T[:j] in S[:i] f[i][j] is at least f[i-1][j] if S[i]==T[j]: transit from f[i-1][j-1] (if you delete both S[i] and T[j]) f[i][j] += f[i-1][j-1] :param S: string :param T: string :return: integer
625941c263b5f9789fde7083
def affine_forward(x, w, b): <NEW_LINE> <INDENT> out = None <NEW_LINE> number_of_images = x.shape[0] <NEW_LINE> reshaped_vector = x.reshape(number_of_images, -1) <NEW_LINE> out = reshaped_vector.dot(w) + b <NEW_LINE> cache = (x, w, b) <NEW_LINE> return out, cache
Computes the forward pass for an affine (fully-connected) layer. The input x has shape (N, d_1, ..., d_k) and contains a minibatch of N examples, where each example x[i] has shape (d_1, ..., d_k). For example, batch of 500 RGB CIFAR-10 images would have shape (500, 32, 32, 3). We will reshape each input into a vector of dimension D = d_1 * ... * d_k, and then transform it to an output vector of dimension M. Inputs: - x: A numpy array containing input data, of shape (N, d_1, ..., d_k) - w: A numpy array of weights, of shape (D, M) - b: A numpy array of biases, of shape (M,) Returns a tuple of: - out: output, of shape (N, M) - cache: (x, w, b)
625941c24f6381625f1149d9
def system_individual_writer(appname, appurl, target, fsize): <NEW_LINE> <INDENT> fnone = get_fnone(fsize) <NEW_LINE> if fnone: <NEW_LINE> <INDENT> target.write("{0} [{1}] {2}\n".format(appname, fsizer(0), appurl)) <NEW_LINE> <DEDENT> elif fsize > 0: <NEW_LINE> <INDENT> target.write("{0} [{1}] {2}\n".format(appname, fsizer(fsize), appurl))
Write individual OS/radio link to file. :param appname: App name. :type appname: str :param appurl: App URL. :type appurl: str :param target: File to write to. :type target: file :param fsize: Filesize. :type fsize: int
625941c2460517430c394128
def new_tag(): <NEW_LINE> <INDENT> if line[4] == '+': <NEW_LINE> <INDENT> strand= 'F' <NEW_LINE> <DEDENT> elif line[4] == '-': <NEW_LINE> <INDENT> strand= 'R' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sys.exit('Unrecognized character for strand: ' + strand) <NEW_LINE> <DEDENT> tss_tag= 'SSTSC_' + line[0] + '_' + strand + '_' + format(int(line[1]), '09d') <NEW_LINE> return(tss_tag)
Generate a new TSS tag like this: SSTSC_1_F_000000123
625941c2283ffb24f3c558a1
def main(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument("-d", "--device_os", type=str, default="cisco_ios", help='Device OS default=Cisco IOS', metavar="") <NEW_LINE> parser.add_argument("-D", "--domain", type=str, default="ne.pvhmc.org", help='Domain, default is=ne.pvhmc.org', metavar="") <NEW_LINE> parser.add_argument("-n", "--hostname", required=True, help='Hostname of device', metavar="") <NEW_LINE> parser.add_argument("-u", "--user", type=str, default="admin", help='user to connect with default=admin', metavar="") <NEW_LINE> args = parser.parse_args() <NEW_LINE> password = getpass.getpass() <NEW_LINE> hostname = args.hostname + "." + args.domain <NEW_LINE> cisco = {'device_type': args.device_os, 'ip': hostname, 'username': args.user, 'password': password, } <NEW_LINE> net_connect = ConnectHandler(**cisco) <NEW_LINE> raw_output = net_connect.send_command("show interfaces status") <NEW_LINE> match10m = re.compile(r'-10\s') <NEW_LINE> for line in raw_output.split("\n"): <NEW_LINE> <INDENT> mo = match10m.search(line) <NEW_LINE> if mo is not None: <NEW_LINE> <INDENT> newline = line.split() <NEW_LINE> print(f"{newline[0]}, {newline[3]}, {newline[4]}") <NEW_LINE> interface_mac = net_connect.send_command(f"show mac address-table interface {newline[0]}") <NEW_LINE> match_mac = re.compile(r"([0-9]|[a-f]){4}[/.]([0-9]|[a-f]){4}[/.]([0-9]|[a-f]){4}") <NEW_LINE> for i in interface_mac.split("\n"): <NEW_LINE> <INDENT> mo2 = match_mac.search(i) <NEW_LINE> if mo2 is not None: <NEW_LINE> <INDENT> print(mo2.group())
Run if as run as a program. Parsing
625941c2507cdc57c6306c74