code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def info(self, reqName, **kwargs): <NEW_LINE> <INDENT> print("### CALL info API with request name %s" % reqName) <NEW_LINE> data = {'status': "OK", "api": "info"} <NEW_LINE> if kwargs: <NEW_LINE> <INDENT> data.update(kwargs) <NEW_LINE> <DEDENT> return data | Return current status about our service | 625941c560cbc95b062c6540 |
def test_supported_features_children_only(self): <NEW_LINE> <INDENT> config = validate_config(self.config_children_only) <NEW_LINE> ump = universal.UniversalMediaPlayer(self.hass, **config) <NEW_LINE> ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name']) <NEW_LINE> run_coroutine_threadsafe(ump.async_upda... | Test supported media commands with only children. | 625941c556b00c62f0f14656 |
def get_current_visitors(): <NEW_LINE> <INDENT> return Visitor.objects.filter(acknowledged=False).order_by("arrival_time") | Returns all visitors that have been registered but not seen
@returns:
Iterable of visitor objects | 625941c5d10714528d5ffcdf |
def standardize(layer, offset, scale, shared_axes): <NEW_LINE> <INDENT> layer = BiasLayer(layer, -offset, shared_axes) <NEW_LINE> layer.params[layer.b].remove('trainable') <NEW_LINE> layer = ScaleLayer(layer, T.inv(scale), shared_axes) <NEW_LINE> layer.params[layer.scales].remove('trainable') <NEW_LINE> return layer | Convenience function for standardizing inputs by applying a fixed offset
and scale. This is usually useful when you want the input to your network
to, say, have zero mean and unit standard deviation over the feature
dimensions. This layer allows you to include the appropriate statistics to
achieve this normalization ... | 625941c55fcc89381b1e16bb |
@process <NEW_LINE> def first(): <NEW_LINE> <INDENT> return First() | Returns class instance of `First`.
For more details, please have a look at the implementations inside `First`.
Returns
-------
First :
Class instance implementing all 'first' processes. | 625941c55fcc89381b1e16bc |
def build_orbital_node_dict(orbit_list: List[DirectOrbit]) -> OrbitalNodeDict: <NEW_LINE> <INDENT> node_dict = OrbitalNodeDict() <NEW_LINE> for orbit in orbit_list: <NEW_LINE> <INDENT> node0 = node_dict[orbit.m0] <NEW_LINE> node1 = node_dict[orbit.m1] <NEW_LINE> node0.satellites.append(node1) <NEW_LINE> node1.parent_or... | Build a OrbitalNodeDict composed of OrbitalNode as values and orbit names as keys.
Each OrbitalNode will be linked to its parent and satellites.
:param orbit_list: List of DirectOrbit objects
:type orbit_list: List[DirectOrbit]
:return: The constructed OrbitalNodeDict
:rtype: OrbitalNodeDict | 625941c58a43f66fc4b54064 |
def find_run_start(self, index): <NEW_LINE> <INDENT> running_count = 0 <NEW_LINE> for i in range(index, -1, -1) + range(index, self.m)[::-1]: <NEW_LINE> <INDENT> if not self.is_empty(i) and not self.array[i][2]: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if self.array[i][0]: <NEW_LINE> <INDENT> running_count += 1 <N... | Find the index of the start of the run containing the input index | 625941c5e5267d203edcdc9d |
def Trouver_Jour(a): <NEW_LINE> <INDENT> x = a%7 <NEW_LINE> if (x==0): <NEW_LINE> <INDENT> return "Dimanche" <NEW_LINE> <DEDENT> elif (x==1): <NEW_LINE> <INDENT> return "Lundi" <NEW_LINE> <DEDENT> elif (x==2): <NEW_LINE> <INDENT> return "Mardi" <NEW_LINE> <DEDENT> elif (x==3): <NEW_LINE> <INDENT> return "Mercredi" <NEW... | récupère le reste et retourne la jour attendu | 625941c5fff4ab517eb2f439 |
def new_frame(self): <NEW_LINE> <INDENT> if not self.frame.new: <NEW_LINE> <INDENT> valid, matrix = self.cam.read() <NEW_LINE> if matrix is None or valid is False: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> f_raw = cv.CreateImageHeader((matrix.shape[1], matrix.shape[0]), cv.IPL_DEPTH_8U, 3) <NEW_LINE> cv.SetData(f_ra... | get a new frame from the webcam | 625941c526068e7796caecda |
def split_in_blocks(sequence, hint, weight=lambda item: 1, key=lambda item: 'Unspecified'): <NEW_LINE> <INDENT> if hint == 0: <NEW_LINE> <INDENT> return sequence <NEW_LINE> <DEDENT> items = list(sequence) <NEW_LINE> assert hint > 0, hint <NEW_LINE> assert len(items) > 0, len(items) <NEW_LINE> total_weight = float(sum(w... | Split the `sequence` in a number of WeightedSequences close to `hint`.
:param sequence: a finite sequence of items
:param hint: an integer suggesting the number of subsequences to generate
:param weight: a function returning the weigth of a given item
:param key: a function returning the key of a given item
The Weigh... | 625941c54f88993c3716c066 |
def pause(self, seconds = -1): <NEW_LINE> <INDENT> self.paused = True <NEW_LINE> self.delay = seconds | Pause this tween
Do ``tween.pause(2)`` to pause for a specific time, or
``tween.pause()`` which pauses indefinitely. | 625941c531939e2706e4ce6a |
def getID(self): <NEW_LINE> <INDENT> return os.path.join(self.group.name, self.name) | Returns the ID of the exercise file, that is, the path to the
file. | 625941c5851cf427c661a50e |
def create_country_flag_collection(): <NEW_LINE> <INDENT> countries = get_all_countries() <NEW_LINE> country_flag = {} <NEW_LINE> for country in countries: <NEW_LINE> <INDENT> country_flag[countries[country]] = 'https://eschome.net/flags/' + country + '.png' <NEW_LINE> <DEDENT> insert_to_db(client, country_flag, 'count... | Create document where the country is the key & flag's picture is the value
:return: Nothing | 625941c58a43f66fc4b54065 |
def install_apk(apklist: list): <NEW_LINE> <INDENT> for apk in apklist: <NEW_LINE> <INDENT> os.system('adb install -r' + apk) | 遍历存放apk绝对路径的list 调用adb命令
:param apklist:
:return: | 625941c5fb3f5b602dac3690 |
def setState(self, state): <NEW_LINE> <INDENT> self.state = state | TODO: purpose of the method | 625941c5be7bc26dc91cd601 |
def get_letters_index(self): <NEW_LINE> <INDENT> container_el = self.get_element(self.__class__.__locators['索引字母容器']) <NEW_LINE> letter_els = container_el.find_elements(MobileBy.XPATH, "//android.widget.TextView") <NEW_LINE> if not letter_els: <NEW_LINE> <INDENT> raise AssertionError("No m005_contacts, please add m005_... | 获取所有索引字母 | 625941c50c0af96317bb81e6 |
def find(self, request: OpenAPIRequest) -> PathTuple: <NEW_LINE> <INDENT> paths_iter_peek = peekable( self._get_paths_iter(request.full_url_pattern) ) <NEW_LINE> if not paths_iter_peek: <NEW_LINE> <INDENT> raise PathNotFound(request.full_url_pattern) <NEW_LINE> <DEDENT> operations_iter_peek = peekable( self._get_operat... | Better finder for request path.
Instead of returning first possible result from
``self._get_servers_iter(...)`` call, attempt to ensure that
``request.full_url_pattern`` ends with ``path.name``. | 625941c51b99ca400220aaaf |
def test_program_sleep_1(test_env): <NEW_LINE> <INDENT> test_env.start(1) <NEW_LINE> program = Program("sleep 1") <NEW_LINE> with test_env.client.new_session() as s: <NEW_LINE> <INDENT> t1 = program() <NEW_LINE> s.submit() <NEW_LINE> test_env.assert_duration(0.99, 1.1, lambda: t1.wait()) | Sleep followed by wait | 625941c550485f2cf553cd97 |
def pageviews_by_document(start_date, end_date): <NEW_LINE> <INDENT> counts = {} <NEW_LINE> request = _build_request() <NEW_LINE> start_index = 1 <NEW_LINE> max_results = 10000 <NEW_LINE> while True: <NEW_LINE> <INDENT> @retry_503 <NEW_LINE> def _make_request(): <NEW_LINE> <INDENT> return request.get( ids='ga:' + profi... | Return the number of pageviews by document in a given date range.
* Only returns en-US documents for now since that's what we did with
webtrends.
Returns a dict with pageviews for each document:
{<document_id>: <pageviews>,
1: 42,
7: 1337,...} | 625941c5a934411ee3751692 |
def get_pending_count(self): <NEW_LINE> <INDENT> session = self.Session() <NEW_LINE> count = session.execute("select count(id) from replays where created = false and failed = false").first()[0] <NEW_LINE> session.close() <NEW_LINE> return count | Get the number of pending replays.
Returns:
str: Number of pending replays | 625941c571ff763f4b549687 |
def __init__(self, model, batcher, word_vocab, entity_vocab): <NEW_LINE> <INDENT> self._model = model <NEW_LINE> self._model.build_graph() <NEW_LINE> self._batcher = batcher <NEW_LINE> self._word_vocab = word_vocab <NEW_LINE> self._entity_vocab = entity_vocab <NEW_LINE> self._saver = tf.train.Saver() <NEW_LINE> self._s... | Initialize decoder.
Args:
model: a Seq2SeqAttentionModel object.
batcher: a Batcher object.
vocab: Vocabulary object | 625941c5925a0f43d2549e74 |
def addWord(self, word: str) -> None: <NEW_LINE> <INDENT> self.words[len(word)].add(word) | Adds a word into the data structure. | 625941c5f7d966606f6aa001 |
def create_category(**args): <NEW_LINE> <INDENT> assert_kwargs({'name'}, args) <NEW_LINE> sql = 'INSERT INTO categories(name) VALUES(:name);' <NEW_LINE> cursor.execute(sql, args) | Creates a new category. Keyword arg: name. | 625941c5d6c5a10208144048 |
def get_machines(cluster, machineSets): <NEW_LINE> <INDENT> machines = [] <NEW_LINE> j = 1 <NEW_LINE> for s in machineSets: <NEW_LINE> <INDENT> for i in range(1, s.replicas + 1): <NEW_LINE> <INDENT> m = VagrantMachine() <NEW_LINE> m.name = "%s-%s" % (cluster.name, s.name) if s.replicas == 1 else "%s-%s%s" ... | transform a cluster / a list of machineSets into a set of machines to be created.
the list of machine is also stored into `tmp/machines.yaml` for vagrant execution | 625941c556b00c62f0f14657 |
def _get_manage_dot_py(host): <NEW_LINE> <INDENT> return f'~/sites/{host}/virtualenv/bin/python ~/sites/{host}/source/manage.py' | получить manage точка py | 625941c51b99ca400220aab0 |
def fit_model(self, order): <NEW_LINE> <INDENT> model = smt.ARIMA(self._data, order).fit( method='mle', trend='nc' ) <NEW_LINE> return model | Args:
order (tuple[int]): a three tuple for the arima orders
Returns: | 625941c55fdd1c0f98dc0231 |
def reverseString(self, s): <NEW_LINE> <INDENT> for i in range(0, len(s) - 1): <NEW_LINE> <INDENT> s = s[:i] + s[-1] + s[i:-1] <NEW_LINE> <DEDENT> return s | :type s: str
:rtype: str | 625941c5498bea3a759b9aae |
def start(self): <NEW_LINE> <INDENT> server = tornado.httpserver.HTTPServer(Application()) <NEW_LINE> server.listen(Application.PORT) <NEW_LINE> tornado.ioloop.IOLoop.instance().start() | Start the application. | 625941c556ac1b37e62641d1 |
def show_action_stats(self,show_plot=False): <NEW_LINE> <INDENT> if show_plot: <NEW_LINE> <INDENT> action_list = list(self.action_stats.keys()) <NEW_LINE> action_count = list(self.action_stats.values()) <NEW_LINE> x_pos = [i for i, _ in enumerate(action_list)] <NEW_LINE> plt.bar(x_pos, action_count, color='green') <NEW... | Show actions count for episode. | 625941c5d268445f265b4e6d |
def _yaml1_minus_section(self, section, srcstr=None): <NEW_LINE> <INDENT> if srcstr is None: <NEW_LINE> <INDENT> srcstr = self.yaml_query1 <NEW_LINE> <DEDENT> obj = yaml.load(srcstr) <NEW_LINE> del(obj[section]) <NEW_LINE> outstr = yaml.dump(obj) <NEW_LINE> return outstr | Return yaml but without the top level section named as indicated.
If srcstr not specified, uses self.yaml_query1. | 625941c585dfad0860c3ae59 |
def restrict_search(dict_enz, sequence, size_restriction_site=4): <NEW_LINE> <INDENT> lresult =[] <NEW_LINE> strand = "+" <NEW_LINE> lseq = [] <NEW_LINE> if size_restriction_site < 1: <NEW_LINE> <INDENT> print("size_restriction_site should be >= 1") <NEW_LINE> raise AttributeError <NEW_LINE> <DEDENT> lseq.append(sequen... | Find the restriction site in the sequence using all the enzyme given in the dict_enz
:parm sequence: DNA sequence
:type sequence: string
:parm dict_enz: Dictionary of restriction enzyme with their names as keys and their characteristics as value in a list
:type dict_enz: dict
:parm size_restriction_site: minimum recog... | 625941c507f4c71912b11480 |
def book_url_dictionary(url): <NEW_LINE> <INDENT> book_dictionary = {} <NEW_LINE> response = requests.get(url) <NEW_LINE> if response.ok: <NEW_LINE> <INDENT> soup = BeautifulSoup(response.text, 'html.parser') <NEW_LINE> n_url = soup.find('form', {'class': 'form-horizontal'}).find('strong').text <NEW_LINE> n_url = int(n... | function to retrieve the product page link, book name and picture link
:param url: category page link
:return: Dictionary with book url (keys) title and picture link (value) | 625941c563f4b57ef000111b |
def count_tap_interuptions(self, dataset1, dataset2, dataset3, dataset4, total_instances): <NEW_LINE> <INDENT> frequency_choice = 0 <NEW_LINE> max_count = 0 <NEW_LINE> count = 0 <NEW_LINE> for i in range(0, int(total_instances/self.SAMPLING_PERIOD_1)): <NEW_LINE> <INDENT> if float(dataset1[i][0]) > 0.999: <NEW_LINE> <I... | :param dataset1:
:param dataset2:
:param dataset3:
:param dataset4:
:param total_instances:
:return: | 625941c563f4b57ef000111c |
def __init__(self, *, name: str, value: str, mime_type: str = None, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.name = canon(name) <NEW_LINE> self.value = value <NEW_LINE> self.mime_type = mime_type.lower() if mime_type else None | Initialize attribute preview object.
Args:
name: attribute name
value: attribute value; caller must base64-encode for attributes with
non-empty MIME type
mime_type: MIME type (default null) | 625941c5be8e80087fb20c43 |
def start(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(self.pidfile, 'r') as pf_handle: <NEW_LINE> <INDENT> pid = int(pf_handle.read().strip()) <NEW_LINE> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <INDENT> pid = None <NEW_LINE> <DEDENT> if pid: <NEW_LINE> <INDENT> log_message = ( 'PID file: {} alrea... | Start the daemon.
Args:
None
Returns: | 625941c5462c4b4f79d1d6cf |
def print_locations(locations): <NEW_LINE> <INDENT> for i, (t, id, alive, patch, state) in enumerate(locations): <NEW_LINE> <INDENT> print('[%4i] %3i %4i %2i %2i %2i' % (i, t, id, alive, state, patch)) | Print rows of locations array for cleaner viewing | 625941c54d74a7450ccd41c2 |
def getLatestOrNone(model, field=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if field: <NEW_LINE> <INDENT> return model.objects.latest(field) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return model.objects.latest() <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> return None | Description:
Get the most recent row of a model or return None
Parameters:
model - model object
field - field to search against (string)
Returns:
query response or None | 625941c5627d3e7fe0d68e4d |
def query(self, variables, evidence=None, args="exact"): <NEW_LINE> <INDENT> if args == "exact": <NEW_LINE> <INDENT> return self.backward_inference(variables, evidence) | Query method for Dynamic Bayesian Network using Interface Algorithm.
Parameters
----------
variables: list
list of variables for which you want to compute the probability
evidence: dict
a dict key, value pair as {var: state_of_var_observed}
None if no evidence
Examples
--------
>>> from pgmpy.factors.dis... | 625941c53346ee7daa2b2d6a |
def cmd_grouptoggle(self, args): <NEW_LINE> <INDENT> tmsg = [] <NEW_LINE> togglea = [] <NEW_LINE> if args['togact'] == 'disable': <NEW_LINE> <INDENT> state = False <NEW_LINE> <DEDENT> elif args['togact'] == 'enable': <NEW_LINE> <INDENT> state = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> state = "toggle" <NEW_LI... | toggle all actions in a group | 625941c50383005118ecf5e2 |
def query_server_dump_results_few_executables(executables_list, functions_list): <NEW_LINE> <INDENT> functions_from_exe_1 = functions_list <NEW_LINE> functions_from_exe_2 = functions_list <NEW_LINE> attr_list = ATTR_LIST <NEW_LINE> for i in range(len(executables_list)): <NEW_LINE> <INDENT> exe_name_1 = executables_list... | Calls query_server_dump_results for all pairs of executables in
executables_list with functions_list. | 625941c599cbb53fe6792be5 |
def api_targetgroup_element(targetgroup_data, element): <NEW_LINE> <INDENT> if element == "user": <NEW_LINE> <INDENT> return utils.response("[" + targetgroup_data.username_list_json() + "]", 200) <NEW_LINE> <DEDENT> elif element == "usergroup": <NEW_LINE> <INDENT> return utils.response("[" ... | Return the attached elements to a targetgroup | 625941c531939e2706e4ce6b |
def remove_content_length_range_condition( self): <NEW_LINE> <INDENT> self._lower_limit = None <NEW_LINE> self._upper_limit = None | Remove previously set content-length-range condition. | 625941c515fb5d323cde0b0d |
def get_data_oxy(self, channel, frame): <NEW_LINE> <INDENT> channel = struct.pack('!i', channel) <NEW_LINE> frame = struct.pack('!i', frame) <NEW_LINE> data, rt = self.request_data("tGetDataOxy", channel, frame) <NEW_LINE> if data is None: <NEW_LINE> <INDENT> return None, rt <NEW_LINE> <DEDENT> elif data[:14] == "Wrong... | Get oxy data.
Parameters:
----------
channel : int
The channel.
frame : int
The time point.
Returns:
--------
data : float
The raw data.
rt : int
The time it took to get the data. | 625941c58c3a8732951583b8 |
def insertMatrix(hm, hm2, groupName): <NEW_LINE> <INDENT> idx = hm.parameters["group_labels"].index(groupName) <NEW_LINE> hmEnd = hm.parameters["group_boundaries"][idx + 1] <NEW_LINE> idx2 = hm2.parameters["group_labels"].index(groupName) <NEW_LINE> hm2Start = hm2.parameters["group_boundaries"][idx2] <NEW_LINE> hm2End ... | Given two heatmapper objects and a region group name, insert the regions and
values from hm2 for that group to the end of those for hm. | 625941c5d58c6744b4257c5f |
def best_sf(data_type, range): <NEW_LINE> <INDENT> data_type = np.dtype(data_type) <NEW_LINE> try: <NEW_LINE> <INDENT> info = np.iinfo(data_type) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> info = np.finfo(data_type) <NEW_LINE> <DEDENT> return info.max/np.abs(range).max() | Computes the optimal scaling factor for data compression
Parameters
----------
data_type
Data type that values are being compressed to
range : scalar or tuple
Expected data range. If scalar, assumes the value falls in the range
(-range, range) | 625941c599cbb53fe6792be6 |
def unique_id(self): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_map_bb_sptr_unique_id(self) | unique_id(self) -> long | 625941c55166f23b2e1a5158 |
def push_branch(self, branch, title='', comment=''): <NEW_LINE> <INDENT> identifier = self.get_branch_identifier(branch) <NEW_LINE> log.info('pushing branch %s in %s' % (identifier, self._gh_name())) <NEW_LINE> self.check_remote() <NEW_LINE> self.push_remote(identifier) <NEW_LINE> if not title: <NEW_LINE> <INDENT> titl... | Pushes a branch upstream.
Since the python github API libraries don't support pull requests,
we'll have to do it manually using urllib2 :( | 625941c50383005118ecf5e3 |
def remove_from_cart(request, module_id): <NEW_LINE> <INDENT> cart = request.session.get('cart', {}) <NEW_LINE> if module_id in cart: <NEW_LINE> <INDENT> del cart[module_id] <NEW_LINE> messages.info(request, "Item has been deleted") <NEW_LINE> <DEDENT> request.session['cart'] = cart <NEW_LINE> return redirect(reverse('... | Delete item from cart | 625941c5c4546d3d9de72a32 |
def test_post_returns_200_code(): <NEW_LINE> <INDENT> r = requests.post('http://capstonedd.cs.pdx.edu:1337/users', data=dataquery) <NEW_LINE> assert r.status_code == 200 | SUMMARY: Test that valid POST body returns a 200 code ('ok')
METHOD: Send a POST request with proper post body.
FAIL: Status code is not 200. | 625941c5566aa707497f456a |
def fileno(self): <NEW_LINE> <INDENT> return self._file.fileno() | Return the underlying file descriptor. Useful for select, epoll, etc. | 625941c5796e427e537b05c4 |
def get_rate(self, exchange): <NEW_LINE> <INDENT> if exchange in self.cache.keys(): <NEW_LINE> <INDENT> if time.time() + self.cache[exchange][0] > self.cache_max_age: <NEW_LINE> <INDENT> return self.cache[exchange][1] <NEW_LINE> <DEDENT> <DEDENT> data = self.get_url_data(self.exchanges[exchange]) <NEW_LINE> try: <NEW_L... | Gets the exchange rate as USD from given exchange, and caches results. | 625941c5bde94217f3682df1 |
def arrays_almost_equal(a1, a2): <NEW_LINE> <INDENT> a1units = False <NEW_LINE> if isinstance(a1, MdtQuantity): <NEW_LINE> <INDENT> if a1.dimensionless: <NEW_LINE> <INDENT> a1mag = a1.value_in(ureg.dimensionless) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> a1units = True <NEW_LINE> a1mag = a1.magnitude <NEW_LINE> <DE... | Return true if arrays are almost equal up to numerical noise
Note:
This is assumes that absolute differences less than 1e-12 are insignificant. It is
therefore more likely to return "True" for very small numbers and
"False" for very big numbers. Caveat emptor.
Args:
a1 (MdtQuantity or np.ndarray): fir... | 625941c50fa83653e4656fbb |
def _windows_cmdline2list(cmdline): <NEW_LINE> <INDENT> whitespace = ' \t' <NEW_LINE> bs_count = 0 <NEW_LINE> in_quotes = False <NEW_LINE> arg = [] <NEW_LINE> argv = [] <NEW_LINE> for ch in cmdline: <NEW_LINE> <INDENT> if ch in whitespace and not in_quotes: <NEW_LINE> <INDENT> if arg: <NEW_LINE> <INDENT> argv.append(''... | Build an argv list from a Microsoft shell style cmdline str.
The reverse of subprocess.list2cmdline that follows the same MS C runtime rules.
Borrowed from Jython source code:
https://github.com/jython/jython/blob/50729e6/Lib/subprocess.py#L668-L722 | 625941c5adb09d7d5db6c78f |
def __init__(self, tag): <NEW_LINE> <INDENT> self._tag = tag <NEW_LINE> self._cells = [Cell(td) for td in tag.find_all('td')] | Initialise the object. | 625941c5091ae35668666f60 |
def __add_loss_summaries(self, total_loss): <NEW_LINE> <INDENT> loss_averages = tf.train.ExponentialMovingAverage(0.9, name='avg') <NEW_LINE> losses = tf.get_collection('losses') <NEW_LINE> loss_averages_op = loss_averages.apply(losses + [total_loss]) <NEW_LINE> for l in losses + [total_loss]: <NEW_LINE> <INDENT> tf.co... | Add summaries for losses in CIFAR-10 model.
Generates moving average for all losses and associated summaries for visualizing the performance of the network.
:param total_loss: Total loss from loss().
:return: op for generating moving averages of losses. | 625941c50c0af96317bb81e7 |
def _convertPitchClassToStr(pc): <NEW_LINE> <INDENT> pc = pc % 12 <NEW_LINE> return '%X' % pc | Given a pitch class number, return a string.
>>> pitch._convertPitchClassToStr(3)
'3'
>>> pitch._convertPitchClassToStr(10)
'A' | 625941c5f548e778e58cd57c |
def scale(self, type=None, option='old', bscale=1, bzero=0): <NEW_LINE> <INDENT> if self.data is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if type is None: <NEW_LINE> <INDENT> type = self.NumCode[self._bitpix] <NEW_LINE> <DEDENT> _type = getattr(np, type) <NEW_LINE> if (bscale != 1 or bzero != 0): <NEW_LINE>... | Scale image data by using ``BSCALE``/``BZERO``.
Call to this method will scale `data` and update the keywords
of ``BSCALE`` and ``BZERO`` in `_header`. This method should
only be used right before writing to the output file, as the
data will be scaled and is therefore not very usable after the
call.
Parameters
-----... | 625941c557b8e32f52483499 |
def acq_request_step1(self, req, form): <NEW_LINE> <INDENT> argd = wash_urlargd(form, {'type': (str, 'acq-book'), 'title': (str, ''), 'authors': (str, ''), 'place': (str, ''), 'publisher': (str, ''), 'year': (str, ''), 'edition': (str, ''), 'this_edition_only': (str, 'No'), 'isbn': (str, ''), 'standard_number': (str, '... | Displays all loans of a given user
@param ln: language
@return the page for inbox | 625941c523e79379d52ee564 |
def __init__(self, mqType=''): <NEW_LINE> <INDENT> self.mqType = mqType <NEW_LINE> self.log = gLogger.getSubLogger( self.mqType ) | Standard constructor
| 625941c5ff9c53063f47c1f3 |
def op_check(file_in): <NEW_LINE> <INDENT> ops_click = [0] * 2 <NEW_LINE> user_num = [0] * 2 <NEW_LINE> average_click = [0] * 2 <NEW_LINE> with open(file_in[0], 'rb') as f_op, open(file_in[1], 'rb') as f_label: <NEW_LINE> <INDENT> user_ops = pickle.load(f_op) <NEW_LINE> user_label = pickle.load(f_label) <NEW_LINE> for ... | 流失玩家和非流失玩家的平均点击量 | 625941c5d18da76e235324d4 |
def ew_vol(series, theta = 0.94, freq = 'daily'): <NEW_LINE> <INDENT> span = (1. + theta)/(1 - theta) <NEW_LINE> log_rets = log_returns(series) <NEW_LINE> fac = _interval_to_factor(freq) <NEW_LINE> ew_vol = pandas.ewmstd(log_rets, span = span, min_periods = span ) <NEW_LINE> return ew_vol*numpy.sqrt(fac) | Returns the exponentially weighted, annualized standard deviation
:ARGS:
series: :class:`Series` or :class:`DataFrame` of prices
theta: coefficient of decay, default BARRA's value of .94
which roughly equates to a span of 33 days
freq: :class:`string` of either ['daily', 'monthly', 'quarterly',
... | 625941c5cc0a2c11143dce90 |
def build(self, docnames, summary=None, method='update'): <NEW_LINE> <INDENT> if summary: <NEW_LINE> <INDENT> self.info(bold('building [%s]: ' % self.name), nonl=1) <NEW_LINE> self.info(summary) <NEW_LINE> <DEDENT> updated_docnames = set() <NEW_LINE> warnings = [] <NEW_LINE> self.env.set_warnfunc(lambda *args: warnings... | Main build method. First updates the environment, and then
calls :meth:`write`. | 625941c5adb09d7d5db6c790 |
def adjust_learning_rate(optimizer, epoch, learning_rate): <NEW_LINE> <INDENT> if learning_rate <= 1e-5: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> lr = learning_rate * (0.1 ** (epoch // 5000)) <NEW_LINE> for param_group in optimizer.param_groups: <NEW_LINE> <INDENT> param_group['lr'] = lr | Sets the learning rate to the initial LR decayed by 10 every 30 epochs | 625941c5bde94217f3682df2 |
def osm_json(file_in, pretty = False, isWrapInArray=True): <NEW_LINE> <INDENT> file_out = "{0}.json".format(file_in) <NEW_LINE> with codecs.open(file_out, "w") as fo: <NEW_LINE> <INDENT> if (isWrapInArray): <NEW_LINE> <INDENT> fo.write("[\n") <NEW_LINE> <DEDENT> i = 0 <NEW_LINE> for _, element in ET.iterparse(file_in):... | Transforms osm file into JSON file
if pretty = True then a nice looking indent will be added
NOTE: set pretty = False to produce a file for MongoDB load. | 625941c5d99f1b3c44c67590 |
def decode(self) -> str: <NEW_LINE> <INDENT> return ''.join(self.factorize()) | 元のテキストを復元して返します | 625941c5187af65679ca511e |
def return_seq_dict_from_fasta(fasta_file): <NEW_LINE> <INDENT> from Bio import SeqIO <NEW_LINE> handle = open(fasta_file, "rU") <NEW_LINE> record_dict = SeqIO.to_dict(SeqIO.parse(handle, "fasta")) <NEW_LINE> handle.close() <NEW_LINE> return record_dict | Usage: Return A Seq Dictionary, keyed on record.id | 625941c5d6c5a10208144049 |
def remove_site_user_with_http_info(self, id, user_id, **kwargs): <NEW_LINE> <INDENT> all_params = ['id', 'user_id'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_LIN... | Site User Access # noqa: E501
Removes the specified user from the site's access list. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_site_user_with_http_info(id, user_id, async_req=True)
>>> result = threa... | 625941c57b25080760e39459 |
def _on_console_visible_changed(self, flag): <NEW_LINE> <INDENT> self._output_console.setVisible(flag) | Internal callback function that is called when console visibility is changed in the model
:param flag: bool | 625941c5ff9c53063f47c1f4 |
def reinit(self): <NEW_LINE> <INDENT> pass | Reinitialise the object, called by :meth:`Network.reinit`. | 625941c5596a897236089ac2 |
def raw_extract(arq): <NEW_LINE> <INDENT> f = open(arq, 'r') <NEW_LINE> t = f.readlines() <NEW_LINE> f.close() <NEW_LINE> infos = re.compile("[0-9]{2}[A-Z]{3}[0-9]{4}") <NEW_LINE> gain = re.compile("[A-Z]{4}", flags=re.I) <NEW_LINE> comments = re.compile("^%") <NEW_LINE> comments2 = re.compile(";") <NEW_LINE> header = ... | Parse raw data obtained with Phyto-Pam.
This raw data is an .rpt file containing
values of curves records, and other useful
informations.
Parameters
----------
arq: str
opened csv file
Returns
-------
curves : arr
Store the "Rapid Light Curves".
pulses : arr
Saturated light pulses. | 625941c560cbc95b062c6542 |
def test_change_max_dist(self): <NEW_LINE> <INDENT> cg = CellGrid(box=np.ones(3), cellsize=0.25) <NEW_LINE> assert all(cg._cell_size == np.array([0.25, 0.25, 0.25])) <NEW_LINE> assert all(cg._ncells == np.array([4, 4, 4])) <NEW_LINE> assert cg._total_cells == 64 <NEW_LINE> assert len(cg) == 64 <NEW_LINE> cg.cellsize = ... | Redefine max dist | 625941c52eb69b55b151c8ad |
def memo_add_names(self, channel): <NEW_LINE> <INDENT> if self.gui.memoTabWindow: <NEW_LINE> <INDENT> self.gui.memoTabWindow.add_names(channel, self.names_list[channel]) | Add names in | 625941c501c39578d7e74e3b |
def get_num_huge_pages(session=None): <NEW_LINE> <INDENT> return read_from_meminfo('HugePages_Total', session=session) | Method to get total no of hugepages
:param session: ShellSession Object of remote host / guest | 625941c556b00c62f0f14658 |
def frontiere_3d(f,data,step=20): <NEW_LINE> <INDENT> ax=plt.gca(projection='3d') <NEW_LINE> xmin,xmax=data[:,0].min() -1, data[:,0].max()+1 <NEW_LINE> ymin,ymax=data[:,1].min() -1, data[:,1].max()+1 <NEW_LINE> xx,yy=np.meshgrid(np.arange(xmin,xmax,(xmax-xmin)*1./step), np.arange(ymin,ymax,(ymax-ymin)*1./step)) <NEW_LI... | plot the 3d frontiere for the decision function ff | 625941c5b545ff76a8913e16 |
def new_game(self): <NEW_LINE> <INDENT> images = 2 * random.sample(list(Image.objects.all()), Game.NUMBER_OF_PAIRS) <NEW_LINE> random.shuffle(images) <NEW_LINE> self.status = Game.STATUS_NO_CARD_SHOWN <NEW_LINE> self.players.update(score=0) <NEW_LINE> self.current_player = random.choice(self.players.all()) <NEW_LINE> s... | reset the cards used in the game
clears the cards used for the game and sets up random cards in pairs | 625941c5a17c0f6771cbe051 |
def has_wall(self, direction): <NEW_LINE> <INDENT> return self.walls[direction] != WALL_NONE | Returns True if we have a wall of *any* type | 625941c58a43f66fc4b54066 |
def add_epics_version_flag(self, help_msg="Change the epics version, " "default is " + env.epicsVer() + " (from your environment)"): <NEW_LINE> <INDENT> self.add_argument("-e", "--epics_version", action="store", type=str, dest="epics_version", default=env.epicsVer(), help=help_msg) | Add epics version flag argument with module specific help message.
Args:
help_msg(str): Help message relevant to module calling function | 625941c585dfad0860c3ae5a |
def coding_problem_01(stack): <NEW_LINE> <INDENT> pass | Given a stack of N elements, interleave the first half of the stack
with the second half reversed using one other queue.
Example:
>>> coding_problem_01([1, 2, 3, 4, 5])
[1, 5, 2, 4, 3]
>>> coding_problem_01([1, 2, 3, 4, 5, 6])
[1, 6, 2, 5, 3, 4]
Note: with itertools, you could instead islice(chain.from_iterable(izip(... | 625941c54a966d76dd55100e |
def html_uencode(text, pattern=_uescape): <NEW_LINE> <INDENT> if not text: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if type(text) is not UnicodeType: <NEW_LINE> <INDENT> text = str(text, "utf-8") <NEW_LINE> <DEDENT> <DEDENT> except (ValueError, LookupError): <NEW_LINE> <INDENT> pass <... | Function to correctly encode a unicode text for html.
@param text text to be encoded (string)
@param pattern search pattern for text to be encoded (string)
@return the encoded text (string) | 625941c5eab8aa0e5d26db58 |
def surftAttrbs(self,nsize): <NEW_LINE> <INDENT> dataStr = cl.OrderedDict() <NEW_LINE> dataStr['VAR_NAME'] = self.getSurfaceTemperatureIndependentName() <NEW_LINE> dataStr['VAR_DESCRIPTION'] = 'Daily average temperature at ground level measured at the observation site' <NEW_LINE> dataStr['VAR_NOTES'] ... | Attributes for instrument surface temperature variable | 625941c57cff6e4e81117986 |
def set_zoom_range(self,zoom_parm,defaults=(0,22)): <NEW_LINE> <INDENT> if not zoom_parm: <NEW_LINE> <INDENT> zoom_parm='%d:%d' % defaults <NEW_LINE> <DEDENT> zchunk_lst=[z.split(':') for z in zoom_parm.split(',')] <NEW_LINE> zlist=[] <NEW_LINE> for zchunk in zchunk_lst: <NEW_LINE> <INDENT> if len(zchunk) == 1: <NEW_LI... | set a list of zoom levels from a parameter list | 625941c5be383301e01b5489 |
def process_log_file(cur, filepath): <NEW_LINE> <INDENT> df = pd.read_json(filepath, lines=True) <NEW_LINE> df = df[df.get('page') == 'NextSong'] <NEW_LINE> t = pd.to_datetime(df.get('ts'), unit='ms') <NEW_LINE> time_data = ([t,t.dt.hour, t.dt.day, t.dt.weekofyear, t.dt.month, t.dt.year, t.dt.weekday]) <NEW_LINE> colum... | Description:This function used to read all the files in the filepath folder (data/log_data)
this will get the user and time data and used to populate in the USERS and TIME tables
Arguments:
cur: the cursor object.
filepath: file path for song_data API file (json).
Returns:
None | 625941c54e4d5625662d43da |
def from_model(model): <NEW_LINE> <INDENT> if isinstance(model, ProbabilisticModel): <NEW_LINE> <INDENT> input_parameters = InputConnector(model.get_output_dimension()) <NEW_LINE> for i in range(model.get_output_dimension()): <NEW_LINE> <INDENT> input_parameters.set(i, model, i) <NEW_LINE> <DEDENT> return input_paramet... | Convenient initializer that converts the full output of a model to input parameters.
Parameters
----------
ProbabilisticModel
Returns
-------
InputConnector | 625941c54f6381625f114a3c |
def upload (self, file_name, data): <NEW_LINE> <INDENT> code = pkb.filedownload(self.socket, self.logger_id, self.cpu_id, file_name, data, self.security_code) <NEW_LINE> return True if code == 0 else False | Function doc | 625941c5ac7a0e7691ed40cf |
def employment_details(request, employment_id): <NEW_LINE> <INDENT> detail = Employment.objects.get(pk=employment_id) <NEW_LINE> linkman = Contacts.objects.values('telephone', 'QQ').get(name=detail.contacts) <NEW_LINE> content = { 'active_menu': 'employment', 'company_purpose': COMPANY_PURPOSE, 'employ': detail, 'linkm... | 招聘详细信息 | 625941c5f9cc0f698b1405fd |
def _wrapper(func): <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def _inner(*args, **kwargs): <NEW_LINE> <INDENT> res = func(*args, **kwargs) <NEW_LINE> if isinstance(res, str): <NEW_LINE> <INDENT> return web.Response(text=res, content_type='text/xml') <NEW_LINE> <DEDENT> elif isinstance(res, int): <NEW_LINE> ... | Wrap an aiohttp view function so it can just return a string or integer | 625941c57d847024c06be2ba |
def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'): <NEW_LINE> <INDENT> if isinstance(s, bytes): <NEW_LINE> <INDENT> if encoding == 'utf-8': <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return s.decode('utf-8', errors).encode(encoding, errors) <NEW_LINE> <DEDENT> <DE... | Return a bytestring version of ``s``, encoded as specified in
``encoding``.
If strings_only is True, don't convert (some) non-string-like objects. | 625941c58c3a8732951583b9 |
def ParseResourceLabels(self, options, cluster): <NEW_LINE> <INDENT> if options.labels is not None: <NEW_LINE> <INDENT> labels = self.messages.Cluster.ResourceLabelsValue() <NEW_LINE> props = [] <NEW_LINE> for k, v in sorted(six.iteritems(options.labels)): <NEW_LINE> <INDENT> props.append(labels.AdditionalProperty(key=... | Parses resource labels options for the cluster. | 625941c555399d3f055886b3 |
def test_favorite_view_post(self): <NEW_LINE> <INDENT> self.req.force_login(self.user) <NEW_LINE> img = models.Image.objects.create(url="example.com", license="CC0") <NEW_LINE> self.assertEqual(0, models.Favorite.objects.filter(user=self.user, image=img).count()) <NEW_LINE> resp = self.req.post('/api/v1/images/favorite... | The Favorite POST view should create a new Favorite object when a user requests it | 625941c5851cf427c661a510 |
def __closewin(self): <NEW_LINE> <INDENT> self.path = self.sto_path.get() <NEW_LINE> self.window.destroy() <NEW_LINE> self.window = MainWindow(self.lang, self.path) | !
A method for closing the window and opening the main window.
@todo give RPG type to main window | 625941c592d797404e30418a |
def test_set_context_wrong_args(self): <NEW_LINE> <INDENT> ctx = Context(TLSv1_2_METHOD) <NEW_LINE> connection = Connection(ctx, None) <NEW_LINE> self.assertRaises(TypeError, connection.set_context) <NEW_LINE> self.assertRaises(TypeError, connection.set_context, object()) <NEW_LINE> self.assertRaises(TypeError, connect... | :py:obj:`Connection.set_context` raises :py:obj:`TypeError` if called with a
non-:py:obj:`Context` instance argument or with any number of arguments other
than 1. | 625941c510dbd63aa1bd2ba4 |
def test_only_silent(self): <NEW_LINE> <INDENT> SearchFilterChain._load_filters() <NEW_LINE> res_json = self.get_spots_for_noise_levels(['silent']) <NEW_LINE> self.assertResponseSpaces(res_json, [self.silent_spot]) | Searching for silent should return only silent | 625941c5046cf37aa974cd49 |
def __init__( self, *, credentials: ga_credentials.Credentials = None, transport: Union[str, CompanyServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: <NEW_LINE> <INDENT> self._client = CompanyServiceClient( credential... | Instantiates the company service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
... | 625941c50c0af96317bb81e8 |
def Sort(self, startIndex, endIndex): <NEW_LINE> <INDENT> for i in xrange(startIndex, endIndex): <NEW_LINE> <INDENT> correctIndex = self.getAppropriateIndex(startIndex, i) <NEW_LINE> self.swapInto(i, correctIndex) | Insertion sort implementation. This algorithm
works by sorting a portion of the array, say i elements,
and inserts the i+1th element into the already sorted part.
Sorts elements with indexes i, startIndex <= i < endIndex | 625941c550485f2cf553cd99 |
def _test_mnt(self, pseudo_path, port, ip, check=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.ctx.cluster.run(args=['sudo', 'mount', '-t', 'nfs', '-o', f'port={port}', f'{ip}:{pseudo_path}', '/mnt']) <NEW_LINE> <DEDENT> except CommandFailedError as e: <NEW_LINE> <INDENT> if not check and e.exitstatus == 32:... | Test mounting of created exports
:param pseudo_path: It is the pseudo root name
:param port: Port of deployed nfs cluster
:param ip: IP of deployed nfs cluster
:param check: It denotes if i/o testing needs to be done | 625941c555399d3f055886b4 |
def get_given_user_followers(browser, login, user_name, amount, dont_include, randomize, blacklist, follow_times, simulation, logger, logfolder): <NEW_LINE> <INDENT> user_name = user_name.strip() <NEW_LINE> browser.get('https://www.instagram.com/{}/'.format(user_name)) <NEW_LINE> update_activity() <NEW_LINE> try: <NEW_... | For the given username, follow their followers.
:param browser: webdriver instance
:param login:
:param user_name: given username of account to follow
:param amount: the number of followers to follow
:param dont_include: ignore these usernames
:param random: randomly select from users' followers
:param blacklist:
:par... | 625941c5d486a94d0b98e145 |
def add_two(num): <NEW_LINE> <INDENT> return num + 2 | Add two to the number passed in. | 625941c56fb2d068a760f09c |
def remove(self, key: KeyType, value: ValueType) -> Future[bool]: <NEW_LINE> <INDENT> check_not_none(key, "key can't be None") <NEW_LINE> check_not_none(key, "value can't be None") <NEW_LINE> key_data = self._to_data(key) <NEW_LINE> value_data = self._to_data(value) <NEW_LINE> request = multi_map_remove_entry_codec.enc... | Removes the given key-value tuple from the multimap.
Warning:
This method uses ``__hash__`` and ``__eq__`` methods of binary form
of the key, not the actual implementations of ``__hash__`` and
``__eq__`` defined in key's class.
Args:
key: The key of the entry to remove.
value: The value of the ent... | 625941c54527f215b584c459 |
def getSecret(self, id=0): <NEW_LINE> <INDENT> log.debug('getSecret()') <NEW_LINE> id = int(id) <NEW_LINE> if self.crypted: <NEW_LINE> <INDENT> if self.secrets.has_key(id): <NEW_LINE> <INDENT> return self.secrets.get(id) <NEW_LINE> <DEDENT> <DEDENT> secret = '' <NEW_LINE> try: <NEW_LINE> <INDENT> f = open(self.secFile)... | internal function, which acceses the key in the defined slot
:param id: slot id of the key array
:type id: int
:return: key or secret
:rtype: binary string | 625941c573bcbd0ca4b2c077 |
def GetInterfaces(self): <NEW_LINE> <INDENT> res = [] <NEW_LINE> for _, interface in sorted(self._all_interfaces.items()): <NEW_LINE> <INDENT> res.append(interface) <NEW_LINE> <DEDENT> return res | Returns a list of all loaded interfaces. | 625941c5b7558d58953c4f17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.