code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def unserialize_all( base_path: str, ) -> List[GluonPredictor]: <NEW_LINE> <INDENT> return [ GluonPredictor.deserialize(Path(base_dir)) for base_dir in glob(base_path + "-fold*") ]
unserialize all predictors from directory Arguments: base_path {str} -- base dir name from which to load models Returns: List[GluonPredictor] -- list of unserialized GluonPredictor objects
625941e9cc0a2c11143dd341
def testDataDirectiveFromQueue(self): <NEW_LINE> <INDENT> rerecoArgs["ConfigCacheID"] = createConfig(rerecoArgs["CouchDBName"]) <NEW_LINE> factory = ReRecoWorkloadFactory() <NEW_LINE> Tier1ReRecoWorkload = factory.factoryWorkloadConstruction('ReRecoWorkload', rerecoArgs) <NEW_LINE> inputDataset = getFirstTask(Tier1ReRe...
Test data directive from queue
625941e9442bda511e8be8c0
def fruit1(): <NEW_LINE> <INDENT> fruit = ["Apples", "Pears", "Oranges", "Peaches"] <NEW_LINE> print(fruit) <NEW_LINE> response = input("Input a fruit > ") <NEW_LINE> fruit.append(response) <NEW_LINE> print(fruit) <NEW_LINE> numres = int(input("Input a number > ")) <NEW_LINE> while numres < 1 or numres > 5: <NEW_LINE> ...
List four fruits, includes a user input to list, and removes fruit that start with the letter "P"
625941e94d74a7450ccd4674
def ensure2DImage(data): <NEW_LINE> <INDENT> d = data.view() <NEW_LINE> if len(d.shape) < 2: <NEW_LINE> <INDENT> d.shape = (1,) * (2 - len(d.shape)) + d.shape <NEW_LINE> <DEDENT> elif len(d.shape) > 2: <NEW_LINE> <INDENT> d.shape = d.shape[-2:] <NEW_LINE> <DEDENT> return d
Reshape data to make sure it's 2D by trimming all the low dimensions (=1). Odemis' convention is to have data organized as CTZYX. If CTZ=111, then it's a 2D image, but it has too many dimensions for functions which want only 2D. data (DataArray): the data to reshape return DataArray: view to the same data but with 2D s...
625941e9d486a94d0b98e5f6
def entity_seq_counter_get(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.entity_seq_counter_get_with_http_info(**kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.entity_seq_counter_get_with_http_info...
EntitySeqCounter_GET # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.entity_seq_counter_get(async_req=True) >>> result = thread.get() :param async_req bool :param str fields: :param str ordering: ...
625941e9fff4ab517eb2f8ee
def isSubsequence(self, s, t): <NEW_LINE> <INDENT> if s == t: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif len(s) == len(t) or (not t): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> pT, pS = 0, 0 <NEW_LINE> while pT<len(t) and pS<len(s) : <NEW_LINE> <INDENT> if s[pS] == t[pT]: <NEW_LINE> <INDENT> pS+...
:type s: str :type t: str :rtype: bool
625941e924f1403a92601011
def feature_breadown(df, feat, title, save_loc): <NEW_LINE> <INDENT> grouped_df = df.groupby([feat])['ID'].count().reset_index() <NEW_LINE> plt.style.use('ggplot') <NEW_LINE> fig, ax = plt.subplots(1, figsize=(10, 8)) <NEW_LINE> x = grouped_df.iloc[:, 0] <NEW_LINE> y = grouped_df.iloc[:,1] <NEW_LINE> ax.bar(x, y, color...
Plot Breakdown of Accidents depending on specific feature to input Args: df - dataframe feat - feature to input title - graph title save_as - name to save image under
625941e966656f66f7cbc65c
def test_tree_solve_route_responds_with_json(testapp): <NEW_LINE> <INDENT> import json <NEW_LINE> response = testapp.get("/api/solve/tree?state=[[1,2,3],[4,5,6],[9,7,8]]") <NEW_LINE> assert json.loads(response.text) == response.json
Test that the tree solving route returns a JSON file.
625941e9bd1bec0571d90ade
def entry_for_one_func(nom, func): <NEW_LINE> <INDENT> args, varargs, varkw, defaults = inspect.getargspec(func) <NEW_LINE> argspec = inspect.formatargspec(args, varargs, varkw, defaults) <NEW_LINE> funcdoc_body_rst = docstring_to_body(dedent_docstring(func.__doc__)) <NEW_LINE> funcdoc_body_html = rst_to_html(funcdoc_b...
Generate a BUILD dictionary entry for a function nom: name like 'python_binary' func: function object
625941e9d164cc61757831fe
def extract_base_citation(words, reporter_index): <NEW_LINE> <INDENT> reporter = words[reporter_index] <NEW_LINE> if reporter == 'U. S.': <NEW_LINE> <INDENT> reporter = 'U.S.' <NEW_LINE> <DEDENT> if words[reporter_index - 1].isdigit(): <NEW_LINE> <INDENT> volume = int(words[reporter_index - 1]) <NEW_LINE> <DEDENT> else...
Given a list of words and the index of a federal reporter, look before and after for volume and page number. If found, construct and return a Citation object.
625941e9460517430c394627
def best_tags(topic_title, count): <NEW_LINE> <INDENT> tags_dict = defaultdict(int) <NEW_LINE> for i in tags_by_topic(topic_title): <NEW_LINE> <INDENT> tags_dict[i.tag] += 1 <NEW_LINE> <DEDENT> result = [(x, tags_dict[x]) for x in tags_dict] <NEW_LINE> result.sort(key=(lambda c: -c[1])) <NEW_LINE> return [i[0] for i in...
Популярные тэги :param topic_title: заголовок темы :param count: необходимое количество тэгов :return: несколько самых популярных тэгов темы
625941e907f4c71912b11933
def test_non_prioritary_document(self): <NEW_LINE> <INDENT> doc = DocumentFactory( revision={ 'reviewers': [self.user], 'leader': self.other_user, 'docclass': 1, 'received_date': datetime.date.today(), } ) <NEW_LINE> doc.latest_revision.start_review() <NEW_LINE> res = self.client.get(self.url) <NEW_LINE> self.assertNot...
User is not approver nor leader.
625941e916aa5153ce362927
def parse_ip_packet(ip): <NEW_LINE> <INDENT> sys.stdout.flush() <NEW_LINE> if isinstance(ip.data, dpkt.tcp.TCP) and len(ip.data.data): <NEW_LINE> <INDENT> parse_tcp_packet(ip)
Parses IP packet.
625941e9a79ad161976cc5f4
def multipart_upload(bucket, s3_key_name, tarball, mb_size, aws_access_key_id, aws_secret_access_key, use_rr=True): <NEW_LINE> <INDENT> cores = multiprocessing.cpu_count() <NEW_LINE> def split_file(in_file, mb_size, split_num=5): <NEW_LINE> <INDENT> prefix = os.path.join(os.path.dirname(in_file), "%sS3PART" % (os.path....
Upload large files using Amazon's multipart upload functionality.
625941e999cbb53fe6793094
def weighted_img(img, initial_img, a=0.8, b=1., c=0.): <NEW_LINE> <INDENT> return cv2.addWeighted(initial_img, a, img, b, c)
Takes the output image with hough lines as input The result image is computed as follows: initial_img * a + img * ß + ?
625941e9d58c6744b425810d
def update_bags(self, bags): <NEW_LINE> <INDENT> self.bags = bags <NEW_LINE> self.data = [flight for flight in self._data if flight.bags_allowed >= self.bags]
Constrain current self.data given bag concerns.
625941e963b5f9789fde7595
def test_decorated_results_callback(self): <NEW_LINE> <INDENT> future = decorated(1, 1) <NEW_LINE> future.add_done_callback(self.callback) <NEW_LINE> self.event.wait(timeout=1) <NEW_LINE> self.assertEqual(self.results, 2)
Process Spawn results are forwarded to the callback.
625941e9fb3f5b602dac3b47
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.id = None <NEW_LINE> self.type = None <NEW_LINE> self.curie = None <NEW_LINE> self.set = False <NEW_LINE> super().__init__(*args, **kwargs)
Initialize QNode.
625941e98e05c05ec3eea828
def result(self): <NEW_LINE> <INDENT> return (self.depth_max + 1, self.field_width_max)
Return the maximums we've computed
625941e950812a4eaa59c7cc
def test_version_match(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> installed_version = self.get_installed_version() <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> self.fail('Cannot import pkg_resources module. It is part of ' 'setuptools, which is a dependency of %s.' % package...
Check that project's package/module __version__ matches pkg_resources information.
625941e9cad5886f8bd27488
def convert_to_index( data, word_to_idx_dict ): <NEW_LINE> <INDENT> print( "Converting to one-hot..." ) <NEW_LINE> language_list = list( data.keys() ) <NEW_LINE> for language in language_list: <NEW_LINE> <INDENT> for i in range( len( data[language] ) ): <NEW_LINE> <INDENT> new_sentence = [] <NEW_LINE> for word in data[...
Convert word to index Args: data: a dictionary contains sentences of each language. Its structure is: {language A: [[word1, word2, ...], [...], ...], language B: ...}. word_to_idx_dict: a dictionary converts word to index. Its structure is: {language A: {word A: index A, word B...
625941e93c8af77a43ae3c55
def axe_set_size(w,h, ax=None): <NEW_LINE> <INDENT> if not ax: ax=plt.gca() <NEW_LINE> l = ax.figure.subplotpars.left <NEW_LINE> r = ax.figure.subplotpars.right <NEW_LINE> t = ax.figure.subplotpars.top <NEW_LINE> b = ax.figure.subplotpars.bottom <NEW_LINE> figw = float(w)/(r-l) <NEW_LINE> figh = float(h)/(t-b) <NEW_LIN...
w, h: width, height in inches
625941e9d99f1b3c44c67a35
def from_json_list(value, context): <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if isinstance(value, basestring): <NEW_LINE> <INDENT> parsed_value = json.loads(value) <NEW_LINE> if not isinstance(parsed_value, list): <NEW_LINE> <INDENT> return [value] ...
CKAN converted. Convert value from JSON format. String value is returned as single item list.
625941e9a4f1c619b28b04dd
def calc_db(self, volume): <NEW_LINE> <INDENT> return self._min_volume + round( abs(self._min_volume - self._max_volume) * volume)
Calculate the decibel given the volume. Return the dB.
625941e9004d5f362079a7df
def unregisterMessageListing(self, messageId): <NEW_LINE> <INDENT> pass
Parameters: - messageId
625941e910dbd63aa1bd3051
def test_session_fallback(self): <NEW_LINE> <INDENT> storage = self.get_storage() <NEW_LINE> response = self.get_response() <NEW_LINE> for i in range(5): <NEW_LINE> <INDENT> storage.add(str(i) * 900) <NEW_LINE> <DEDENT> storage.update(response) <NEW_LINE> cookie_storing = self.stored_cookie_messages_count(storage, resp...
If the data exceeds what is allowed in a cookie, older messages which did not "fit" are stored in the SessionBackend.
625941e973bcbd0ca4b2c524
def _load_tweets(self): <NEW_LINE> <INDENT> page = self._cursor.next() <NEW_LINE> for tweet in page: <NEW_LINE> <INDENT> urls = re.findall(r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", tweet.text) <NEW_LINE> if len(urls) > 0: <NEW_LINE> <INDENT> tweet_blob = TextBlob(tweet.text) <NE...
Load new tweets from the search stream.
625941e98a43f66fc4b5450f
def message_ports_in(self): <NEW_LINE> <INDENT> return _ASPIN_swig.Async_File_Writer_sptr_message_ports_in(self)
message_ports_in(Async_File_Writer_sptr self) -> swig_int_ptr
625941e93346ee7daa2b321f
def like(self): <NEW_LINE> <INDENT> self.rating += 1 <NEW_LINE> self.save()
Метод увеличивает рейтинг поста на единицу.
625941e9009cb60464c6385d
def register_pipeline_node(node_class, name=None): <NEW_LINE> <INDENT> if bool(name)==False: <NEW_LINE> <INDENT> name = node_class.__name__ <NEW_LINE> <DEDENT> PIPELINE_NODE_REGISTRY[name] = node_class <NEW_LINE> debug('Registered pipeline node %s as %s' %(node_class.__name__, name))
Registers new pipeline node class to registry.
625941e98c0ade5d55d3ee6e
def __init__(self, token_type: int, text: str) -> None: <NEW_LINE> <INDENT> self.token_type = token_type <NEW_LINE> self.text = text
Constructor. Args: token_type (TokenType): A numeric token type representation. text (str): A lexeme
625941e929b78933be1e5b55
def test_deep_recursion(self): <NEW_LINE> <INDENT> mpa3 = TestMpa(user=self.user1, name="My Mpa") <NEW_LINE> mpa3.save() <NEW_LINE> mpa4 = TestMpa(user=self.user1, name="My Mpa 2") <NEW_LINE> mpa4.save() <NEW_LINE> mpa5 = TestMpa(user=self.user1, name="My Mpa 2") <NEW_LINE> mpa5.save() <NEW_LINE> folder3 = TestFolder(u...
folder1 |- mpa1 |- folder2 | - mpa2 | - folder3 |- mpa3 |- folder4 |- mpa4 |- mpa5
625941e921bff66bcd684dfd
def get_column_count(self, sheetname): <NEW_LINE> <INDENT> self.sheet = self.wb[sheetname] <NEW_LINE> return self.sheet.max_column
Return the column count of the given sheet Example: | Get Column count | Sheet1 |
625941e98c3a873295158870
def to_numpy(tensor): <NEW_LINE> <INDENT> return tensor.transpose(0, 1).transpose(1, 2).clone().numpy()
Convert 3-D torch tensor to a 3-D numpy array. Args: tensor (torch.Tensor): Tensor to be converted. Returns: numpy.ndarray
625941e963d6d428bbe449a0
def max_free_mem(server): <NEW_LINE> <INDENT> xm_ret, mfm = utils.run_remote(server, 'xm info | awk -F ": " "/max_free_memory/ {print \$2}"') <NEW_LINE> if xm_ret != 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return int(mfm)
Function to get max free mem on dom0. Returns an int containing the value in MB.
625941e9de87d2750b860247
def authorize(oauth_type, callback): <NEW_LINE> <INDENT> flask.session['oauth.next_uri'] = flask.request.args.get('next') or flask.request.referrer or None <NEW_LINE> state = werkzeug.security.gen_salt(64) <NEW_LINE> flask.session['oauth.state'] = state <NEW_LINE> return _oauth_provider(oauth_type).authorize( ca...
Call the OAuth provider's server which returns to the callback on completion or failer. Store the "next" or referrer page to return to after callback.
625941e9bde94217f368329c
def foo_bar_qix(number): <NEW_LINE> <INDENT> final_string = '' <NEW_LINE> if number % 3 == 0: <NEW_LINE> <INDENT> final_string += 'Foo' <NEW_LINE> <DEDENT> if number % 5 == 0: <NEW_LINE> <INDENT> final_string += 'Bar' <NEW_LINE> <DEDENT> if number % 7 == 0: <NEW_LINE> <INDENT> final_string += 'Qix' <NEW_LINE> <DEDENT> ...
:param number: integer :return: prints a string following the rules of the function >>> foo_bar_qix(1) 1 >>> foo_bar_qix(2) 2 >>> foo_bar_qix(3) FooFoo >>> foo_bar_qix(4) 4 >>> foo_bar_qix(5) BarBar >>> foo_bar_qix(6) Foo >>> foo_bar_qix(7) QixQix >>> foo_bar_qix(8) 8 >>> foo_bar_qix(9) Foo >>> foo_bar_qix(10) Bar >>> ...
625941e9187af65679ca55cf
def sequence_preprocess(sequence): <NEW_LINE> <INDENT> if isinstance(sequence, str): <NEW_LINE> <INDENT> return ''.join([i for i in sequence.replace(' ', '') if i>= u'\u4e00' and i<= u'\u9fa5']) <NEW_LINE> <DEDENT> return [''.join([i for i in s.replace(' ', '') if i>= u'\u4e00' and i<= u'\u9fa5']) for s in sequence]
Sequence preprocess, keep only Chinese. Args: sequence: pd.Series or np.array or list, sample feature value. Returns: a only Chinese list.
625941e9b7558d58953c53ba
def create_aggregate(self, **attrs): <NEW_LINE> <INDENT> return self._create(_aggregate.Aggregate, **attrs)
Create a new host aggregate from attributes :param dict attrs: Keyword arguments which will be used to create a :class:`~openstack.compute.v2.aggregate.Aggregate`, comprised of the properties on the Aggregate class. :returns: The results of aggregate creation :rtype: :class:`~openstack.compute.v2.aggregate.Ag...
625941e9d6c5a102081444fe
def format_data_from_value(self, value): <NEW_LINE> <INDENT> return list(value)
Convert field to byte form for writting to device
625941e9e76e3b2f99f3acb3
def move_by_radius(a, r, A): <NEW_LINE> <INDENT> return a + arr(r*cos(A), r*sin(A))
a: point r: radius A: angle
625941e9925a0f43d254a32b
def send_bits(self, data, nbits): <NEW_LINE> <INDENT> for i in range(nbits): <NEW_LINE> <INDENT> GPIO.output(self._W_CLK, 0) <NEW_LINE> bit = (data & 0b01) <NEW_LINE> data >>= 1 <NEW_LINE> GPIO.output(self._DATA, bit) <NEW_LINE> GPIO.output(self._W_CLK, 1) <NEW_LINE> <DEDENT> GPIO.output(self._DATA, 0) <NEW_LINE> GPIO....
Send a sequence of nbits bits from data to output, LSB first.
625941e9498bea3a759b9f5d
def save_to_file(collected, filename): <NEW_LINE> <INDENT> f = open(filename, "w") <NEW_LINE> f.write("Year, Month, Day, Url\n") <NEW_LINE> ordered_dates = sorted(collected.keys()) <NEW_LINE> for date_tuple in ordered_dates: <NEW_LINE> <INDENT> url = collected[date_tuple] <NEW_LINE> year, month, day = date_tuple <NEW_L...
Save the dictionary of collected urls to a csv file
625941e93539df3088e2e7fb
def previous_error(self): <NEW_LINE> <INDENT> error = self.command({"getpreverror": 1}) <NEW_LINE> if error.get("err", 0) is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return error
Get the most recent error to have occurred on this database. Only returns errors that have occurred since the last call to `Database.reset_error_history`. Returns None if no such errors have occurred.
625941e9f8510a7c17cf9baf
def get_dask_volume_b64(self): <NEW_LINE> <INDENT> with start_action(action_type="get_dask_volume_b64"): <NEW_LINE> <INDENT> vmt_yaml_str = self._get_volume_mount_yaml_str(left_pad=4) <NEW_LINE> vol_yaml_str = self._get_volume_yaml_str(left_pad=2) <NEW_LINE> ystr = "{}\n{}".format(vmt_yaml_str, vol_yaml_str) <NEW_LINE>...
Return the base-64 encoding of the K8s statements to create the pod's mountpoints. Probably better handled as a ConfigMap.
625941e99c8ee82313fbbc26
def post(self, *args, **kwargs): <NEW_LINE> <INDENT> self.render(r'../template/admin_pages/adminList.html')
对管理员账号的操作请求处理 :param args: :param kwargs: :return: ret :author: Yanfuzi
625941e9cb5e8a47e48b7f53
def __init__(self): <NEW_LINE> <INDENT> self.names = [] <NEW_LINE> self.posSent = [] <NEW_LINE> self.negSent = [] <NEW_LINE> self.netSent = [] <NEW_LINE> self.absumSent = []
Will hold the identifiers for records
625941e90c0af96317bb8697
def __init__(self, size, scale=1): <NEW_LINE> <INDENT> ptr = lib.wlr_xcursor_manager_create(ffi.NULL, size) <NEW_LINE> self._ptr = ffi.gc(ptr, lib.wlr_xcursor_manager_destroy) <NEW_LINE> lib.wlr_xcursor_manager_load(self._ptr, scale)
Creates a new XCursor manager Create cursor with base size and scale.
625941e991af0d3eaac9becd
def eReadNameString(handle, name): <NEW_LINE> <INDENT> if not isinstance(name, str): <NEW_LINE> <INDENT> raise TypeError("Expected a string instead of " + str(type(name)) + ".") <NEW_LINE> <DEDENT> outStr = ("\0"*constants.STRING_ALLOCATION_SIZE).encode("ascii") <NEW_LINE> error = _staticLib.LJM_eReadNameString(handle,...
Reads a string from a device. Args: handle: A valid handle to an open device. name: The string name of a register to read. Returns: The read string. Raises: TypeError: name is not a string. LJMError: An error was returned from the LJM library call. Note: This is a convenience function for eNames...
625941e94a966d76dd5514c4
def VerifySignedData(self, mac_bytes, sig_bytes): <NEW_LINE> <INDENT> return util.ConstantTimeCompare(sig_bytes, mac_bytes)
Return True if the signature corresponds to the signed message @param msg: message that has been signed @type msg: string @param sig_bytes: raw byte string of the signature @type sig_bytes: string @return: True if signature is valid for message. False otherwise. @rtype: boolean
625941e921bff66bcd684dfe
def GetContentUploadUrl(request, callback, customData = None, extraHeaders = None): <NEW_LINE> <INDENT> if not PlayFabSettings.DeveloperSecretKey: <NEW_LINE> <INDENT> raise PlayFabErrors.PlayFabException("Must have DeveloperSecretKey set to call this method") <NEW_LINE> <DEDENT> def wrappedCallback(playFabResult, error...
Retrieves the pre-signed URL for uploading a content file. A subsequent HTTP PUT to the returned URL uploads the content. Also, please be aware that the Content service is specifically PlayFab's CDN offering, for which standard CDN rates apply. https://docs.microsoft.com/rest/api/playfab/admin/content/getcontentuploadu...
625941e93617ad0b5ed683a6
def setup(hass, config): <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> if not util.validate_config(config, {DOMAIN: [ha.CONF_TYPE]}, logger): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> switch_type = config[DOMAIN][ha.CONF_TYPE] <NEW_LINE> switch_init = get_component('switch.{}'.format(sw...
Track states and offer events for switches.
625941e98c0ade5d55d3ee6f
def run_model(input_values): <NEW_LINE> <INDENT> gb = load_fitted_model() <NEW_LINE> X = get_default_values() <NEW_LINE> y = gb.predict(X) <NEW_LINE> return y[0]*input_values['sqft']
Runs prediction model
625941e9c432627299f050f9
def create_movie(self, fps, filenames_in="%05d.png", filename_out="movie.mp4"): <NEW_LINE> <INDENT> curr_dir = os.getcwd() <NEW_LINE> os.chdir(self.save_path) <NEW_LINE> os.system(r"ffmpeg -r {} -b 1800 -i {} {}".format(int(fps), filenames_in, filename_out)) <NEW_LINE> os.chdir(curr_dir)
Generate a movie from the pictures generated by save_pictures. Movie gets saved in self.save_path For filenames of the type 00000.png etc use filenames_in="%05d.png". Files must all have the save extension and resolution. :param fps: frames per second (integer). :param filenames_in: Signature of series of file names in...
625941e9187af65679ca55d0
def apply_select2(widget_cls): <NEW_LINE> <INDENT> cname = 'Select2%s' % widget_cls.__name__ <NEW_LINE> return type(cname, (Select2Mixin, widget_cls), {})
Dynamically creates new widget class mixed with Select2Mixin. Usage, for example: class SomeModelForm(admin.ModelForm): class Meta: widgets = { 'field': apply_select2(forms.Select), } So, `apply_select2(forms.Select)` will return new class, named Select2Select.
625941e93cc13d1c6d3c7828
def disable() -> typing_extensions.ContextManager[proto.Log]: <NEW_LINE> <INDENT> return set(NullLog())
Disable logger.
625941e97d847024c06be770
def text(update, context): <NEW_LINE> <INDENT> state = STORAGE.get_chat(update.message.chat.id).state <NEW_LINE> if state == chat.State.INACTIVE: <NEW_LINE> <INDENT> update.message.reply_text('введите /help') <NEW_LINE> <DEDENT> elif state == chat.State.GET_POSTS_STAGE_1: <NEW_LINE> <INDENT> id_group = VK.check_by_uuid...
Execute commands based on chat status
625941e9e1aae11d1e74a16c
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> inherit = bool(kwargs.pop("inherit_panels", True)) <NEW_LINE> super(AdminSite, self).__init__(*args, **kwargs) <NEW_LINE> if inherit: <NEW_LINE> <INDENT> self._registry.update(admin.site._registry)
Initialize the instance.
625941e9d4950a0f3b08c7f8
def testGetUsrDetail_7(self): <NEW_LINE> <INDENT> self.assertEqual(self.TUM.getUserDetail(),200)
验证获取用户详情
625941e9a934411ee3751b45
def simecolonCompletion(self, sql): <NEW_LINE> <INDENT> if sql.endswith(';'): <NEW_LINE> <INDENT> return sql <NEW_LINE> <DEDENT> return sql + ';'
add simecolon to a sql when it is not end with simecolon :type sql: str "param sql" the sql going to do completion
625941e976d4e153a657efe3
def wifi_connect(): <NEW_LINE> <INDENT> if not wlan.isconnected(): <NEW_LINE> <INDENT> print('connecting to network...') <NEW_LINE> wlan.connect('WIFI_SSID', 'WIFI_PASSWD') <NEW_LINE> while not wlan.isconnected(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> print('network config:', wlan.ifconfig())
If not presently connected, connect.
625941e991f36d47f21ac9a7
def __init__(self, typ): <NEW_LINE> <INDENT> self.typ = typ <NEW_LINE> self.length = 0 <NEW_LINE> self.capacity = 2 <NEW_LINE> self.A = self.make_array(self.capacity)
Initialize Array element with specifying the type and length typ: str
625941e93317a56b8693a0fd
def getDraft(self,numCards): <NEW_LINE> <INDENT> sets = [] <NEW_LINE> for set in xrange(numCards): <NEW_LINE> <INDENT> if set in [0,9,19,29]: <NEW_LINE> <INDENT> sets.append(self.getSet(2)) <NEW_LINE> <DEDENT> else: sets.append(self.getSet()) <NEW_LINE> <DEDENT> return sets
Make a draft of numCards sets of three cards.
625941e91b99ca400220af64
def get_cleaned_query_data_http_error(handler, *args): <NEW_LINE> <INDENT> data = {} <NEW_LINE> for k in args: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data[k] = clean_data(handler.get_query_argument(k)) <NEW_LINE> <DEDENT> except MissingArgumentError: <NEW_LINE> <INDENT> raise HTTPError(400) <NEW_LINE> <DEDENT> <D...
同上 :param handler: :param args: :return:
625941e999cbb53fe6793095
def reset_server(self, server_name): <NEW_LINE> <INDENT> self._begin_op() <NEW_LINE> db_session = self.db_session <NEW_LINE> server_sm = find_server_byname(db_session, server_name) <NEW_LINE> exec_server_sm(server_sm, ServerSMReset) <NEW_LINE> self._finish_op()
Reset server SM
625941e9a8ecb033257d357b
def _socket_command(remote, socket_path, command, args): <NEW_LINE> <INDENT> json_fp = StringIO() <NEW_LINE> remote.run( args=[ 'LD_LIBRARY_PATH=/tmp/cephtest/binary/usr/local/lib', '/tmp/cephtest/enable-coredump', '/tmp/cephtest/binary/usr/local/bin/ceph-coverage', '/tmp/cephtest/archive/coverage', '/tmp/cephtest/bina...
Run an admin socket command and return the result as a string.
625941e95f7d997b87174f4c
def produce(self, inputs: Inputs, timeout=None, iterations=None) -> Outputs: <NEW_LINE> <INDENT> with stopit.ThreadingTimeout(timeout) as timer: <NEW_LINE> <INDENT> outputs = List() <NEW_LINE> for cinput in inputs: <NEW_LINE> <INDENT> deg, num_feats = cinput[0].beta.shape <NEW_LINE> betas = np.array([ segment.beta for ...
Arguments: - inputs: List( # Data List( # Segments CurveFitting ) ) Returns: - List(d3m_ndarray)
625941e9d164cc61757831ff
def _em_iteration(self, params0, init=None, mstep_method=None): <NEW_LINE> <INDENT> res = self._em_expectation_step(params0, init=init) <NEW_LINE> params1 = self._em_maximization_step(res, params0, mstep_method=mstep_method) <NEW_LINE> return res, params1
EM iteration.
625941e97cff6e4e81117e36
def test_supply_names(self): <NEW_LINE> <INDENT> array = UnitOptionsArray('A', [2, 5, 10], names=['i', 'ii', 'iii']) <NEW_LINE> expected_names = ['i', 'ii', 'iii'] <NEW_LINE> for el, expected in zip(array, expected_names): <NEW_LINE> <INDENT> self.assertEqual(str(el), expected)
I create an OptionsArray and explicitly supply names for its elements.
625941e9cc40096d61595dff
def table_cell_to_html(cell): <NEW_LINE> <INDENT> if HTML.match(cell): <NEW_LINE> <INDENT> return cell <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return html.escape(cell)
Formats a cell from a Zeppelin TABLE as HTML.
625941e93346ee7daa2b3220
def join(self, *args, **colorkwargs): <NEW_LINE> <INDENT> flat = [] <NEW_LINE> for clr in args: <NEW_LINE> <INDENT> if isinstance(clr, (list, tuple, GeneratorType)): <NEW_LINE> <INDENT> flat.extend(str(c) for c in clr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> flat.append(str(clr)) <NEW_LINE> <DEDENT> <DEDENT> retu...
Like str.join, except it returns a ChainedBase. Arguments: args : One or more ChainedBase or str objects. If a list or tuple is given it will be flattened.
625941e9e8904600ed9f23e5
def iterate(agents, E, t, episode_nr): <NEW_LINE> <INDENT> global batch_size <NEW_LINE> terminal_list = [] <NEW_LINE> for agent in agents: <NEW_LINE> <INDENT> S = State(E, [agent.m, agent.n]) <NEW_LINE> if not agent.carry: <NEW_LINE> <INDENT> S_new, action_number, r, terminal = agent.move_agent(S) <NEW_LINE> agent.step...
Performs one iteration, i.e. simulation of one time step.
625941e999fddb7c1c9de83f
def _getTemplateAttribute(self, instance): <NEW_LINE> <INDENT> request = self._buildTemplateAttributes(instance) <NEW_LINE> status, ret_data = self.conn.send(request) <NEW_LINE> return ret_data
Get the attributes of a UDT
625941e9d53ae8145f87a717
def getfield(self, pkt, s): <NEW_LINE> <INDENT> self.sz = 1 <NEW_LINE> self.fmt = "B" <NEW_LINE> offset = 0 <NEW_LINE> val = struct.unpack(self.fmt, s[:1]) <NEW_LINE> val = val[0] <NEW_LINE> if val == 0xFD: <NEW_LINE> <INDENT> self.sz = 2 <NEW_LINE> self.fmt = ">H" <NEW_LINE> offset = 1 <NEW_LINE> <DEDENT> elif val == ...
Extract an internal value from a string
625941e9462c4b4f79d1db80
def get_mag_diff(obj, color): <NEW_LINE> <INDENT> c1,c2=color[0],color[1] <NEW_LINE> cmap=dict(g='g',r='r',z='z',m='w1',n='w2') <NEW_LINE> return '%s - %s' % (cmap[c1],cmap[c2]), obj.mag[ cmap[c1] ] - obj.mag[ cmap[c2] ]
returns color as string and array of colors color -- "gr" or "rz" etc obj -- qso_mag, star_mag
625941e94527f215b584c903
def __init__(self, std=0.05): <NEW_LINE> <INDENT> self.std = std
:param mean: global mean computed from dataset :param std: global std computed from dataset
625941e930c21e258bdfa953
def open_library_docs_info(dictionary): <NEW_LINE> <INDENT> book_results = [] <NEW_LINE> for i in range(len(dictionary["docs"])): <NEW_LINE> <INDENT> book_data = {key: value for key, value in dictionary["docs"][i].items() if key in ["title", "key", "author_name", "edition_count", "publish_year", "isbn", "language", "id...
Takes a dictionary (from OpenLibrary's JSON API) and returns a list with a dictionary of important features for each book
625941e9d10714528d600199
def get_post_day_list(post_list): <NEW_LINE> <INDENT> def_posts_date_list = [] <NEW_LINE> for post in post_list: <NEW_LINE> <INDENT> if get_date_only(post["date"]) not in get_date_only_list(def_posts_date_list): <NEW_LINE> <INDENT> def_posts_date_list.append(post["date"]) <NEW_LINE> <DEDENT> <DEDENT> return def_posts_d...
Create a unique list of iso from a post list, keeping the first iso date if multiple are on the same date
625941e94428ac0f6e5baca7
def start_node(i, dirname, extra_args=None, rpchost=None): <NEW_LINE> <INDENT> datadir = os.path.join(dirname, "node"+str(i)) <NEW_LINE> args = [ os.getenv("BITCOIND", "octod"), "-datadir="+datadir, "-keypool=1", "-discover=0", "-rest" ] <NEW_LINE> if extra_args is not None: args.extend(extra_args) <NEW_LINE> bitcoind_...
Start a octod and return RPC connection to it
625941e9bd1bec0571d90adf
def touch(self): <NEW_LINE> <INDENT> return self.fsobj.touch(self.parts)
Creates the file at this path, or updates the timestamp.
625941e94d74a7450ccd4676
def test_ct_dg(self): <NEW_LINE> <INDENT> bk = Backend(product='qulacs', device='gpu_simulator') <NEW_LINE> qc = QCirc().h(0).h(1).ct_dg(0,1) <NEW_LINE> res = bk.run(qcirc=qc) <NEW_LINE> actual = res.info['quantumstate'].get_vector() <NEW_LINE> expect = reverse_bit_order(np.array([(0.5+0j), (0.5+0j), (0.5+0j), (0.35355...
test 'ct_dg' gate
625941e9442bda511e8be8c2
def problem17(): <NEW_LINE> <INDENT> result = len(lib.thousand[0]) <NEW_LINE> for num in range(1, 1000): <NEW_LINE> <INDENT> divident1, remainder1 = divmod(num, 100) <NEW_LINE> number_in_words = divident1 and lib.below_20[divident1]+lib.hundred[0] or '' <NEW_LINE> if remainder1: <NEW_LINE> <INDENT> number_in_words = di...
Return letters would be needed to write all the numbers in words from 1 to 1000
625941e9f548e778e58cda30
def is_logged_in(self): <NEW_LINE> <INDENT> return self._token and self._token_remain_time() > 0
로그인 상태인지 구합니다.
625941e9d486a94d0b98e5f8
def basis_message_func(self, edges): <NEW_LINE> <INDENT> if self.num_bases < self.num_rels: <NEW_LINE> <INDENT> weight = tf.reshape(self.weight, (self.num_bases, self.in_feat * self.out_feat)) <NEW_LINE> weight = tf.reshape(tf.matmul(self.w_comp, weight), ( self.num_rels, self.in_feat, self.out_feat)) <NEW_LINE> <DEDEN...
Message function for basis regularizer
625941e966656f66f7cbc65e
def hermi_sum(x): <NEW_LINE> <INDENT> return x + x.T.conj().copy()
x + x^\dagger
625941e924f1403a92601013
def _cov(X, shrinkage=None): <NEW_LINE> <INDENT> shrinkage = "empirical" if shrinkage is None else shrinkage <NEW_LINE> if isinstance(shrinkage, str): <NEW_LINE> <INDENT> if shrinkage == 'auto': <NEW_LINE> <INDENT> sc = StandardScaler() <NEW_LINE> X = sc.fit_transform(X) <NEW_LINE> s = ledoit_wolf(X)[0] <NEW_LINE> s = ...
Estimate covariance matrix (using optional shrinkage). Parameters ---------- X : array-like, shape (n_samples, n_features) Input data. shrinkage : string or float, optional Shrinkage parameter, possible values: - None or 'empirical': no shrinkage (default). - 'auto': automatic shrinkage using the ...
625941e9091ae35668667407
def run(self, event, lambda_context): <NEW_LINE> <INDENT> resources = self.resolve_resources(event) <NEW_LINE> if not resources: <NEW_LINE> <INDENT> return resources <NEW_LINE> <DEDENT> resources = self.policy.resource_manager.filter_resources( resources, event) <NEW_LINE> if 'debug' in event: <NEW_LINE> <INDENT> self....
Run policy in push mode against given event. Lambda automatically generates cloud watch logs, and metrics for us, albeit with some deficienies, metrics no longer count against valid resources matches, but against execution. Fortunately we already have replacements. TODO: better customization around execution context ...
625941e916aa5153ce362929
def setup_vars(var_file, var, merge_vars, debug, no_colour): <NEW_LINE> <INDENT> logger = setup_logging(debug, no_colour) <NEW_LINE> return_value = {} <NEW_LINE> def _update_dict(variable): <NEW_LINE> <INDENT> variable_key, variable_value = variable.split("=") <NEW_LINE> keys = variable_key.split(".") <NEW_LINE> def _n...
Handle --var-file and --var arguments before returning data for the user_variables as required by the ConfigReader and SceptreContext. :param var_file: the var_file list. :type var_file: List[Dict] :param var: the var list. :type var: List[str] :param merge_vars: Merge instead of overwrite duplicate keys. :type me...
625941e971ff763f4b549b45
def get_authorization_header(username, password): <NEW_LINE> <INDENT> if username == EMPTY_GUID: <NEW_LINE> <INDENT> auth = _get_bearer_auth_str(password) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> auth = _get_basic_auth_str(username, password) <NEW_LINE> <DEDENT> return {'Authorization': auth}
Get the authorization header as Basic auth if username is provided, or Bearer auth otherwise :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry
625941e999cbb53fe6793096
def _limit_memory_usage(self): <NEW_LINE> <INDENT> while self.surfaces_referenced > 25: <NEW_LINE> <INDENT> min_id, min_old = None, 2**31 <NEW_LINE> for key, parent in self.parents.iteritems(): <NEW_LINE> <INDENT> if parent.surface is not None and parent.old < min_old: <NEW_LINE> <INDENT> min_id, min_old = key, parent...
limit memory usage, forget old surfaces
625941e907f4c71912b11936
def __delitem__(self, item): <NEW_LINE> <INDENT> keys = object.__getattribute__(self, "_data") <NEW_LINE> if item in keys: <NEW_LINE> <INDENT> del(keys[item]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> object.__delitem__(self, item)
Deletes the given item from the objects _data dict, or if from the objects namespace, if it does not exist in _data.
625941e9d268445f265b5320
def uni(): <NEW_LINE> <INDENT> pass
>>> import pymel.core as pmc >>> xform = pmc.polyCube()[0] >>> myname = 'cubexform' >>> xform.rename(myname) nt.Transform(u'cubexform') >>> xform.name() u'cubexform' >>> myname == xform.name() True >>> type(myname), type(xform.name()) (<type 'str'>, <type 'unicode'>) >>> str.__mro__ (<type 'str'>, <type 'basestring'>,...
625941e950812a4eaa59c7ce
def test_active_model_manager_returns_query_set_of_profiles(self): <NEW_LINE> <INDENT> query = ImagerProfile.active.all() <NEW_LINE> self.assertIsInstance(query[0], ImagerProfile)
Test that active model manager returns profil query set.
625941e9e1aae11d1e74a16d
def readDNS(): <NEW_LINE> <INDENT> pass
读取DNS
625941e96e29344779a62ac1
def clean_up_statement(self, statement: str): <NEW_LINE> <INDENT> if not statement[-1] == '.': <NEW_LINE> <INDENT> statement += '.' <NEW_LINE> <DEDENT> statement.strip('•') <NEW_LINE> statement.strip('\t') <NEW_LINE> statement.strip('"') <NEW_LINE> tokens = wordpunct_tokenize(statement.lower()) <NEW_LINE> if tokens[0] ...
This function takes a statement and cleans it, i.e. removes undesirable parts. This includes stripping it of undesirable characters and discourse markers, and doing some punctuation checks. The output is a (cleaned-up) string.
625941e93eb6a72ae02ec99b
def transform(mapping): <NEW_LINE> <INDENT> def process(pipeline): <NEW_LINE> <INDENT> for row in pipeline: <NEW_LINE> <INDENT> if isinstance(mapping, dict): <NEW_LINE> <INDENT> row = dict((col, value(row) if callable(value) else row[value]) for col, value in mapping.items()) <NEW_LINE> <DEDENT> elif isinstance(mapping...
>>> items = [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}] >>> res = list(transform({'a': 'b', 'b': 'a', 'c': lambda r: r['a']+r['b']})(items)) >>> cmp(res, [{'a': 2, 'b': 1, 'c': 3}, {'a': 4, 'b': 3, 'c': 7}]) 0
625941e97d847024c06be771
def rm_users(self, ls_users): <NEW_LINE> <INDENT> from drastic.models import User <NEW_LINE> not_exist = [] <NEW_LINE> removed = [] <NEW_LINE> not_there = [] <NEW_LINE> for username in ls_users: <NEW_LINE> <INDENT> user = User.find(username) <NEW_LINE> if user: <NEW_LINE> <INDENT> if self.name in user.get_groups(): <NE...
Remove a list of users from the group Return 3 lists: removed for the username who were removed not_there for the username who weren't in the gr not_exist for the usernames who doesn't exist
625941e9aad79263cf390ef9
def main(): <NEW_LINE> <INDENT> from x84.bbs import getsession, getterminal, echo <NEW_LINE> session, term = getsession(), getterminal() <NEW_LINE> session.activity = 'Weather' <NEW_LINE> while True: <NEW_LINE> <INDENT> echo(u'\r\n\r\n') <NEW_LINE> location = session.user.get('location', dict()) <NEW_LINE> search = loc...
Main routine.
625941e9f9cc0f698b140aa8
def power_capacity(cur): <NEW_LINE> <INDENT> init_year, init_month, duration, timestep = simulation_timesteps(cur) <NEW_LINE> insts = institutions(cur) <NEW_LINE> entry_exit = cur.execute('SELECT max(value), timeseriespower.agentid, ' 'parentid, entertime, entertime + lifetime' ' FROM agententry ' 'INNER JOIN timeserie...
Gets dictionary of power capacity by calling capacity_calc Parameters ---------- cur: sqlite cursor sqlite cursor Returns ------ power: dictionary "dictionary with key=government, and value=timeseries list of installed capacity"
625941e9dd821e528d63b656
def replacement_reconstruct_n(self, n0, ni, x=None): <NEW_LINE> <INDENT> if x is None: <NEW_LINE> <INDENT> x = np.empty((ni, self.d), dtype=np.float32) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert x.shape == (ni, self.d) <NEW_LINE> <DEDENT> self.reconstruct_n_c(n0, ni, swig_ptr(x)) <NEW_LINE> return x
Approximate reconstruction of vectors `n0` ... `n0 + ni - 1` from the index. Missing vectors trigger an exception. Parameters ---------- n0 : int Id of the first vector to reconstruct ni : int Number of vectors to reconstruct x : array_like, optional pre-allocated array to store the results Returns ------...
625941e9b5575c28eb68e4b6