code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def callback(self): <NEW_LINE> <INDENT> self.log.add_log("XiaolanInit: Detected awaken from snowboy", 1) <NEW_LINE> self.conversation()
回调函数 :return:
625941cc3cc13d1c6d3c746a
def register_user(update, context): <NEW_LINE> <INDENT> query = update.callback_query <NEW_LINE> user_id = query.from_user.id <NEW_LINE> first_name = query.from_user.first_name <NEW_LINE> user_name = query.from_user.username <NEW_LINE> name = query.data.lower() <NEW_LINE> db = readSQL.Database(DATABASE_PATH) <NEW_LINE>...
If user_id has not been registered, write to database. Then, continue to _start.
625941cc7b25080760e39549
def testMoveToBottomActionLayer(self): <NEW_LINE> <INDENT> view = QgsLayerTreeView() <NEW_LINE> view.setModel(self.model) <NEW_LINE> actions = QgsLayerTreeViewDefaultActions(view) <NEW_LINE> self.assertEqual(self.project.layerTreeRoot().layerOrder(), [self.layer, self.layer2, self.layer3]) <NEW_LINE> view.setCurrentLay...
Test move to bottom action on layer
625941ccff9c53063f47c2e4
def menage_clients(self, func): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> while self.connection_up: <NEW_LINE> <INDENT> client_con, addr = self.socket.accept() <NEW_LINE> client_ip = addr[0] <NEW_LINE> self.add_connection(client_ip, client_con) <NEW_LINE> start_new_thread(func, (client_ip, client_con)) <NEW_LINE> <D...
accepting connections of clients to the server and making new thread for each connection each thread run
625941cc187af65679ca520f
def listlib(self): <NEW_LINE> <INDENT> response = self._get_request(params = { "op": "listlib"}) <NEW_LINE> if response.mimetype != "text/plain": <NEW_LINE> <INDENT> raise UnexpectedResponseError(response) <NEW_LINE> <DEDENT> if not response.text: <NEW_LINE> <INDENT> raise UnexpectedResponseError(response) <NEW_LINE> <...
List XML libraries. Returns a sequence of library names.
625941ccbe383301e01b5576
def test_vl_spec_for_band_edge_values(): <NEW_LINE> <INDENT> band = api.Band() <NEW_LINE> try: <NEW_LINE> <INDENT> band.size = -1 <NEW_LINE> raise Exception('Should have thrown for illegal size min value.') <NEW_LINE> <DEDENT> except TraitError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> band...
Check edge values
625941cc851cf427c661a5ff
def cleanup ( command ) : <NEW_LINE> <INDENT> index = command.index('-log') + 1 <NEW_LINE> logfile_path = get_abspath(command[index]) <NEW_LINE> if ( (os.path.dirname(logfile_path) == tempfile.gettempdir()) and os.path.lexists(logfile_path) ) : <NEW_LINE> <INDENT> os.remove(logfile_path)
Remove the temporary files and directories created (if any) in gen_args() function. Arguments : command ( list ) FastTree's command line executed.
625941cc50485f2cf553ce8a
def extract_views_from_urlpatterns(urlpatterns, base='', namespace=None, ignored_modules=None): <NEW_LINE> <INDENT> ignored_modules = ignored_modules if ignored_modules else [] <NEW_LINE> views = [] <NEW_LINE> for p in urlpatterns: <NEW_LINE> <INDENT> if isinstance(p, URLPattern): <NEW_LINE> <INDENT> try: <NEW_LINE> <I...
Return a list of views from a list of urlpatterns. Each object in the returned list is a tuple: (view_func, regex, name)
625941cc091ae3566866704e
def inference(images, is_training=True): <NEW_LINE> <INDENT> with tf.variable_scope('squeezenet') as scope: <NEW_LINE> <INDENT> with tf.variable_scope('conv1') as scope: <NEW_LINE> <INDENT> kernel = tf.Variable(tf.truncated_normal(shape=[2, 2, 3, 96], stddev=5e-2), name='weights') <NEW_LINE> conv = tf.nn.conv2d(images,...
Build the CIFAR-10 model. Args: images: Images returned from distorted_inputs() or inputs(). Returns: Logits.
625941cca219f33f34628a5a
def __init__(__self__, *, irule: pulumi.Input[str], name: pulumi.Input[str]): <NEW_LINE> <INDENT> pulumi.set(__self__, "irule", irule) <NEW_LINE> pulumi.set(__self__, "name", name)
The set of arguments for constructing a IRule resource. :param pulumi.Input[str] irule: Body of the iRule :param pulumi.Input[str] name: Name of the iRule
625941cc30c21e258bdfa58e
def split(self): <NEW_LINE> <INDENT> if len(self) <= 1: <NEW_LINE> <INDENT> raise RecordIOTooSmallToSplitError() <NEW_LINE> <DEDENT> lo_records = [] <NEW_LINE> hi_records = [] <NEW_LINE> lo_size = 0 <NEW_LINE> hi_size = 0 <NEW_LINE> left = -1 <NEW_LINE> right = len(self) <NEW_LINE> while left + 1 != right: <NEW_LINE> <...
Split a RecordIORecords data into two even chunks. :return: lower_entries, higher_entries, middle_entry
625941cc2ae34c7f2600d221
def postcode_selector(default): <NEW_LINE> <INDENT> root_org = current.auth.root_org_name() <NEW_LINE> if root_org in (ARCS, IRCS, VNRC, YRCS): <NEW_LINE> <INDENT> default = False <NEW_LINE> <DEDENT> return default
NS-specific selection of whether to show Postcode
625941cc16aa5153ce362569
def find_report_file(name): <NEW_LINE> <INDENT> name = name.split('/') <NEW_LINE> app_label = name[0] <NEW_LINE> app = models.get_app(app_label) <NEW_LINE> return os.path.join(os.path.dirname(app.__file__), *name[1:])
Detect real report file name.
625941cc21bff66bcd684a44
def get_ip_list(url): <NEW_LINE> <INDENT> ip_list = [] <NEW_LINE> web_data = requests.get(url, headers=headers) <NEW_LINE> html = etree.HTML(web_data.text) <NEW_LINE> trs = html.xpath("//table[@id='ip_list']//tr[position()>1]") <NEW_LINE> for tr in trs: <NEW_LINE> <INDENT> ips = tr.xpath(".//td/text()") <NEW_LINE> ip_p...
获取代理网站上的所有ip并验证可用性, 返回代理池:格式:[{'http':'http://ip:port','https':'http://ip:port'}]
625941ccd7e4931a7ee9e00e
def list_cameras(): <NEW_LINE> <INDENT> with libctl.temp_open(): <NEW_LINE> <INDENT> camids=lib.Picam_GetAvailableCameraIDs() <NEW_LINE> return [_parse_camid(ci) for ci in camids]
List all cameras available through Picam interface
625941ccd6c5a1020814413b
def help(progname, args): <NEW_LINE> <INDENT> print("Available commands are:") <NEW_LINE> for (cmds, test, usages) in ro_command_usage: <NEW_LINE> <INDENT> for u in usages: <NEW_LINE> <INDENT> print( " %s %s" % (progname, u)) <NEW_LINE> <DEDENT> <DEDENT> helptext = ( [ "" , "Supported annotation type names are: " , "\...
Display ro command help. See also ro --help
625941cca934411ee3751784
def compute_error(y_true, y_pred): <NEW_LINE> <INDENT> size = len(y_true) <NEW_LINE> err = [y_true[i]!=y_pred[i] for i in range(n)] <NEW_LINE> return sum(err)/n <NEW_LINE> raise Exception('Function not yet implemented!')
Computes the average error between the true labels (y_true) and the predicted labels (y_pred) Returns the error = (1/n) * sum(y_true != y_pred)
625941ccc4546d3d9de72b24
def __init__(self, species, qty, order_type, tax): <NEW_LINE> <INDENT> if qty > 100: <NEW_LINE> <INDENT> raise TooManyMelonsError <NEW_LINE> <DEDENT> self.species = species <NEW_LINE> self.qty = qty <NEW_LINE> self.shipped = False <NEW_LINE> self.order_type = order_type <NEW_LINE> self.tax = tax
Initialize melon order attributes.
625941cce64d504609d74930
def __call__(self, seq, cksmethod="spcrc", stype="protein", **kwargs): <NEW_LINE> <INDENT> data = { "sequence": seq, "cksmethod": cksmethod, "stype": stype, } <NEW_LINE> data.update(kwargs) <NEW_LINE> return self._run(data)
Generate checksums for protein/nucleotide sequences. The default method generates a CRC64 checksum like it is used in UniProtKB. Args: seq (str): Sequence in FASTA format. cksmethod (str): Checksum method. Defaults to: CRC64-ISO (spcrc). There are others, including other flavours of CRC, which ...
625941cc91af0d3eaac9bb09
def __init__(self, positions, orientation=None, lineoffset=0, linelength=1, linewidth=None, color=None, linestyle='solid', antialiased=None, **kwargs ): <NEW_LINE> <INDENT> segment = (lineoffset + linelength / 2., lineoffset - linelength / 2.) <NEW_LINE> if positions is None or len(positions) == 0: <NEW_LINE> <INDENT> ...
Parameters ---------- positions : 1D array-like object Each value is an event. orientation : {None, 'horizontal', 'vertical'}, optional The orientation of the **collection** (the event bars are along the orthogonal direction). Defaults to 'horizontal' if not specified or None. lineoffset : scalar, opt...
625941cc5fdd1c0f98dc0324
def run(self) -> None: <NEW_LINE> <INDENT> self.clear() <NEW_LINE> self.player = Player(self.name, STARTING_MONEY) <NEW_LINE> self._generate_cities() <NEW_LINE> for n in range(1, self.days + 1): <NEW_LINE> <INDENT> self._calc_interest() <NEW_LINE> self.current_day_num = n <NEW_LINE> day = Day(self.current_city, self.pl...
Start and run game.
625941cccdde0d52a9e53124
def LoadFile(p): <NEW_LINE> <INDENT> data = np.array([0]) <NEW_LINE> try: <NEW_LINE> <INDENT> with open(p, 'rb') as file: <NEW_LINE> <INDENT> data = pickle.load(file) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> print('文件不存在!') <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> return data
读取文件 :param p: 数据集绝对路径 :return: 数据集
625941cca8ecb033257d31be
def test_send_seqno(self): <NEW_LINE> <INDENT> seqno = self.protocol._send_seqno <NEW_LINE> self.assertEquals(0, self.transport.message_sent_count) <NEW_LINE> self.transport.send_message(FIXMessage(source=[(8, 'FIX.4.2'), (35, 'A'), ])) <NEW_LINE> self.assertEquals(1, self.transport.message_sent_count) <NEW_LINE> self....
test send sequence numbering
625941cc63b5f9789fde71d6
def plotly_messages_freq(dates: list) -> None: <NEW_LINE> <INDENT> s = Counter(dates) <NEW_LINE> xCoor = list(s.keys()) <NEW_LINE> yCoor = list(s.values()) <NEW_LINE> stats = [go.Scatter(x=xCoor, y=yCoor)] <NEW_LINE> py.iplot(stats)
Построение графика с помощью Plot.ly :param date: список дат :param freq: число сообщений в соответствующую дату
625941cc1f5feb6acb0c4c41
def render_manage_geoserver_pages(request, html_file): <NEW_LINE> <INDENT> session_maker = app.get_persistent_store_database('main_db', as_sessionmaker=True) <NEW_LINE> session = session_maker() <NEW_LINE> geoservers = session.query(GeoServer) .order_by(GeoServer.name, GeoServer.url) ...
Generates managemement pages for GeoServers.
625941cc462c4b4f79d1d7c1
def SetInput2(self, *args): <NEW_LINE> <INDENT> return _itkSubtractImageFilterPython.itkSubtractImageFilterIUL3IUL3IUL3_Superclass_SetInput2(self, *args)
SetInput2(self, itkImageUL3 image2)
625941ccf548e778e58cd66e
def pre_connection_tests(self): <NEW_LINE> <INDENT> raise NotImplementedError
This is a helper function used by the cli tool cl_napalm_show_tech. Drivers can override this method to do some tests, show information, enable debugging, etc. before a connection with the device is attempted.
625941cc5510c4643540f4d5
def matching(tokens, *types, **fields): <NEW_LINE> <INDENT> return [t for t in tokens if t.match(*types, **fields)]
We have a recurring need to find all elements in a list that "match". This shorthand method helps
625941cc55399d3f055887a5
@charts_blueprint.route('/api_chart_data/<string:chart_json_template>/<int:year>/<int:month>/<int:day>/<int:hour>/<int:minute>/<int:hours>', methods=['GET']) <NEW_LINE> def api_chart_data(chart_json_template, year, month, day, hour, minute, hours): <NEW_LINE> <INDENT> template = eval(chart_json_template) <NEW_LINE> con...
returns a json chart with datas from : given date (y m d h m) to : given date + `hours` the template of json conf is selected with chart_json_template passed by url. this parameter shall be equal to one of the json variable defined at the begining of this file (eg: static_conf_minute)
625941cc4c3428357757c418
def exp_general(en, en_0=10.): <NEW_LINE> <INDENT> return 1. / en_0 * np.exp(-en / en_0)
Exponential number flux spectrum .. math:: \phi(E, E_0) = 1 / E_0 \cdot \exp\{-E / E_0\} Standard exponential distribution with :math:`\lambda` = 1 / ``en_0`` or :math:`\beta` = ``en_0``. normalized to unit number flux, i.e. :math:`\int_0^\infty \phi(E) \text{d}E = 1`. Parameters ---------- en: float or arra...
625941cc67a9b606de4a7faa
def load_reference(self, path, fmts, metadata, include=2, genes=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.reference = SeqIO.read(path, 'genbank') <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.log.fatal("Problem reading reference {}. Error: {}".format(path, e)) <NEW_LINE> <DEDENT> t...
Assume it's genbank.
625941cc23e79379d52ee655
def save_video(self, video, timestamp=None): <NEW_LINE> <INDENT> if timestamp is None: <NEW_LINE> <INDENT> timestamp = datetime.utcnow() <NEW_LINE> <DEDENT> return self._create_or_update_video(video, **{'saved': True, 'timestamp': timestamp})
Add video to user's saved queue. @type video: `Video` instance @type timestamp: Specify a timestamp - defaults to `datetime.utcnow()` @returns: Updated `UserVideo` association object >>> user = User.objects.create(username='birdman') >>> video = Video.objects.create(url='http://www.vimeo.com/24532073') >>> timestamp ...
625941cc85dfad0860c3af4c
def get_number_of_uncovered_cards(self): <NEW_LINE> <INDENT> num = 0 <NEW_LINE> for x in self: <NEW_LINE> <INDENT> if isinstance(x, cards.Card): <NEW_LINE> <INDENT> num = num + 1 <NEW_LINE> <DEDENT> <DEDENT> return num
Returns number of uncovered cards on the table.
625941ccb545ff76a8913f07
def parse(self): <NEW_LINE> <INDENT> self._validate_file_path(self._xml_file_path) <NEW_LINE> self._validate_file_path(self._xml_schema_path) <NEW_LINE> if self._is_valid_xml(): <NEW_LINE> <INDENT> self._parse_spatial_entities() <NEW_LINE> self._parse_spatial_measures() <NEW_LINE> return True <NEW_LINE> <DEDENT> else: ...
Validate the given xml file against the given schema Return true if the xml file is valid, and false otherwise.
625941cc3d592f4c4ed1d15f
def create_attention_mechanism(attention_option, num_units, memory, source_sequence_length, mode): <NEW_LINE> <INDENT> del mode <NEW_LINE> if attention_option == "luong": <NEW_LINE> <INDENT> attention_mechanism = tf.contrib.seq2seq.LuongAttention( num_units, memory, memory_sequence_length=source_sequence_length) <NEW_L...
Create attention mechanism based on the attention_option.
625941cc66673b3332b92182
@app.cli.command() <NEW_LINE> def update_tags(): <NEW_LINE> <INDENT> from app.controllers import set_tags <NEW_LINE> set_tags()
Updating shop product's tags only
625941cc8e71fb1e9831d89a
def t111140_x5(text15=_, z12=_, flag25=0, mode16=1): <NEW_LINE> <INDENT> assert t111140_x3() and CheckSpecificPersonTalkHasEnded(0) == 1 <NEW_LINE> if not flag25: <NEW_LINE> <INDENT> TalkToPlayer(text15, -1, -1, flag25, 0) <NEW_LINE> def WhilePaused(): <NEW_LINE> <INDENT> GiveSpEffectToPlayer(30700) <NEW_LINE> <DEDENT>...
State 0,7
625941ccd10714528d5ffdd4
def _format_83(f): <NEW_LINE> <INDENT> if -999.999 < f < 9999.999: <NEW_LINE> <INDENT> return '%8.3f' % f <NEW_LINE> <DEDENT> if -9999999 < f < 99999999: <NEW_LINE> <INDENT> return ('%8.3f' % f)[:8] <NEW_LINE> <DEDENT> raise ValueError('coordinate "%s" could not be represented ' 'in a width-8 field' % f)
Format a single float into a string of width 8, with ideally 3 decimal places of precision. If the number is a little too large, we can gracefully degrade the precision by lopping off some of the decimal places. If it's much too large, we throw a ValueError
625941cc66656f66f7cbc29b
def get_attendee_col(): <NEW_LINE> <INDENT> app_db = cosmosdb_client['app_db'] <NEW_LINE> attendee_col = app_db['attendees'] <NEW_LINE> return attendee_col
Retrieves the attendee collection from CosmosDB
625941cc3346ee7daa2b2e5c
def scrape(): <NEW_LINE> <INDENT> url = graburl() <NEW_LINE> mydoc = grabstring() <NEW_LINE> scraper = SwatScraper(mydoc) <NEW_LINE> scraper.findEvents() <NEW_LINE> return scraper.events
grabs events from string of parsed html from the page
625941cccc40096d61595a41
def get_label(s): <NEW_LINE> <INDENT> return s[1:]
>>> get_label('>Rosalind_4120') 'Rosalind_4120'
625941cce5267d203edcdd8e
def install_requirements(self): <NEW_LINE> <INDENT> proc = subprocess.Popen(['npm install'], cwd=self.app_name, shell=True) <NEW_LINE> return_code = proc.wait() <NEW_LINE> if return_code != 0: <NEW_LINE> <INDENT> self.FAIL('Could not run `npm install` for app {}.'.format(self.app_name)) <NEW_LINE> <DEDENT> self.install...
Install requirements for app to build
625941cc32920d7e50b282c1
def storage_format(self, reformat=False, timeout=30, verbose=False, force=False): <NEW_LINE> <INDENT> saved_timeout = self.timeout <NEW_LINE> self.timeout = timeout <NEW_LINE> self._get_result( ("storage", "format"), reformat=reformat, verbose=verbose, force=force) <NEW_LINE> self.timeout = saved_timeout <NEW_LINE> ret...
Get the result of the dmg storage format command. Args: reformat (bool): always reformat storage, could be destructive. This will create control-plane related metadata i.e. superblock file and reformat if the storage media is available and formattable. timeout: seconds after which the f...
625941cc0c0af96317bb82d9
def to_dict(self, columns): <NEW_LINE> <INDENT> ret = {} <NEW_LINE> for col in columns: <NEW_LINE> <INDENT> ret[col] = self.__dict__.get(col) or '' <NEW_LINE> <DEDENT> if self.parsed_content: <NEW_LINE> <INDENT> ret['title'] = self.parsed_content.get('title') <NEW_LINE> ret['author'] = self.parsed_content['author'].get...
returns a dict of the values listed in columns
625941cc596a897236089bb2
def _parse_config_file(self, cfile=None): <NEW_LINE> <INDENT> if cfile is None: <NEW_LINE> <INDENT> cfile = self._config_file <NEW_LINE> <DEDENT> ftype = get_config_type(cfile) <NEW_LINE> if cfile is not None: <NEW_LINE> <INDENT> if ftype == 'ini': <NEW_LINE> <INDENT> self._parsers[cfile] = configparser.ConfigParser() ...
return flat configuration settings from file(s)
625941cc76e4537e8c351764
def force_active(self,key,val=None,msg=None): <NEW_LINE> <INDENT> if msg == None: <NEW_LINE> <INDENT> msg == "Option forced to active for no given reason." <NEW_LINE> <DEDENT> if key not in self.ActiveOptions: <NEW_LINE> <INDENT> if val == None: <NEW_LINE> <INDENT> val = self.InactiveOptions[key] <NEW_LINE> <DEDENT> de...
Force an option to be active and set it to the provided value, regardless of the user input. There are no safeguards, so use carefully. key : The name of the option. val : The value that the option is being set to. msg : A warning that is printed out if the option is not activated.
625941cce64d504609d74931
def _verify_activation_data(self, user, activation_date, activation_data): <NEW_LINE> <INDENT> decrypted = decrypt_aes(activation_data) <NEW_LINE> user_id, data = decrypted.split('$') <NEW_LINE> new_data = "{0}]*[{1}]*[{2}".format(user.user_id, activation_date, user.user_password) <NEW_LINE> return verify_sh...
Generates activation/change password data.
625941cc5fcc89381b1e17b0
def add_user(session, new_user): <NEW_LINE> <INDENT> session.add(new_user) <NEW_LINE> session.commit() <NEW_LINE> return new_user.user_id
Creates and saves a new user to the database. :param new_user: new User record :param session: database session
625941cc8a43f66fc4b54156
def extract_path_info(environ_or_baseurl, path_or_url, charset='utf-8', errors='replace', collapse_http_schemes=True): <NEW_LINE> <INDENT> def _normalize_netloc(scheme, netloc): <NEW_LINE> <INDENT> parts = netloc.split(u'@', 1)[-1].split(u':', 1) <NEW_LINE> if len(parts) == 2: <NEW_LINE> <INDENT> netloc, port = parts <...
Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a WSGI environment. The URLs might also be IRIs. If the path info could not be determined, `None` is returned. Some examples: >>> extract_path_info(app.py, app.py) u'/...
625941cc7b180e01f3dc48ee
def deserialize(self, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> end = 0 <NEW_LINE> start = end <NEW_LINE> end += 16 <NEW_LINE> self.frequency = 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 :param str: byte array of serialized message, ``str``
625941cc796e427e537b06b7
def pre_save(self, public_key): <NEW_LINE> <INDENT> public_key.member = self._member_parent_instance()
Implement the hook method to inject the corresponding parent :class:`models.Member` instance to the newly created public key.
625941cc462c4b4f79d1d7c2
def hide_bkmark_popover(self, _widget=None, _event=None): <NEW_LINE> <INDENT> self.bkmark_popover.popdown()
Hide bookmark popup.
625941cc7b180e01f3dc48ef
@autojit_py3doc <NEW_LINE> def nested_result(): <NEW_LINE> <INDENT> result = [[a-1 for a in range(b)] for b in range(4)] <NEW_LINE> return result
>>> nested_result() [[], [-1L], [-1L, 0L], [-1L, 0L, 1L]]
625941cccb5e8a47e48b7b9c
def _get_marvin_last_modified(self, book): <NEW_LINE> <INDENT> timestamp = float(book.attrib['lastmodified']) <NEW_LINE> m_last_modified = datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz.tzutc()) <NEW_LINE> m_last_modified = m_last_modified.astimezone(tz.tzlocal()) <NEW_LINE> self._log_location(m_last_modified) ...
Return a datetime object in local tz
625941ccb5575c28eb68e0f2
def run(self, input_data=None, stdout=None, stderr=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.process = subprocess.Popen( self._cmd, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr ) <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> if e.errno == errno.ENOENT: <NEW_LINE> <INDENT> raise FFEx...
Execute FFmpeg command line. ``input_data`` can contain input for FFmpeg in case ``pipe`` protocol is used for input. ``stdout`` and ``stderr`` specify where to redirect the ``stdout`` and ``stderr`` of the process. By default no redirection is done, which means all output goes to running shell (this mode should norma...
625941cc0a366e3fb873e90b
def test_define_meta_es_doc(self): <NEW_LINE> <INDENT> output = define_meta_es_doc(self.valuedict, self.meta_info) <NEW_LINE> self.assertEquals(output['account_holder'], 'Mister Grouse') <NEW_LINE> self.assertEquals(output['account_number'], "123456789") <NEW_LINE> self.assertEquals(output['kind'], 'customsearch#search...
Walk through data structure
625941cc63b5f9789fde71d7
def hasValues(self): <NEW_LINE> <INDENT> return _libsedml.SedVectorRange_hasValues(self)
hasValues(SedVectorRange self) -> bool
625941cca4f1c619b28b012b
def dms_ddd(a, sep=" "): <NEW_LINE> <INDENT> d, m, s = [float(i) for i in a.split(sep)] <NEW_LINE> sign = [-1, 1][d > 0] <NEW_LINE> dd = sign*(abs(d) + (m + s/60.)/60.) <NEW_LINE> return dd
convert degree, minute, decimal second string to decimal degrees : a - degree, minute, decimal second string : sep - usually a space, but check : Useage - dms_ddd(!SourceField!, sep=" ") : python parser, sourcefield is the input string field, destination : field is type double
625941cc4e696a04525c953d
def get_compounds_by_chemblId_form(self, query, frmt="json"): <NEW_LINE> <INDENT> res = self._process(query, frmt, "compounds/%s/form") <NEW_LINE> return self._postprocess(res, 'forms')
:param query: valid chembl identifier (or list) :param str frmt: json or xml (Default to json) See :meth:`get_compounds_by_chemblId` for full doc. :: >>> s.get_compounds_by_chemblId_form("CHEMBL2") [{u'chemblId': u'CHEMBL1347191', u'parent': False}, {u'chemlId': u'CHEMBL1558', u'parent': False}, {u...
625941ccbe7bc26dc91cd6f2
def test_tiered_rate_with_gaps(self): <NEW_LINE> <INDENT> self.ocp_data['rates'][0]['tiered_rates'] = [ { 'unit': 'USD', 'value': 0.22, 'usage': { 'usage_start': None, 'usage_end': 7.0 } }, { 'unit': 'USD', 'value': 0.26, 'usage_start': 10.0, 'usage_end': None } ] <NEW_LINE> with tenant_context(self.tenant): <NEW_LINE>...
Test creating a tiered rate with a gap between the tiers.
625941cc004d5f362079a425
def mimetype_for_file(fname, strict=False): <NEW_LINE> <INDENT> mtype, enc = mimetypes.guess_type(fname) <NEW_LINE> if mtype is None and not strict: <NEW_LINE> <INDENT> mtype, enc = mimetypes.guess_type('foo.bin') <NEW_LINE> <DEDENT> return mtype
Return the mimetype for a given file. If one is not found, defaults to 'application/octect-stream'
625941ccd268445f265b4f60
def getDerivatives( fmu_me ): <NEW_LINE> <INDENT> if not isinstance( fmu_me, FMUModelExchangeV1 ) and not isinstance( fmu_me, FMUModelExchangeV2 ): <NEW_LINE> <INDENT> raise TypeError( 'this function is only supported for FMUModelExchangeV1 and FMUModelExchangeV2' ) <NEW_LINE> <DEDENT> n = fmu_me.nStates() <NEW_LINE> d...
Extract the derivatoves matrix (as numpy.array) from an FMU for ModelExchange (FMI v1.0 or FMI 2.0).
625941cc50812a4eaa59c414
def getSimilarity(data, binary=True): <NEW_LINE> <INDENT> for arr in data: <NEW_LINE> <INDENT> up = arr*data <NEW_LINE> if binary: <NEW_LINE> <INDENT> down = arr + data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> down = arr**2 + data**2 <NEW_LINE> <DEDENT> value = up.sum(axis=1)/(down.sum(axis=1)-up.sum(axis=1)) <NEW...
Parameters ---------- data : numpy.ndarray fingrtprint or descriptor in 2d-arrry. Yields ------ value : numpy.ndarray the similarity between a molecule and the lib.
625941ccbf627c535bc132c1
def spin(program_list, amount): <NEW_LINE> <INDENT> return program_list[-amount:] + program_list[:len(program_list) - amount]
Rotate program list by amount from the end of the list e.g. abcde amount 3 gives cdeab.
625941cc5f7d997b87174b89
def macro_usa_trade_balance(): <NEW_LINE> <INDENT> t = time.time() <NEW_LINE> res = requests.get( f"https://cdn.jin10.com/dc/reports/dc_usa_trade_balance_all.js?v={str(int(round(t * 1000))), str(int(round(t * 1000)) + 90)}" ) <NEW_LINE> json_data = json.loads(res.text[res.text.find("{"): res.text.rfind("}") + 1]) <NEW_...
美国贸易帐报告, 数据区间从19700101-至今 https://datacenter.jin10.com/reportType/dc_usa_trade_balance https://cdn.jin10.com/dc/reports/dc_usa_trade_balance_all.js?v=1578742911 :return: 美国贸易帐报告-今值(亿美元) :rtype: pandas.Series
625941cc0a366e3fb873e90c
def urlfetch_to_gcs_stub(url, payload, method, headers, request, response, follow_redirects=False, deadline=None, validate_certificate=None, http_proxy=None): <NEW_LINE> <INDENT> headers_map = dict( (header.key().lower(), header.value()) for header in headers) <NEW_LINE> result = gcs_dispatcher.dispatch(method, headers...
Forwards Google Cloud Storage `urlfetch` requests to gcs_dispatcher.
625941ccb7558d58953c5006
def __init__(self, query_dims, key_dims, num_attn = 1, activation = "leakyrelu", f_activation = "sigmoid", layernorm = False, use_post_mat = False): <NEW_LINE> <INDENT> super(IntersectConcatAttention, self).__init__() <NEW_LINE> self.atten_vecs = {} <NEW_LINE> self.query_dims = query_dims <NEW_LINE> self.key_dims = key...
The attention method used by Graph Attention network (LeakyReLU) Args: query_dims: a dict() mapping: node type --> pre-computed variable embeddings dimention key_dims: a dict() mapping: node type --> embeddings dimention computed from different query path for the same variables num_attn: number of attention...
625941cc07d97122c417897d
def split_dataset(self, x_df, y_df, frac): <NEW_LINE> <INDENT> whole_count, x_col = x_df.shape <NEW_LINE> whole_dt = pd.merge(x_df, y_df, left_index=True, right_index=True) <NEW_LINE> shuffle_dt = shuffle(whole_dt) <NEW_LINE> shuffle_dt = shuffle_dt.reset_index(drop=True) <NEW_LINE> split_line = int(whole_count * frac)...
input x,y are dataframes, output are dataframes either, frac the percent of the training dataset, between 0 and 1, 0.8 for example :param x: x is a pd.DataFrame :param y: y is a pd.DataFrame :param frac: 训练样本的划分比例,介于0-1之间 :return:
625941cc6fb2d068a760f18f
def get_output(self, *command): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> out = check_output([ self.git, '-C', self.root ] + list(command)) <NEW_LINE> <DEDENT> except CalledProcessError: <NEW_LINE> <INDENT> raise GitError() <NEW_LINE> <DEDENT> return out
Run a git command and return output Args: *command (array of str): List of parameters to pass to git executable. Returns: str: The output of the git command Raises: GitError
625941cc5f7d997b87174b8a
def test_sql_statements(self): <NEW_LINE> <INDENT> filename = 'sql_statements{}.py' <NEW_LINE> if sys.version_info <= (3, 6): <NEW_LINE> <INDENT> filename = filename.format('') <NEW_LINE> expect = { 'SEVERITY': {'UNDEFINED': 0, 'LOW': 0, 'MEDIUM': 14, 'HIGH': 0}, 'CONFIDENCE': {'UNDEFINED': 0, 'LOW': 8, 'MEDIUM': 6, 'H...
Test for SQL injection through string building.
625941ccd58c6744b4257d52
def t21(self): <NEW_LINE> <INDENT> sr = self.get_sr() <NEW_LINE> data = {'xzqh': '= 4103'} <NEW_LINE> result = sr.get(data=data, return_instance=True) <NEW_LINE> self.print_result(result)
行查询,获取实例 :return:
625941cc956e5f7376d70f60
def encode(self,text): <NEW_LINE> <INDENT> out=""; <NEW_LINE> for c in text: <NEW_LINE> <INDENT> word=self.characters[c]+self.delim; <NEW_LINE> out=out+word; <NEW_LINE> <DEDENT> return out;
Encodes a string to a string of bits.
625941cc30c21e258bdfa58f
def unregister(self): <NEW_LINE> <INDENT> self.node_handle.destroy_publisher(self.publisher) <NEW_LINE> self.clients.clear()
Unregisters the publisher and clears the clients
625941ccf8510a7c17cf97ef
def seckill_by_proc_pool(self, work_count=5): <NEW_LINE> <INDENT> with ProcessPoolExecutor(work_count) as pool: <NEW_LINE> <INDENT> for i in range(work_count): <NEW_LINE> <INDENT> pool.submit(self.seckill)
多进程进行抢购 work_count:进程数量
625941cc236d856c2ad448cc
def categorize(df, columns=None, index=None, split_every=None, **kwargs): <NEW_LINE> <INDENT> meta = df._meta <NEW_LINE> if columns is None: <NEW_LINE> <INDENT> columns = list(meta.select_dtypes(['object', 'category']).columns) <NEW_LINE> <DEDENT> elif is_scalar(columns): <NEW_LINE> <INDENT> columns = [columns] <NEW_LI...
Convert columns of the DataFrame to category dtype. Parameters ---------- columns : list, optional A list of column names to convert to categoricals. By default any column with an object dtype is converted to a categorical, and any unknown categoricals are made known. index : bool, optional Whether to ...
625941cc3c8af77a43ae3892
def unregister(self): <NEW_LINE> <INDENT> if self.registered: <NEW_LINE> <INDENT> if ( datetime.datetime.now() - datetime.timedelta(seconds=self.unregister_timeout) > self.lastmsg ): <NEW_LINE> <INDENT> self.registered = False <NEW_LINE> if self.parent: <NEW_LINE> <INDENT> self.parent.unregister(self)
Proxy method to unregister the device with the parent.
625941cc21a7993f00bc7de1
def sql_df(self, query): <NEW_LINE> <INDENT> con = self.create_connection() <NEW_LINE> df = pd.read_sql(query, con) <NEW_LINE> return df
A sql injection vulnerability, except I don't care :param query: :return:
625941cc0a50d4780f666f84
def fail_on_shallow(wd): <NEW_LINE> <INDENT> if wd.is_shallow(): <NEW_LINE> <INDENT> raise ValueError( '%r is shallow, please correct with ' '"git fetch --unshallow"' % wd.path)
experimental, may change at any time
625941cc1d351010ab855c0e
def pbar_updater (block_num, block_size, total_size): <NEW_LINE> <INDENT> if pbar.total != total_size: <NEW_LINE> <INDENT> pbar.total = total_size <NEW_LINE> <DEDENT> pbar.update(block_num * block_size - pbar.n) <NEW_LINE> return
ref: https://github.com/tqdm/tqdm#hooks-and-callbacks
625941cc8e05c05ec3eea467
def timeSliceTier(self, tiername, start, end=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> start = float(start) <NEW_LINE> if end: <NEW_LINE> <INDENT> end = float(end) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> if end: <NEW_LINE> <INDENT> sys.exit(SCRIPT + "Cannot convert " + str(start) + " and " +...
Finds the Interval object(s) at the specified time (interval)
625941cccad5886f8bd270cb
def test_show_white_value_if_only_command_topic(self): <NEW_LINE> <INDENT> config = {light.DOMAIN: { 'platform': 'mqtt', 'name': 'test', 'white_value_command_topic': 'test_light_rgb/white_value/set', 'command_topic': 'test_light_rgb/set', 'state_topic': 'test_light_rgb/status', }} <NEW_LINE> with assert_setup_component...
Test the white_value if only a command topic is present.
625941ccb830903b967e99fd
def pending_for_user(self, user, ref=None): <NEW_LINE> <INDENT> qs = self.pending(ref).filter(program_usage__klass__students=user) <NEW_LINE> late_klasses = user.took_klasses.late_payment() <NEW_LINE> qs = qs.exclude(program_usage__klass__in=late_klasses) <NEW_LINE> qs = qs.extra( where=['select not count(is_done) fro...
Tells what is the schedules not done or not started for the given user.
625941cc50485f2cf553ce8c
def closestFood(blitList, nextPos, currentCell): <NEW_LINE> <INDENT> fringe = [(nextPos, 0)] <NEW_LINE> expanded = set() <NEW_LINE> while fringe: <NEW_LINE> <INDENT> nextPos, dist = fringe.pop(0) <NEW_LINE> if nextPos in expanded: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> expanded.add(nextPos) <NEW_LINE> if next...
closestFood -- this is similar to the function that we have worked on in the search project; here its all in one place
625941ccad47b63b2c50a071
def clearFields(self): <NEW_LINE> <INDENT> self.dlg.leMetadata.clear() <NEW_LINE> self.dlg.teParam.clear() <NEW_LINE> self.dlg.leOutput.clear()
Clears fields
625941cc23e79379d52ee656
def validate(user): <NEW_LINE> <INDENT> if not user: <NEW_LINE> <INDENT> raise ValueError("User cannot be empty.") <NEW_LINE> <DEDENT> if not user.name: <NEW_LINE> <INDENT> raise ValueError("Missing user name.") <NEW_LINE> <DEDENT> enrollment = user.enrollment <NEW_LINE> if not enrollment: <NEW_LINE> <INDENT> raise Val...
Check the user. Args: user: A user object Raises: ValueError: When user property is invalid
625941cc5e10d32532c5f019
def countNodes(self, root): <NEW_LINE> <INDENT> dl = [] <NEW_LINE> count = 0 <NEW_LINE> if root == None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dl.append(root) <NEW_LINE> <DEDENT> while dl: <NEW_LINE> <INDENT> curr = dl.pop() <NEW_LINE> count += 1 <NEW_LINE> if curr.left: <NEW_LINE> ...
:type root: TreeNode :rtype: int
625941cca8ecb033257d31bf
def current_line(self): <NEW_LINE> <INDENT> if self.is_optimized_out(): <NEW_LINE> <INDENT> return FRAME_INFO_OPTIMIZED_OUT <NEW_LINE> <DEDENT> lineno = self.current_line_num() <NEW_LINE> if lineno is None: <NEW_LINE> <INDENT> return '(failed to get frame line number)' <NEW_LINE> <DEDENT> filename = self.filename() <NE...
Get the text of the current source line as a string, with a trailing newline character
625941cc091ae35668667050
def __init__(self, n, conc=1, name=''): <NEW_LINE> <INDENT> if n < 2: <NEW_LINE> <INDENT> raise ValueError('A Dirichlet distribution with ' 'n<2 makes no sense') <NEW_LINE> <DEDENT> self.n = n <NEW_LINE> self.params = np.ones(n, dtype=np.float) * conc <NEW_LINE> self.name = name
Initializes a Dirichlet distribution. n: number of dimensions conc: concentration parameter (smaller yields more concentration) name: string name
625941cc24f1403a92600c59
def plot_train_data(iterations, mb_losses, loc_losses, conf_losses): <NEW_LINE> <INDENT> fig = plt.figure() <NEW_LINE> plt.title('Training Process') <NEW_LINE> plt.xlabel('Iterations') <NEW_LINE> plt.ylabel('Value') <NEW_LINE> l1, = plt.plot(iterations, mb_losses, c='green') <NEW_LINE> l2, = plt.plot(iterations, loc_lo...
Plot a graph with the training trend Parameters ---------- iterations: array with actual iterations for each iteration mb_losses: array of mulibox losses loc_losses: array of localization losses conf_losses: array of confidence losses
625941ccbd1bec0571d90722
def get_interface_detail_output_interface_if_state(self, **kwargs): <NEW_LINE> <INDENT> config = ET.Element("config") <NEW_LINE> get_interface_detail = ET.Element("get_interface_detail") <NEW_LINE> config = get_interface_detail <NEW_LINE> if kwargs.pop('delete_get_interface_detail', False) is True: <NEW_LINE> <INDENT> ...
Auto Generated Code
625941ccd7e4931a7ee9e010
def _get_passive(self): <NEW_LINE> <INDENT> return self.__passive
Getter method for passive, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/interfaces/interface/levels/level/state/passive (boolean) YANG Description: ISIS passive interface admin enable/disable function.
625941cc2ae34c7f2600d224
def ll2xy(self, lon, lat): <NEW_LINE> <INDENT> lon = np.asarray(lon) <NEW_LINE> lat = np.asarray(lat) <NEW_LINE> return self.getproj()(lon, lat)
Converts lon/lat to x distances (no false easting/northing) Parameters ---------- lon : scalar or iterable longitudes in decimal degrees lat : scalar or iterable latitudes in decimal degrees Returns ------- x, y : tuple of arrays coordinates in map projection (meters or radians)
625941cc76d4e153a657ec23
def __init__(self): <NEW_LINE> <INDENT> SingletonDefinition.__init__(self, Type.SECRET)
Initialize SecretDefinition
625941cc8c0ade5d55d3eaad
def surviving_creature_names(self, chits): <NEW_LINE> <INDENT> return [chit.creature.name for chit in chits if not chit.dead]
Return a list of creature names for the survivors.
625941cc435de62698dfdd3f
def default_db_entities(self): <NEW_LINE> <INDENT> config_entity = self.config_entity <NEW_LINE> parent_region_fixture = self.parent_fixture <NEW_LINE> default_db_entities = parent_region_fixture.default_db_entities() <NEW_LINE> remote_db_entity_setups = map( lambda remote_setup: update_or_create_db_entity(config_entit...
Region specific SACOG db_entity_setups :param default_dict: :return:
625941ccac7a0e7691ed41bf
def prettify_seconds(seconds): <NEW_LINE> <INDENT> if seconds < 0: <NEW_LINE> <INDENT> raise ValueError("negative input not allowed") <NEW_LINE> <DEDENT> signs = {"s": {"singular": "second", "plural": "seconds", }, "h": {"singular": "hour", "plural": "hours"}, "min": {"singular": "minute", "plural": "minutes"}, "d": {"...
Prettifies seconds. Takes number of seconds (int) as input and returns a prettified string. Example: >>> prettify_seconds(342543) '3 days, 23 hours, 9 minutes and 3 seconds'
625941ccb830903b967e99fe
def multi_restart(self, request): <NEW_LINE> <INDENT> id_list = request.POST.getlist('pk') <NEW_LINE> kubernetes_restart_resource_controller.delay(pk_list=id_list)
批量执行重启控制器 :param request: :return:
625941cc31939e2706e4cf5d
def get_tile_properties_by_layer(self, layer): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> assert (int(layer) >= 0) <NEW_LINE> layer = int(layer) <NEW_LINE> <DEDENT> except (TypeError, AssertionError): <NEW_LINE> <INDENT> msg = "Layer must be a positive integer. Got {0} instead." <NEW_LINE> logger.debug(msg.format(ty...
Get the tile properties of each GID in layer :param layer: layer number :rtype: iterator of (gid, properties) tuples
625941cc0383005118ecf6d5
def Destroy(self): <NEW_LINE> <INDENT> self.lock.acquire() <NEW_LINE> self.freeResources = [] <NEW_LINE> self.maxResources = 0 <NEW_LINE> self.lock.release() <NEW_LINE> while self.busyResources: <NEW_LINE> <INDENT> self.poolEvent.Wait()
Destroy the resource pool, this blocks until all resources are returned to the pool for destruction.
625941cc30dc7b7665901a59
def reverse(self, n): <NEW_LINE> <INDENT> if n == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> neg = 1 <NEW_LINE> if n < 0: <NEW_LINE> <INDENT> neg, n = -1, -n <NEW_LINE> <DEDENT> reverse = 0 <NEW_LINE> while n > 0: <NEW_LINE> <INDENT> reverse = reverse * 10 + n % 10 <NEW_LINE> n = n / 10 <NEW_LINE> <DEDENT> rev...
:type x: int :rtype: int
625941cc627d3e7fe0d68f42