code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def setControl( self, request_type, request, value, index, buffer_or_len, callback=None, user_data=None, timeout=0): <NEW_LINE> <INDENT> if self.__submitted: <NEW_LINE> <INDENT> raise ValueError('Cannot alter a submitted transfer') <NEW_LINE> <DEDENT> if self.__doomed: <NEW_LINE> <INDENT> raise DoomedTransferError('Can... | Setup transfer for control use.
request_type, request, value, index
See USBDeviceHandle.controlWrite.
request_type defines transfer direction (see
ENDPOINT_OUT and ENDPOINT_IN)).
buffer_or_len
Either a string (when sending data), or expected data length (when
receiving data).
callback
Callback ... | 625941c35510c4643540f3b3 |
def __init__( self, dataset, chrom_column=None, start_column=None, end_column=None, named_columns=False, **kwargs ): <NEW_LINE> <INDENT> dataset_source = DatasetDataProvider( dataset ) <NEW_LINE> if chrom_column == None: <NEW_LINE> <INDENT> chrom_column = dataset_source.get_metadata_column_index_by_name( 'chromCol' ) <... | :param dataset: the Galaxy dataset whose file will be the source
:type dataset: model.DatasetInstance
:param chrom_column: optionally specify the chrom column index
:type chrom_column: int
:param start_column: optionally specify the start column index
:type start_column: int
:param end_column: optionally specify the e... | 625941c3ab23a570cc25014b |
def get_action(self, t, observation, policy, **kwargs): <NEW_LINE> <INDENT> opt_action = policy.get_action(observation) <NEW_LINE> self._decay() <NEW_LINE> if np.random.random() < self._epsilon: <NEW_LINE> <INDENT> opt_action = self._action_space.sample() <NEW_LINE> <DEDENT> return opt_action | Get action from this policy for the input observation.
Args:
t: Iteration.
observation: Observation from the environment.
policy: Policy network to predict action based on the observation.
Returns:
opt_action: optimal action from this policy. | 625941c33eb6a72ae02ec4a3 |
def do_iteration(self): <NEW_LINE> <INDENT> kw = {'q': self.query, 'count': self.count} <NEW_LINE> if self.since_id is not None: <NEW_LINE> <INDENT> kw['since_id'] = self.since_id <NEW_LINE> <DEDENT> tweets = self.connection.search.tweets(**kw) <NEW_LINE> last_id = self.since_id or 0 <NEW_LINE> for status in tweets['st... | Search for a specific number of tweets, maintain `self.since_id`,
call `print_tweet` accordingly. | 625941c37b180e01f3dc47cb |
def initialize(self): <NEW_LINE> <INDENT> raise NotImplementedError('%r must implement initialize()' % self.__class__) | Initialize the integration.
Integration implementation subclasses must override this to provide
any initialization needed for the integration, including signal and
hook registration.
This should only be called from :py:meth:`enable_integration`. | 625941c3851cf427c661a4db |
def test_changue_group_with_login(self): <NEW_LINE> <INDENT> data = {'name': 'Test2'} <NEW_LINE> client = APIClient() <NEW_LINE> client.login(username=self.user.username, password=self.user.username) <NEW_LINE> group = Group.objects.get(name="Test") <NEW_LINE> url = reverse('groups_detail_api', args=(group.id,)) <NEW_L... | Changue group name with login | 625941c376e4537e8c35163b |
def remSuperSet(KB): <NEW_LINE> <INDENT> index = 0 <NEW_LINE> for clause in KB: <NEW_LINE> <INDENT> index = index + 1; <NEW_LINE> for x in KB[index:len(KB)]: <NEW_LINE> <INDENT> sub = 1 <NEW_LINE> for literal in clause: <NEW_LINE> <INDENT> if literal not in x: <NEW_LINE> <INDENT> sub = 0 <NEW_LINE> break <NEW_LINE> <DE... | Removes sets from KB if there are subsets also in the KB | 625941c34a966d76dd550fd9 |
def game(self,player1,player2="computador",version=1): <NEW_LINE> <INDENT> return self.jugar(player1,player2,version,"en") | Play a NIM game starting in the current state of this NIM.
player1 and player2 are the names of the player, if any of
them if is "computador" or "computadora" the AI play instead
version: is the version of the NIM game to play | 625941c315baa723493c3f3e |
def attr_getter(obj, attr): <NEW_LINE> <INDENT> return obj.get(attr) | Return the attribute value of an individual DOM node.
Parameters
----------
obj : node-like
A DOM node.
attr : str or unicode
The attribute, such as "colspan"
Returns
-------
str or unicode
The attribute value. | 625941c3adb09d7d5db6c75b |
def make_DFA(r): <NEW_LINE> <INDENT> def explore(q): <NEW_LINE> <INDENT> for S in C(q): <NEW_LINE> <INDENT> goto(q, S) <NEW_LINE> <DEDENT> <DEDENT> def goto(q, S): <NEW_LINE> <INDENT> if S: <NEW_LINE> <INDENT> c = S.any_member() <NEW_LINE> qc = d(q, c) <NEW_LINE> if qc in Q: <NEW_LINE> <INDENT> δ[q, S] = qc <NEW_LINE> ... | r may be a RE or a sequence of REs. | 625941c3ec188e330fd5a76d |
def read_tree(tree_root): <NEW_LINE> <INDENT> tree = {} <NEW_LINE> for root, dirs, files in os.walk(tree_root): <NEW_LINE> <INDENT> for d in filter(lambda x: x.startswith('.'), dirs): <NEW_LINE> <INDENT> dirs.remove(d) <NEW_LINE> <DEDENT> for f in [join(root, f) for f in files if not f.startswith('.')]: <NEW_LINE> <IND... | Returns a dict of all the files in a tree. Defaults to self.root_dir. | 625941c3796e427e537b058f |
def test_object_get_by_singletag(self): <NEW_LINE> <INDENT> t1 = self.test_model.objects.get(singletag="Mrs") <NEW_LINE> self.assertEqual(t1.pk, self.o2.pk) | Check that object.get singletag loads the item correctly | 625941c323849d37ff7b305b |
def _changeDirectoryParameter(self, paths, directoryFunction, fileFunction, recursive=False): <NEW_LINE> <INDENT> arguments = paths <NEW_LINE> successful = {} <NEW_LINE> failed = {} <NEW_LINE> for path, attribute in arguments.items(): <NEW_LINE> <INDENT> result = directoryFunction(path, attribute) <NEW_LINE> if not res... | Bulk setting of the directory parameter with recursion for all the subdirectories and files
:param dictionary paths: dictionary < lfn : value >, where value is the value of parameter to be set
:param function directoryFunction: function to change directory(ies) parameter
:param function fileFunction: function to chang... | 625941c3a8ecb033257d3098 |
def bufferKeyEventMapper(self, key): <NEW_LINE> <INDENT> self.keyPressBuffer = self.appendDelimitedStr(key, self.keyPressBuffer, Qt.Key_Escape, ',') <NEW_LINE> bufferKeyEvent = {'details': self.keyMap['BUFFER_COMMANDS'].get( self.keyPressBuffer, False), 'key': key} <NEW_LINE> if not bufferKeyEvent['details'] or ... | Takes in the key event and determines what function should be called
in order to handle said event if we are attempting to cut/copy.
@arg int key integer value of the key pressed, used to determine the
appropriate handler
@ret mixed success Returns the exit status of the event handler (True or False) or
it re... | 625941c326068e7796caeca6 |
def get_checkboxes(self): <NEW_LINE> <INDENT> checks = [] <NEW_LINE> for i in range(len(self.liststore)): <NEW_LINE> <INDENT> checks.append(self.liststore[i][0]) <NEW_LINE> <DEDENT> return checks | Get the state of all checkboxes.
@return: A list with True or False according checkbox state.
@rtype: A List. | 625941c315baa723493c3f3f |
def DescribeChannels(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("DescribeChannels", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.DescribeChannelsResponse() ... | 本接口(DescribeChannels)用于获取设备下属通道列表
:param request: Request instance for DescribeChannels.
:type request: :class:`tencentcloud.iotvideoindustry.v20201201.models.DescribeChannelsRequest`
:rtype: :class:`tencentcloud.iotvideoindustry.v20201201.models.DescribeChannelsResponse` | 625941c33539df3088e2e316 |
def lowercase_dict(dictionary: dict) -> dict: <NEW_LINE> <INDENT> if not isinstance(dictionary, dict): <NEW_LINE> <INDENT> raise TypeError(f'Expected a dictionary, got a {type(dictionary)}') <NEW_LINE> <DEDENT> new_dict = dict() <NEW_LINE> for key, val in dictionary.items(): <NEW_LINE> <INDENT> new_key = key.lower() if... | Convert all string keys and values in a dictionary to lowercase.
Args:
dictionary (dict): A dictionary to process.
Raises:
TypeError: If ``dictionary`` is not a ``dict`` instance.
Returns:
dict: A dictionary with all string keys and values lowercase. | 625941c3e1aae11d1e749c80 |
def calc_breakeven_prob(vig, n, cutoff = .01, tol=1e-4): <NEW_LINE> <INDENT> prob = .5 <NEW_LINE> h = .25 <NEW_LINE> dfProb = make_df_prob(prob) <NEW_LINE> weights, obj = optimal_bet_given_same_probs(dfProb, n, vig) <NEW_LINE> while (abs(obj - cutoff) > tol): <NEW_LINE> <INDENT> if (obj - cutoff > 0): <NEW_LINE> <INDEN... | calc_breakeven_prob calculates the probability you need to win a given bet in order to expect a certain level of compensation as a function of the vig
INPUTS:
vig: float, expressed as a decimal, percent the house takes of your money
n: number of bets you can make in a given period
cutoff: amount you need to... | 625941c330dc7b7665901933 |
def __create_tool(self, section): <NEW_LINE> <INDENT> tool_config = defaultdict(str) <NEW_LINE> if not self.__parse_tool_options(section, tool_config): return None <NEW_LINE> if not self.__parse_tool_install_status(tool_config): return None <NEW_LINE> return Tool( tool_config['name_clean'], tool_config['name'], tool_... | Create a Tool object
:param section: Tool section into the toolbox settings file
:return: The created Tool instance | 625941c3d486a94d0b98e110 |
def insert(self, word: str) -> None: <NEW_LINE> <INDENT> t = self.trie <NEW_LINE> for c in word: <NEW_LINE> <INDENT> if c not in t: <NEW_LINE> <INDENT> t[c] = {} <NEW_LINE> <DEDENT> t = t[c] <NEW_LINE> <DEDENT> t['#'] = '#' | Inserts a word into the trie. | 625941c3ad47b63b2c509f4a |
def plot_times(data): <NEW_LINE> <INDENT> plt.figure() <NEW_LINE> times = [] <NEW_LINE> for line in data: <NEW_LINE> <INDENT> times.append(line[2]) <NEW_LINE> <DEDENT> bins = np.linspace(500, 900, 9) <NEW_LINE> n, bins, patches = plt.hist(times, bins, range=(500, 900), facecolor='green', alpha=0.75) <NEW_LINE> plt.xlab... | Plots histograms out of a data set | 625941c376e4537e8c35163c |
@cache_control(public=True) <NEW_LINE> @cache_page(1 * 60) <NEW_LINE> def index(request): <NEW_LINE> <INDENT> return render(request, 'stats/index.html') | Index page of Gentoostats. | 625941c396565a6dacc8f696 |
def set_protected(self, protected: bool=True) -> 'Stream': <NEW_LINE> <INDENT> self.protected = protected <NEW_LINE> return self | Set the stream to listed or protected (must not be set) | 625941c315fb5d323cde0ad8 |
def p_constants_empty(subexpressions): <NEW_LINE> <INDENT> pass | constants : | 625941c3498bea3a759b9a7a |
def not_found(_): <NEW_LINE> <INDENT> return jsonify({ 'name': 'NotFound', 'message': 'Resource Not Found', 'status': HTTPStatus.NOT_FOUND }), HTTPStatus.NOT_FOUND | Handles the not found errors.
Args:
error: the error object.
Returns:
An JSON representation of the error. | 625941c3596a897236089a8d |
def construct_keyword_graph(keyword_dir): <NEW_LINE> <INDENT> keyword_dict = read_keyword_dir(keyword_dir) <NEW_LINE> keyword2id = {} <NEW_LINE> rev_keyword2id = {} <NEW_LINE> keyword_graph = nx.Graph() <NEW_LINE> idx = 0; <NEW_LINE> for doc, keyword_list in keyword_dict.items(): <NEW_LINE> <INDENT> for keyword, _ in k... | Construct keyword graph with sharing documents as edges.
keyword_i and keyword_j will have shared edges with weight
equals to the summation over sharing documents.
(keyword_i weight in doc * keyword_j weight in doc)
Returns:
keyword2id: map keyword to id
rev_keyword2id: map id to keyword
keyword_graph: keyword-k... | 625941c36aa9bd52df036d6e |
def Gibbs_trisH(log_kt_trisH, log_ks_trisH, log_acfs, log_aH2O): <NEW_LINE> <INDENT> return ( log_acfs["tris"] + log_acfs["H"] - log_acfs["trisH"] + log_ks_trisH - log_kt_trisH ) | Evaluate the Gibbs energy for the tris-trisH+ equilibrium. | 625941c3d99f1b3c44c6755c |
def checkHandForAces(self): <NEW_LINE> <INDENT> for card in self.hand: <NEW_LINE> <INDENT> if self.getHandValue() > 21 and card.rank == "Ace": <NEW_LINE> <INDENT> card.value = 1 | If hand contains aces and ahdn value > 21, change ace value to 1 | 625941c3b57a9660fec3384d |
def do_qq(self, arg): <NEW_LINE> <INDENT> arg = arg.strip().split() <NEW_LINE> try: <NEW_LINE> <INDENT> symbol = arg[0].upper() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print("Please check arguments again. Format: ") <NEW_LINE> print("Stock: q <symbol>") <NEW_LINE> print("Option: q <symbol> <call/put> <strike> <... | Get quote for stock q <symbol> or option q <symbol> <call/put> <strike> <(optional) YYYY-mm-dd> | 625941c3d268445f265b4e39 |
def matrix_sub (A,B): <NEW_LINE> <INDENT> return [ a-b for a,b in zip(A,B) ]; | Subtracts two matrices given as a flat 4-list | 625941c3e64d504609d7480b |
def public_net_mask(self): <NEW_LINE> <INDENT> return str(IPNetwork(self.environment().network_by_name('public').ip_network).netmask) | Get public netmask. | 625941c3656771135c3eb838 |
def extract_teachers(timetable): <NEW_LINE> <INDENT> added_teachers = set() <NEW_LINE> teachers = [] <NEW_LINE> for lesson in timetable: <NEW_LINE> <INDENT> for teacher in lesson['teachers']: <NEW_LINE> <INDENT> key = teacher['full_name'] <NEW_LINE> if key in added_teachers: <NEW_LINE> <INDENT> continue <NEW_LINE> <DED... | Extracts unique teachers from a timetable | 625941c376d4e153a657eafb |
def __init__(self, domain_mapper, mode='classification', class_names=None, random_state=None): <NEW_LINE> <INDENT> self.random_state = random_state <NEW_LINE> self.mode = mode <NEW_LINE> self.domain_mapper = domain_mapper <NEW_LINE> self.local_exp = {} <NEW_LINE> self.intercept = {} <NEW_LINE> self.score = None <NEW_LI... | Initializer.
Args:
domain_mapper: must inherit from DomainMapper class
type: "classification" or "regression"
class_names: list of class names (only used for classification)
random_state: an integer or numpy.RandomState that will be used to
generate random numbers. If None, the random state wil... | 625941c3009cb60464c6337e |
def _process_file_element(file_element): <NEW_LINE> <INDENT> file_info = deepcopy(FILE_INFO_SKEL) <NEW_LINE> file_info['path'] = file_element.text <NEW_LINE> return file_info | Process a parsed file element (child element of the files element) into a
file information dictionary.
:param file_element: parsed file element
:return: file information dictionary
:rtype: dict | 625941c38e71fb1e9831d775 |
def getUrl(self): <NEW_LINE> <INDENT> return self.url | Return the project URL, e.g. https://bitbucket.org/petsc/petsc-dev | 625941c3004d5f362079a2ff |
@contextmanager <NEW_LINE> def cleared(lcd): <NEW_LINE> <INDENT> warnings.warn('The `cursor` context manager is deprecated', DeprecationWarning) <NEW_LINE> lcd.clear() <NEW_LINE> yield | Context manager to clear display before writing. DEPRECATED. | 625941c366656f66f7cbc175 |
def closest_point2d_on_arc2d(point, arc): <NEW_LINE> <INDENT> v = point - arc.c <NEW_LINE> v = v.normalize() * arc.r <NEW_LINE> if arc.is_circle: <NEW_LINE> <INDENT> return Point2D(arc.c.x + v.x, arc.c.y + v.y) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> a = Vector2D(1, 0).angle_counterclockwise(v) <NEW_LINE> if (not... | Get the closest Point2D on a Arc2D to the input point.
Args:
point: A Point2D object.
arc: An Arc2D object along which the closest point will be determined.
Returns:
Point2D for the closest point on arc to point. | 625941c350812a4eaa59c2ee |
def book_air_segment(token, trip): <NEW_LINE> <INDENT> env = Environment(loader=PackageLoader('sabre', 'templates')) <NEW_LINE> context = { "PCC": "PPC", "EMAIL": settings.EMAIL_HOST_USER, "TOKEN": token, "TRIP": trip } <NEW_LINE> template = env.get_template('book_air_segment.xml') <NEW_LINE> soap_req = template.render... | Sends xml-formatted SOAP request to book a flight with Sabre | 625941c38a43f66fc4b54032 |
def BreakpointCreateByRegex(self, *args): <NEW_LINE> <INDENT> return _lldb.SBTarget_BreakpointCreateByRegex(self, *args) | BreakpointCreateByRegex(self, str symbol_name_regex, str module_name = None) -> SBBreakpoint
BreakpointCreateByRegex(self, str symbol_name_regex) -> SBBreakpoint
BreakpointCreateByRegex(self, str symbol_name_regex, LanguageType symbol_language,
SBFileSpecList module_list, SBFileSpecList comp_unit_list) -> SBBreakp... | 625941c3956e5f7376d70e39 |
def test__str__(self): <NEW_LINE> <INDENT> self.assertIn("name", str(ArgumentFutureRename("name", "new_name"))) <NEW_LINE> self.assertIn( "new_name", str(ArgumentFutureRename("name", "new_name")) ) | Test :meth:`colour.utilities.deprecation.ArgumentFutureRename.__str__` method. | 625941c3187af65679ca50e9 |
def vote_is_enabled(ctx): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = koalabot.check_guild_has_ext(ctx, "Vote") <NEW_LINE> <DEDENT> except PermissionError: <NEW_LINE> <INDENT> result = False <NEW_LINE> <DEDENT> return result or (str(ctx.author) == koalabot.TEST_USER and koalabot.is_dpytest) | A command used to check if the guild has enabled verify
e.g. @commands.check(vote_is_enabled)
:param ctx: The context of the message
:return: True if enabled or test, False otherwise | 625941c3090684286d50ecaf |
def lsP4(queryStr, includeDeleted=False): <NEW_LINE> <INDENT> filesAndDicts = [] <NEW_LINE> queryLines = _p4run('files', queryStr) <NEW_LINE> for line in queryLines: <NEW_LINE> <INDENT> fDict = {} <NEW_LINE> toks = line.split(' ') <NEW_LINE> if line.startswith('exit'): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> i... | returns a list of dict's containing the clientFile, depotFile, headRev, headChange and headAction | 625941c3ad47b63b2c509f4b |
def __contains__(self, x): <NEW_LINE> <INDENT> if not isinstance(x, (OrderedSetPartition, list, tuple)): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if sum(map(len, x)) != len(self._set): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> u = Set([]) <NEW_LINE> for s in x: <NEW_LINE> <INDENT> if not s or not... | TESTS::
sage: OS = OrderedSetPartitions([1,2,3,4])
sage: all(sp in OS for sp in OS)
True
sage: [[1,2], [], [3,4]] in OS
False
sage: [Set([1,2]), Set([3,4])] in OS
True
sage: [set([1,2]), set([3,4])] in OS
Traceback (most recent call last):
...
TypeError: X (=set([1, 2])) mus... | 625941c3ff9c53063f47c1bf |
def mali(model='unknown', options=None): <NEW_LINE> <INDENT> opts = ["-device=mali", '-model=%s' % model] <NEW_LINE> opts = _merge_opts(opts, options) <NEW_LINE> return _api_internal._TargetCreate("opencl", *opts) | Returns a ARM Mali GPU target.
Parameters
----------
model: str
The model of this device
options : str or list of str
Additional options | 625941c3287bf620b61d3a30 |
def get_volume_metadata_value(self, volume, key): <NEW_LINE> <INDENT> metadata = volume.get('volume_metadata') <NEW_LINE> if metadata: <NEW_LINE> <INDENT> for i in volume['volume_metadata']: <NEW_LINE> <INDENT> if i['key'] == key: <NEW_LINE> <INDENT> return i['value'] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return None | Get value of particular metadata key. | 625941c394891a1f4081ba74 |
def get_endpoint_type(endpoint, type_hint=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> esri_regex = re.compile('/(mapserver|featureserver)/?\d*$', re.IGNORECASE) <NEW_LINE> xml_regex = re.compile('(text|application)/.*xml', re.IGNORECASE) <NEW_LINE> is_esri = esri_regex.search(endpoint) or type_hint in esri_type... | Determine the type of the endpoint | 625941c3b57a9660fec3384e |
def numIslands(self, grid): <NEW_LINE> <INDENT> if not grid: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> res = [] <NEW_LINE> count = 0 <NEW_LINE> for i in range(len(grid)): <NEW_LINE> <INDENT> for j in range(len(grid[0])): <NEW_LINE> <INDENT> if grid[i][j] == '1': <NEW_LINE> <INDENT> pixels = self.dfs(grid, i, j, ... | :type grid: List[List[str]]
:rtype: int | 625941c397e22403b379cf64 |
def post_loadbalancer_pool_read(self, resource_id, resource_dict): <NEW_LINE> <INDENT> pass | Method called after loadbalancer-pool is read | 625941c3711fe17d8254233a |
def pc_throughput_avg(self): <NEW_LINE> <INDENT> return _MFSK_swig.MFSK_sptr_pc_throughput_avg(self) | pc_throughput_avg(MFSK_sptr self) -> float | 625941c326238365f5f0ee37 |
def str(self): <NEW_LINE> <INDENT> return self.astype(str) | Casts values to strings. | 625941c3d4950a0f3b08c31c |
def remove(self, value): <NEW_LINE> <INDENT> if value in self._list: <NEW_LINE> <INDENT> self._list.remove(value) | Remove item from list. | 625941c3cc0a2c11143dce5b |
def _init_parameters(self, **kwargs): <NEW_LINE> <INDENT> self._graph_type = self._name.lower().capitalize() <NEW_LINE> if self._name_dict is None: <NEW_LINE> <INDENT> self._name_dict = {_item: _item for _item in self._df.columns} | :param kwargs | 625941c33cc13d1c6d3c7346 |
def get_string(self, pretty_print: bool = True) -> str: <NEW_LINE> <INDENT> string = _ET.tostring(self._root, "utf-8").decode("ascii") <NEW_LINE> if pretty_print is True: <NEW_LINE> <INDENT> if "\n" in string: <NEW_LINE> <INDENT> return string <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._prettify() <NEW_L... | gets the string of the xml tree in the file
:param pretty_print: bool, optional
sets True or False if the xml tree string should be pretty printed
syntax: <boolean>
example: True
:return: str
returns the string of the xml tree
syntax: <xml tree>
example: "<root>
<root_child auth... | 625941c3e1aae11d1e749c81 |
def calc_max_uptime(reboots): <NEW_LINE> <INDENT> pass | Parse the passed in reboots output,
extracting the datetimes.
Calculate the highest uptime between reboots =
highest diff between extracted reboot datetimes.
Return a tuple of this max uptime in days (int) and the
date (str) this record was hit.
For the output above it would be (30, '2019-02-17'),
but we use differe... | 625941c37b25080760e39425 |
def partial(self): <NEW_LINE> <INDENT> self._partial = t.time() <NEW_LINE> partial = self._partial - self._ref <NEW_LINE> self._ref = self._partial <NEW_LINE> return "partial elapsed time: %.2f s" % partial | returns partial elapsed time | 625941c3a17c0f6771cbe01d |
def _schwefel(x, xmin=-1, xmax=1): <NEW_LINE> <INDENT> x = _rescale(x, xmin, xmax, -500, 500) <NEW_LINE> result = 418.9829 * tf.to_float(tf.shape(x)[1]) - tf.reduce_sum(tf.sin(tf.abs(x) ** 0.5) * x,axis=1) <NEW_LINE> return result | https://www.sfu.ca/~ssurjano/schwef.html | 625941c36fb2d068a760f067 |
def act(self, state, add_noise: bool = True, logger=None): <NEW_LINE> <INDENT> state = torch.from_numpy(state).float().to(self.device) <NEW_LINE> if self.num_agents == 1: <NEW_LINE> <INDENT> self.actor_local.eval() <NEW_LINE> with torch.no_grad(): <NEW_LINE> <INDENT> action = self.actor_local(state).cpu().data.numpy() ... | Chooses an action for the current state based on the current policy.
Args:
state: The current state of the environment.
add_noise (bool): Controls addition of noise.
logger (Logger): An instance of Logger.
Returns:
Actions for given state as per current policy. | 625941c3f548e778e58cd548 |
def pc_setup_sleep(mins): <NEW_LINE> <INDENT> if int(mins) > 5: <NEW_LINE> <INDENT> cmd = 'powercfg -x standby-timeout-ac %s' % str(mins) <NEW_LINE> subprocess_call(cmd) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.error('Too short time for pc sleep interaval!!!') | Set up System_power_settings:PC_sleep_interval in minutes | 625941c36fece00bbac2d708 |
def test_get_method_name(): <NEW_LINE> <INDENT> trans = JsonTranslator('fixture.json') <NEW_LINE> assert trans.get_method_name() == 'def create_fixture_json_objects():' | test that filename with extension is handled correctly | 625941c366673b3332b9205c |
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_get_struct_ih2B().pack(_x.iTOW, _x.week, _x.numVis, _x.numSV)) <NEW_LINE> length = len(self.sv) <NEW_LINE> buff.write(_struct_I.pack(length)) <NEW_LINE> for val1 in self.sv: <NEW_LINE> <INDENT> _x = val1 <NEW_LINE> ... | serialize message into buffer
:param buff: buffer, ``StringIO`` | 625941c330c21e258bdfa467 |
@app.route('/lego/workflow/handle_info') <NEW_LINE> def workflow_info(): <NEW_LINE> <INDENT> user = request.args['user'] <NEW_LINE> account = request.args['account'] <NEW_LINE> handle = request.args['handle'] <NEW_LINE> return jsonify({ "info": getHandleInfo(handle) }) | Get progress of a running workflow | 625941c34d74a7450ccd418f |
def get_arg_num( self): <NEW_LINE> <INDENT> arg_num = self._frame_inst_arg.get_arg_num() <NEW_LINE> return arg_num | called from HTML_creator.process_inst | 625941c3adb09d7d5db6c75c |
def init_temperature_data(self): <NEW_LINE> <INDENT> self.get_weather_station() <NEW_LINE> if self.weather_station_pk: <NEW_LINE> <INDENT> date_format = self.get_date_format() <NEW_LINE> for t in self.get_temperature_set(): <NEW_LINE> <INDENT> temp_C = t.temp_C <NEW_LINE> if temp_C is None: <NEW_LINE> <INDENT> temp_C =... | Pulls all cached weather data into memory.
| 625941c3377c676e91272175 |
def append(self, row): <NEW_LINE> <INDENT> row = tuple(row) <NEW_LINE> if len(row) != self.table_width: <NEW_LINE> <INDENT> raise ValueError('Wrong result row length') <NEW_LINE> <DEDENT> self.results.append(row) | Append a result row and check its length.
>>> x = Results(['title', 'type'])
>>> x.append(('Konosuba', 'TV'))
>>> x
Results(['title', 'type'], [('Konosuba', 'TV')])
>>> x.append(('Konosuba',))
Traceback (most recent call last):
...
ValueError: Wrong result row length | 625941c3851cf427c661a4dc |
def addKeyToCatalog(portal): <NEW_LINE> <INDENT> catalog = getToolByName(portal, 'portal_catalog') <NEW_LINE> indexes = catalog.indexes() <NEW_LINE> indexables = [] <NEW_LINE> WANTED_INDEXES = (('fundingCategory', 'FieldIndex'),) <NEW_LINE> for name, meta_type in WANTED_INDEXES: <NEW_LINE> <INDENT> if name not in index... | Takes portal_catalog and adds a key to it
@param portal: context providing portal_catalog | 625941c3b830903b967e98d8 |
def fill_macro(self, x, y): <NEW_LINE> <INDENT> self.macro[(x, y)] = True | set the macro True. | 625941c3d7e4931a7ee9dee9 |
@task(base=BaseInstructorTask, routing_key=settings.GRADES_DOWNLOAD_ROUTING_KEY) <NEW_LINE> @set_code_owner_attribute <NEW_LINE> def calculate_problem_grade_report(entry_id, xmodule_instance_args): <NEW_LINE> <INDENT> action_name = ugettext_noop('problem distribution graded') <NEW_LINE> TASK_LOG.info( u"Task: %s, Instr... | Generate a CSV for a course containing all students' problem
grades and push the results to an S3 bucket for download. | 625941c33617ad0b5ed67ec4 |
def fit_best_classifier(docs, labels, best_result): <NEW_LINE> <INDENT> classifier= LogisticRegression() <NEW_LINE> tokenized_list= [tokenize(documents,best_result['punct']) for documents in docs] <NEW_LINE> csr_matrix,vocab= vectorize(tokenized_list,list(best_result['features']),best_result['min_freq']) <NEW_LINE> cla... | Using the best setting from eval_all_combinations,
re-vectorize all the training data and fit a
LogisticRegression classifier to all training data.
(i.e., no cross-validation done here)
Params:
docs..........List of training document strings.
labels........The true labels for each training document (0 or 1)
best... | 625941c32c8b7c6e89b3578d |
def quickSort(a, pivot): <NEW_LINE> <INDENT> def get_pivot(pivot, a, l, r): <NEW_LINE> <INDENT> if pivot == 'first': <NEW_LINE> <INDENT> return l <NEW_LINE> <DEDENT> if pivot == 'last': <NEW_LINE> <INDENT> return r <NEW_LINE> <DEDENT> if pivot == 'median': <NEW_LINE> <INDENT> three = [(a[l], l), (a[r], r), (a[(r - l) /... | :param a:
:return: | 625941c3004d5f362079a300 |
def __repr__(self): <NEW_LINE> <INDENT> return str("{}".format(self.id)) | Define an ASCII string safe representation of the translation. | 625941c3be7bc26dc91cd5cf |
def level_features(self, opts): <NEW_LINE> <INDENT> for level in opts: <NEW_LINE> <INDENT> if self.level > int(level[0]): <NEW_LINE> <INDENT> if isinstance(level[1], str): <NEW_LINE> <INDENT> self.features.append(level[1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for item in level[1]: <NEW_LINE> <INDENT> self.feat... | adds features to character/class input based on option list provided
FOR FEATURES ONLY. ALL OTHER HAVE TO BE IN IND. CHARACTER CLASSES CLASS
:param opts: list of options & levels, similar to adding spells function
format: [[(int level), ["feature1", "feature2"]], [(int level2), ["feature3", "feature4"]]]
:return: N/A | 625941c33cc13d1c6d3c7347 |
def browse_children(self, id_, filter = "*", count = "25"): <NEW_LINE> <INDENT> children = self._contentDirectory.Browse(ObjectID = id_, BrowseFlag = "BrowseDirectChildren", Filter = filter, StartingIndex = "0", RequestedCount = count, SortCriteria = "") <NEW_LINE> result = children.Result <NEW_LINE> count_returned = c... | Convenience function for browsing child elements; returns Result and NumberReturned | 625941c35fcc89381b1e1689 |
def atcacert_date_enc(date_format, timestamp, formatted_date, formatted_date_size): <NEW_LINE> <INDENT> if not isinstance(formatted_date, bytearray) or not isinstance(formatted_date_size, AtcaReference): <NEW_LINE> <INDENT> status = Status.ATCA_BAD_PARAM <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> c_formatted_date = ... | Format a timestamp according to the format type.
Args:
date_format Format to use.
timestamp Timestamp to format. Expects atcacert_tm_utc_t.
formatted_date Formatted date will be returned in this buffer.
Expects bytearray.
formatted_date_siz... | 625941c310dbd63aa1bd2b70 |
def handwritingClassTest(): <NEW_LINE> <INDENT> hwLabels = [] <NEW_LINE> trainingFileList = listdir('trainingDigits') <NEW_LINE> m = len(trainingFileList) <NEW_LINE> trainingMat = zeros((m, 1024)) <NEW_LINE> for i in range(m): <NEW_LINE> <INDENT> fileNameStr = trainingFileList[i] <NEW_LINE> fileStr = fileNameStr.split(... | 每个文件的文件名前缀为数字几的标签 | 625941c376d4e153a657eafc |
def wipe_device(client: HardwareWalletClient) -> Dict[str, bool]: <NEW_LINE> <INDENT> return {"success": client.wipe_device()} | Wipe a device
:param client: The client to interact with
:return: A dictionary with the ``success`` key. | 625941c3dc8b845886cb5500 |
@csrf_exempt <NEW_LINE> @ajax(require_POST=True) <NEW_LINE> def sort_post(request): <NEW_LINE> <INDENT> tour_private_id = request.POST.get('tour_private_id', None) <NEW_LINE> order = request.POST.get('order', None) <NEW_LINE> if not all((tour_private_id, order)): <NEW_LINE> <INDENT> return HttpResponseBadRequest('order... | POST /sort_post/
Given a tour_private_id and order, sort post object of tour according to
order.
order example: "post[]=40&post[]=52". | 625941c3462c4b4f79d1d69c |
def internet_connect(): <NEW_LINE> <INDENT> code, headers, html, cur_opener = get_url("http://reliancebroadband.co.in/reliance/startportal_isg.do", timeout=3) <NEW_LINE> if debug: print(html) <NEW_LINE> login_data = urllib.parse.urlencode({'userId' : username, 'password' : password, 'action' : 'doLoginSubmit'}).encode(... | try to connect to the internet | 625941c392d797404e304155 |
def test_get_details_root_non_phoenixborn(client: TestClient, session: db.Session): <NEW_LINE> <INDENT> response = client.get("/v2/cards/summon-example-conjuration/details") <NEW_LINE> assert response.status_code == status.HTTP_200_OK | Must properly find root non-Phoenixborn cards | 625941c357b8e32f52483465 |
def compositionMode(self): <NEW_LINE> <INDENT> pass | QPaintEngineState.compositionMode() -> QPainter.CompositionMode | 625941c37b25080760e39426 |
def more_specific(self,hyp1,hyp2): <NEW_LINE> <INDENT> return self.more_general(hyp2,hyp1) | hyp1 more specific than hyp2 is
equivalent to hyp2 being more general than hyp1 | 625941c356ac1b37e626419e |
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_get_struct_3I().pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) <NEW_LINE> _x = self.header.frame_id <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <INDENT> _x... | serialize message into buffer
:param buff: buffer, ``StringIO`` | 625941c3d6c5a10208144015 |
def _identify_with_OPTIONS(self, url): <NEW_LINE> <INDENT> _allowed_methods = [] <NEW_LINE> id_list = [] <NEW_LINE> try: <NEW_LINE> <INDENT> res = self._uri_opener.OPTIONS(url) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> headers = res.get_lower_case_headers() <NEW_... | Find out what methods are allowed using OPTIONS
:param url: Where to check. | 625941c3187af65679ca50ea |
def get_instance_header(self, instance_identifier: str, params: Dict = None) -> Any: <NEW_LINE> <INDENT> return self.get_request( f'{self._orthanc_url}/instances/{instance_identifier}/header', params ) | Get the meta information (header) of the DICOM file
Get the meta information (header) of the DICOM file,
Parameters
----------
instance_identifier
Instance identifier.
params
GET HTTP request's params.
Returns
-------
Any
Meta information (header) of the DICOM file. | 625941c3711fe17d8254233b |
def __repr__(self): <NEW_LINE> <INDENT> return "<User %r>" % self.id_ | User string representation. | 625941c3d18da76e235324a0 |
def compile(self, optimizer, loss, metrics=None, sample_weight_mode=None, **kwargs): <NEW_LINE> <INDENT> self.build() <NEW_LINE> self.model.compile(optimizer, loss, metrics=metrics, sample_weight_mode=sample_weight_mode, **kwargs) <NEW_LINE> self.optimizer = self.model.optimizer <NEW_LINE> self.loss = self.model.loss <... | Configures the learning process.
# Arguments
optimizer: str (name of optimizer) or optimizer object.
See [optimizers](/optimizers).
loss: str (name of objective function) or objective function.
See [objectives](/objectives).
metrics: list of metrics to be evaluated by the model
duri... | 625941c391f36d47f21ac4bd |
def github(parser, xml_parent, data): <NEW_LINE> <INDENT> github = XML.SubElement(xml_parent, 'com.coravy.hudson.plugins.github.' 'GithubProjectProperty') <NEW_LINE> github_url = XML.SubElement(github, 'projectUrl') <NEW_LINE> github_url.text = data['url'] | yaml: github
Sets the GitHub URL for the project.
:arg str url: the GitHub URL
Example::
properties:
- github:
url: https://github.com/openstack-ci/jenkins-job-builder/ | 625941c344b2445a33932063 |
def get_random_state_space(self, num_layers): <NEW_LINE> <INDENT> states = [] <NEW_LINE> for id in range(self.size * num_layers): <NEW_LINE> <INDENT> state = self[id] <NEW_LINE> size = state['size'] <NEW_LINE> sample = np.random.choice(size, size=1) <NEW_LINE> sample = state['index_map_'][sample[0]] <NEW_LINE> state = ... | Constructs a random initial state space for feeding as an initial value
to the Controller RNN
Args:
num_layers: number of layers to duplicate the search space
Returns:
A list of one hot encoded states | 625941c36aa9bd52df036d6f |
def _api_call(self, endpoint: str, params: dict=None, request: str=None) -> dict: <NEW_LINE> <INDENT> if not params: <NEW_LINE> <INDENT> params = {} <NEW_LINE> <DEDENT> if request is PUT: <NEW_LINE> <INDENT> request = requests.put <NEW_LINE> <DEDENT> elif request is DELETE: <NEW_LINE> <INDENT> request = requests.delete... | BASE FUNCTION FOR MAKING API CALLS TO MRR | 625941c38e71fb1e9831d776 |
def empty_beat_rate(pianoroll: ndarray, resolution: int) -> float: <NEW_LINE> <INDENT> reshaped = pianoroll.reshape(-1, resolution * pianoroll.shape[1]) <NEW_LINE> if len(reshaped) < 1: <NEW_LINE> <INDENT> return nan <NEW_LINE> <DEDENT> n_empty_beats = np.count_nonzero(reshaped.any(1)) <NEW_LINE> return n_empty_beats /... | Return the ratio of empty beats.
The empty-beat rate is defined as the ratio of the number of empty
beats (where no note is played) to the total number of beats. Return
NaN if song length is zero.
.. math:: empty\_beat\_rate = \frac{\#(empty\_beats)}{\#(beats)}
Parameters
----------
pianoroll : ndarray
Piano rol... | 625941c3be8e80087fb20c11 |
def introsort(array): <NEW_LINE> <INDENT> p = 0 <NEW_LINE> r = len(array)-1 <NEW_LINE> introsort2(array,p,r) | Establece otras dos variables aparte del arreglo, y llama a introsort con tres parametros
Parametros:
array: Arreglo a ordenar | 625941c39c8ee82313fbb740 |
def push_new_articles(self, articles): <NEW_LINE> <INDENT> inserted = 0 <NEW_LINE> logger.info("trying to insert {} articles".format(len(articles))) <NEW_LINE> for article in articles: <NEW_LINE> <INDENT> if ( self.client.Articles.allArticles.find({"id": article["id"]}).count() == 0 ): <NEW_LINE> <INDENT> self.client.A... | inserts new articles to database | 625941c330bbd722463cbd90 |
def __init__(self, resources): <NEW_LINE> <INDENT> self._operations = [] <NEW_LINE> self._resources = resources | Run jobs on your local machine.
Args:
resources: module providing access to files packaged with dsub
(See dsub/libs/resources.py) | 625941c356ac1b37e626419f |
def set_processor_affinity(self, mask): <NEW_LINE> <INDENT> return _cdma_swig.pac_err_cal_sptr_set_processor_affinity(self, mask) | set_processor_affinity(pac_err_cal_sptr self, std::vector< int,std::allocator< int > > const & mask) | 625941c38e7ae83300e4af98 |
def goal_state_not_in_prop_layer(self, propositions): <NEW_LINE> <INDENT> for goal in self.goal: <NEW_LINE> <INDENT> if goal not in propositions: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | Helper function that returns true if all the goal propositions
are in propositions | 625941c31b99ca400220aa7d |
def fails(self, dstore=None): <NEW_LINE> <INDENT> for index in self.selvar.get_lower(dstore=dstore): <NEW_LINE> <INDENT> constraint = self.constraints[index] <NEW_LINE> if constraint and constraint.fails(dstore=dstore): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | Fail if any of the UnionSelection constraints over the selvars and mainvars indexed by the
lower bound of selvar fail. | 625941c356b00c62f0f14625 |
def lcd_backlight(self, state): <NEW_LINE> <INDENT> if state: <NEW_LINE> <INDENT> self.lcd_out.lcd_backlight(state) <NEW_LINE> self.lcd_is_on = True <NEW_LINE> self.timer = time.time() - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.lcd_is_on = False | Turn the backlight on or off | 625941c3e76e3b2f99f3a7da |
def _make_searches_by_size(searches: list[Search]) -> dict[int, set[Search]]: <NEW_LINE> <INDENT> searches_by_size: dict[int, set[Search]] = OrderedDict() <NEW_LINE> for search in searches: <NEW_LINE> <INDENT> size = len(search.players) <NEW_LINE> if size not in searches_by_size: <NEW_LINE> <INDENT> searches_by_size[si... | Creates a lookup table indexed by number of players in the search. | 625941c3e76e3b2f99f3a7db |
def get_selected_FishManifest(self,widget): <NEW_LINE> <INDENT> fish_file = '' <NEW_LINE> iterator = self.FISH_combobox.get_active_iter() <NEW_LINE> if iterator is not None: <NEW_LINE> <INDENT> model = self.FISH_combobox.get_model() <NEW_LINE> fish_file = model[iterator][1] <NEW_LINE> print(fish_file) <NEW_LINE> self.f... | Returns the selected device from the GUI | 625941c3f548e778e58cd549 |
def smart_label(df, pltkwargs): <NEW_LINE> <INDENT> xlabel_def=pltkwargs.pop('xlabel_def', '') <NEW_LINE> ylabel_def=pltkwargs.pop('ylabel_def', '') <NEW_LINE> zlabel_def=pltkwargs.pop('zlabel_def', '') <NEW_LINE> title_def=pltkwargs.pop('title_def', '') <NEW_LINE> if 'xlabel' in pltkwargs: <NEW_LINE> <INDENT> xlabel=p... | Infers title, xlabel and ylabel either from dictionary or dataframe attributes index.name, columns.name
and df.name. Used by plotting functions to assign labels and title. All defaults are set to blank.
Note: xlabel, ylabel, zlabel are popped out of the dictionary, so will be gone upon return. | 625941c32eb69b55b151c87a |
def _read_categories_from_sitemaps(self) -> list: <NEW_LINE> <INDENT> self._cats = [self._scrape_sitemap_pages(cats) for cats in self._read_urls_from_sitemap_link()][0] <NEW_LINE> _left_strip = ICFG.STARTING_URL + self.location + "/category/" <NEW_LINE> _right_strip = "/accredited" if self._acc else "" <NEW_LINE> retur... | uses the results from _read_urls_from_sitemap_link, and cleans up the names of
the categories from the URLs. makes it easier to compare it with the
input argument | 625941c33539df3088e2e317 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.