code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def traffic_file_types(self, **kwargs): <NEW_LINE> <INDENT> url_path = "traffic/fileTypes" <NEW_LINE> body = self._make_body(kwargs) <NEW_LINE> self.logger.debug("Retrieving fileTypes data with filtering") <NEW_LINE> return self._common_post(request_path=url_path, body=body) | Retrieve fileTypes data with filtering.
:param shortname: (required) <list> - List of shortnames
:param requestedFields: (required) <list> - List of result fields to be retrieved
:param startDate: (required) <int> - Datetime (first occurrence of the entry)
:param endDate: (optional) <int> - Datetime (... | 625941ca711fe17d8254240d |
def read_board(board_file): <NEW_LINE> <INDENT> board = [] <NEW_LINE> board_row = [] <NEW_LINE> i = 0 <NEW_LINE> for line in board_file: <NEW_LINE> <INDENT> line = line.rstrip('\n') <NEW_LINE> board_row += line <NEW_LINE> board.insert( i, board_row ) <NEW_LINE> i = i + 1 <NEW_LINE> board_row = [] <NEW_LINE> <DEDENT> re... | (file open for reading) -> list of list of str
Return a board read from open file board_file. The board file will contain
one row of the board per line. Newlines are not included in the board. | 625941ca97e22403b379d03a |
def test_unavailable(self): <NEW_LINE> <INDENT> self.env.user.lang = False <NEW_LINE> self.rl = self.rl.with_context(lang=False) <NEW_LINE> first = self.rl.search([("active", "=", True)], limit=1) <NEW_LINE> self.assertEqual(self.rl.best_match("fake_LANG").code, first.code) <NEW_LINE> with self.assertRaises(exceptions.... | When matches to an unavailable language. | 625941ca4d74a7450ccd4265 |
@csrf_exempt <NEW_LINE> def read_or_update_or_delete(request, resource_type, id): <NEW_LINE> <INDENT> if request.method == 'GET': <NEW_LINE> <INDENT> logger.debug("making read with Resource:" "%s and id:%s" % (resource_type, id)) <NEW_LINE> return read(request, resource_type, id) <NEW_LINE> <DEDENT> msg = "HTTP method ... | Route to read, update, or delete based on HTTP method FHIR Interaction | 625941cae1aae11d1e749d57 |
def remove_none_values(params): <NEW_LINE> <INDENT> def remove_nones(o, **kwargs): <NEW_LINE> <INDENT> if isinstance(o, dict): <NEW_LINE> <INDENT> for k, v in dict(o).items(): <NEW_LINE> <INDENT> if v is None: <NEW_LINE> <INDENT> o.pop(k) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if isinstance(o, list): <NEW_LINE> <INDENT>... | Remove None values recursively in the given object. | 625941ca57b8e32f5248353b |
def add_message(thing, code): <NEW_LINE> <INDENT> message_is_text = CODED.get_response_type(code) <NEW_LINE> if message_is_text: <NEW_LINE> <INDENT> thing.say(CODED.get_response_text(code)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> thing.play(url_for('answer_audio', code=code)) | Add the message from code to thing. | 625941ca99cbb53fe6792c87 |
def mobilenet_v2(pretrained=False, progress=True, **kwargs): <NEW_LINE> <INDENT> model = MobileNetV2(**kwargs) <NEW_LINE> if pretrained: <NEW_LINE> <INDENT> state_dict = load_state_dict_from_url(model_urls['mobilenet_v2'], progress=progress) <NEW_LINE> model.load_state_dict(state_dict, strict=False) <NEW_LINE> <DEDENT>... | Constructs a MobileNetV2 architecture from
`"MobileNetV2: Inverted Residuals and Linear Bottlenecks" <https://arxiv.org/abs/1801.04381>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr | 625941ca76d4e153a657ebd2 |
def _reset_battle_stats(self): <NEW_LINE> <INDENT> self._battle_stats = BattleStats.from_stats(self._stats) | Recalculate the battle stats. | 625941cacc0a2c11143dcf31 |
def _run(self): <NEW_LINE> <INDENT> def raise_signal_exception(signum, _): <NEW_LINE> <INDENT> if signum == signal.SIGHUP: <NEW_LINE> <INDENT> raise SIGHUPReceivedException <NEW_LINE> <DEDENT> elif signum == signal.SIGTERM: <NEW_LINE> <INDENT> raise SIGTERMReceivedException <NEW_LINE> <DEDENT> <DEDENT> signal.signal(si... | Run a :py:meth:`select.poll.poll()` loop processing both
synchronous and asynchronous events.
:returns: None | 625941caac7a0e7691ed416e |
def _get_insensitive_data_columns(self) -> List: <NEW_LINE> <INDENT> return [col.replace('_', '').lower() for col in self.data_columns] | Return list of case- & underscore-insensitive data column names.
Returns
-------
insensitive_data_columns
List of data columns, with underscores removed and case ignored. | 625941ca711fe17d8254240e |
def get_video_type_choices(): <NEW_LINE> <INDENT> choices = [] <NEW_LINE> for typ in _CUBANE_VIDEO_TYPES: <NEW_LINE> <INDENT> slug = slugify(typ.name) <NEW_LINE> if slug in settings.CUBANE_VIDEO_TYPES: <NEW_LINE> <INDENT> choices.append((slug, typ.name)) <NEW_LINE> <DEDENT> <DEDENT> return choices | Get video type choices filter by settings | 625941ca96565a6dacc8f76c |
def dispatch_actions(url, key, actions): <NEW_LINE> <INDENT> for action in actions: <NEW_LINE> <INDENT> prefixes, entries = retrieve_filterlist(url, key) <NEW_LINE> new_prefixes = action(prefixes) <NEW_LINE> if new_prefixes is not None: <NEW_LINE> <INDENT> new_entries = merge_entries(entries, new_prefixes) <NEW_LINE> b... | Dispatch queued actions
An action is a callback function describing the action
that should be taken for each script argument. Every action will
be preceded by retrieving a list of blacklisted prefixes from the
sp leader. This list will be passed into whatever function is
designated by the action.
Lifecycle:
Retri... | 625941ca73bcbd0ca4b2c117 |
def create_eep(opt, out_base): <NEW_LINE> <INDENT> if opt.verbose > 2: <NEW_LINE> <INDENT> print('- Create .eep: {f}.elf => {f}.eep:'.format(f=out_base)) <NEW_LINE> <DEDENT> cmd = cmd_eep.format( outname=out_base, objcopy=objcopy) <NEW_LINE> run(opt, cmd) | Create EEP: | 625941ca9f2886367277a92e |
def series3(fruits_list): <NEW_LINE> <INDENT> copy_list = fruits_list[:] <NEW_LINE> for fruit in copy_list: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> user_response = input("Do you like {} ?".format(fruit.lower())) <NEW_LINE> if user_response.lower() in ('yes', 'no'): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDE... | Ask user if he likes the fruit for each fruit in the list. If he responds
with no, delete it
:param fruits_list:
:return: None | 625941ca66656f66f7cbc24b |
def unwatch_service(self, hookname, srvname): <NEW_LINE> <INDENT> self._unwatch('srv:%s' % (srvname), hookname) | Stop watching service C{srvname}. | 625941ca2eb69b55b151c94f |
def _getSeriesPocketAndComponentDescription(self): <NEW_LINE> <INDENT> if IDistroArchSeries.providedBy(self.series): <NEW_LINE> <INDENT> text = ("Series %s, Architecture %s" % (self.series.distroseries.title, self.series.architecturetag)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> text = "Series %s" % self.series.ti... | Return a string containing the name of the series, pocket and
component.
This is meant to be used in the logs, to help us identify if this is a
MirrorDistroSeriesSource or a MirrorDistroArchSeries. | 625941ca7d43ff24873a2d41 |
def test_try_create_netipv6_with_auto_alloc_in_full_env(self): <NEW_LINE> <INDENT> name_file = self.json_path % 'post/net_without_octs_full_env.json' <NEW_LINE> response = self.client.post( '/api/v3/networkv6/', data=json.dumps(self.load_json_file(name_file)), content_type='application/json', HTTP_AUTHORIZATION=self.au... | Test of error to create a Network IPv6 without octs in vlan
of Environment with not available Network IPv6. | 625941ca442bda511e8be4ba |
def in6_cidr2mask(m): <NEW_LINE> <INDENT> if m > 128 or m < 0: <NEW_LINE> <INDENT> raise Kamene_Exception("value provided to in6_cidr2mask outside [0, 128] domain (%d)" % m) <NEW_LINE> <DEDENT> t = [] <NEW_LINE> for i in range(0, 4): <NEW_LINE> <INDENT> t.append(max(0, 2**32 - 2**(32-min(32, m)))) <NEW_LINE> m -= 32 <... | Return the mask (bitstring) associated with provided length
value. For instance if function is called on 48, return value is
'ÿÿÿÿÿÿ '. | 625941ca50485f2cf553ce3a |
def _get_file(self, share_name, directory_name, file_name, start_range=None, end_range=None, validate_content=False, timeout=None, _context=None, snapshot=None): <NEW_LINE> <INDENT> _validate_not_none('share_name', share_name) <NEW_LINE> _validate_not_none('file_name', file_name) <NEW_LINE> request = HTTPRequest() <NEW... | Downloads a file's content, metadata, and properties. You can specify a
range if you don't need to download the file in its entirety. If no range
is specified, the full file will be downloaded.
See get_file_to_* for high level functions that handle the download
of large files with automatic chunking and progress notif... | 625941ca796e427e537b0666 |
def check_prime(n): <NEW_LINE> <INDENT> if n == 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if n == 2: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> for i in range(2, n // 2): <NEW_LINE> <INDENT> if n % i == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True | Write a program that checks if a given number n (1 < n < 100) is a
prime number (i.e. it is divisible without remainder only to itself and 1).
:param n:
:return: | 625941cabe8e80087fb20ce4 |
def setEnable(self, enable): <NEW_LINE> <INDENT> self.enable = enable | :param enable: (Optional) 是否开启鉴权[on,off] | 625941ca3317a56b86939cfb |
def classify(self, example): <NEW_LINE> <INDENT> if 'Yea' in example or 'Nay' in example: <NEW_LINE> <INDENT> for i in range(len(example)): <NEW_LINE> <INDENT> if example[i] not in ['Yea','Nay','Democrat','Republican']: <NEW_LINE> <INDENT> example[i] = self.replace[i] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return self.r... | Perform inference on a single example.
Args:
example: the instance being classified
Returns: a tuple containing a class label and a probability | 625941ca462c4b4f79d1d772 |
def power_on_node_if_needed(task): <NEW_LINE> <INDENT> if not task.driver.network.need_power_on(task): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> previous_power_state = task.driver.power.get_power_state(task) <NEW_LINE> if previous_power_state == states.POWER_OFF: <NEW_LINE> <INDENT> node_set_boot_device( task, boo... | Powers on node if it is powered off and has a Smart NIC port
:param task: A TaskManager object
:returns: the previous power state or None if no changes were made
:raises: exception.NetworkError if agent status didn't match the required
status after max retry attempts. | 625941cabe8e80087fb20ce5 |
def labels(root): <NEW_LINE> <INDENT> asset_labels = [] <NEW_LINE> name_type_map = OrderedDict( [("fig", "fig"), ("media", "video"), ("table-wrap", "table")] ) <NEW_LINE> for tag_name in list(name_type_map): <NEW_LINE> <INDENT> for block_tag in root.findall(".//" + tag_name): <NEW_LINE> <INDENT> label_tags = block_tag.... | find label values from assets | 625941ca627d3e7fe0d68ef0 |
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_struct_iB.pack(_x.parameter, _x.parameterValue)) <NEW_LINE> <DEDENT> except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) <NEW... | serialize message into buffer
:param buff: buffer, ``StringIO`` | 625941cad99f1b3c44c67630 |
def get_max_dilution_of_precision(self) -> Optional[float]: <NEW_LINE> <INDENT> return max(self.horizontal_dilution, self.vertical_dilution, self.position_dilution) | Only care about the max dop for filtering, no need to go into too much detail | 625941ca3eb6a72ae02ec57d |
def __init__(self, raw_json_str): <NEW_LINE> <INDENT> self.json_data = [] <NEW_LINE> self.all_fields = set() <NEW_LINE> list_json_data = json.loads(raw_json_str) <NEW_LINE> for list_entry in list_json_data: <NEW_LINE> <INDENT> self.json_data += list_entry['_embedded']['tours'] <NEW_LINE> <DEDENT> for tour in self.json_... | Parse json data and get all fields (columns).
:param raw_json_str: Tour overview json data as returned by komoot API (type: str). | 625941ca30c21e258bdfa53e |
def detecPy3(self, mensagem=""): <NEW_LINE> <INDENT> return input(mensagem) | Desc: Retorna o valor digitado
mensagem = Str: Mensagem a ser exibida
return = Str: O que o usuário inseriu | 625941cade87d2750b85fe34 |
def get_networks(self, context, filters=None, fields=None): <NEW_LINE> <INDENT> pass | For this model this method will be delegated to vswitch plugin. | 625941ca8a349b6b435e8214 |
def test_post_order_view(self): <NEW_LINE> <INDENT> url_order = reverse('backend:order') <NEW_LINE> self.create_user() <NEW_LINE> email = self.data['email'] <NEW_LINE> user = User.objects.get(email=email) <NEW_LINE> token = Token.objects.get_or_create(user_id=user.id)[0].key <NEW_LINE> self.client.credentials(HTTP_AUTH... | Create order. | 625941cac4546d3d9de72ad5 |
def fill_first_stool(self, num_cheese): <NEW_LINE> <INDENT> self.num_cheese = num_cheese <NEW_LINE> for i in reversed(range(num_cheese)): <NEW_LINE> <INDENT> self._stools[0].append(Cheese(i + 1)) | Add num_cheese number of num_cheese to the first stool.
@type self: TOAHModel
@type num_cheese: int
@rtype: None
>>> M = TOAHModel(4)
>>> M.fill_first_stool(5)
>>> (M.get_number_of_stools(), M.number_of_moves()) == (4,0)
True
>>> M.get_number_of_cheeses()
5 | 625941ca07f4c71912b11523 |
def getChildWithDefault(self, name, request): <NEW_LINE> <INDENT> return resource.ErrorPage(NOT_FOUND, "No Such Resource", "No Such Resource") | This should never be called; it's simply required to implement the
:py:class:`twisted.web.resource.IResource` interface. Just returns
a 404.
See: :py:meth:`twisted.web.resource.IResource.getChildWithDefault` | 625941caec188e330fd5a841 |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <... | Returns the model properties as a dict | 625941ca004d5f362079a3d5 |
def duration(self) -> str: <NEW_LINE> <INDENT> if not self.start_year: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> return "1 Year 6 Months" | Return the amount of time this project has been around | 625941ca1f037a2d8b94629f |
def _pygments_highlight(source, output_formatter, language='ipython', metadata=None): <NEW_LINE> <INDENT> from pygments import highlight <NEW_LINE> from pygments.lexers import get_lexer_by_name <NEW_LINE> from IPython.nbconvert.utils.lexers import IPythonLexer <NEW_LINE> if language == 'ipython' and metadata ... | Return a syntax-highlighted version of the input source
Parameters
----------
source : str
source of the cell to highlight
output_formatter : Pygments formatter
language : str
language to highlight the syntax of
metadata : NotebookNode cell metadata
metadata of the cell to highlight | 625941ca7b25080760e394fb |
def save_xml_response(response, action): <NEW_LINE> <INDENT> output_dir = os.path.dirname(os.path.abspath(__file__)) <NEW_LINE> filename = action + "_response.xml" <NEW_LINE> with open(os.path.join(output_dir, "../tests/assets", filename), "w") as f: <NEW_LINE> <INDENT> f.write(response.encode("utf-8")) <NEW_LINE> prin... | Save the response in a file | 625941caa8370b7717052941 |
def __init__(self, controller, jenkins_master): <NEW_LINE> <INDENT> super(StatusView, self).__init__(controller, jenkins_master) | :param controller:
class capable of handling common HTTP IO requests sent by this
object to the Jenkins REST API
:type controller: :class:`~.utils.datarequester.DataRequester`
:param jenkins_master:
Reference to Jenkins object associated with the master instance managing
this job
:type jenkins_master: :... | 625941ca60cbc95b062c65e5 |
def test_create_barchart_default_type_of_bar(self): <NEW_LINE> <INDENT> print("@test_create_barchart_default_type_of_bar") <NEW_LINE> x_data = numpy.ones(3, dtype=numpy.float64) <NEW_LINE> y_data = numpy.ones(3, dtype=numpy.float64) <NEW_LINE> width = 1 / 1.5 <NEW_LINE> colour = ["green"] <NEW_LINE> xlabel = "Years" <N... | Check create_barchart runs ok using default value for type_of_bar | 625941caec188e330fd5a842 |
def keys(d,_all=True): <NEW_LINE> <INDENT> key_list = list(d.keys()) <NEW_LINE> if _all: <NEW_LINE> <INDENT> out = key_list <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out = key_list[:1] <NEW_LINE> <DEDENT> if type(out) != list: <NEW_LINE> <INDENT> out = [out] <NEW_LINE> <DEDENT> return out | Returns the keys of a dictionary as a list. If _all=False only the first key is returned. | 625941ca44b2445a33932138 |
def _add_app_id(self, message): <NEW_LINE> <INDENT> if self._app_id: <NEW_LINE> <INDENT> app_override = message.mutable_override() <NEW_LINE> app_override.set_app_id(self._app_id) <NEW_LINE> app_override.set_num_memcacheg_backends(self._num_memcacheg_backends) <NEW_LINE> if self._ignore_shardlock: <NEW_LINE> <INDENT> a... | Populates override field in message if accessing another app's memcache.
Args:
message: A protocol buffer supporting the mutable_override() operation. | 625941ca167d2b6e31218c37 |
def create_services(self, services_list, detail=None): <NEW_LINE> <INDENT> return service._create_services( self._get_resource_root(), self.cluster_name, services_list) | Creates services.
@param services_list: list of services
@return: StatusModel. | 625941ca8a43f66fc4b54107 |
def main(): <NEW_LINE> <INDENT> client = AdminClient({"bootstrap.servers": BROKER_URL}) <NEW_LINE> try: <NEW_LINE> <INDENT> asyncio.run(produce_consume(TOPIC_NAME)) <NEW_LINE> <DEDENT> except KeyboardInterrupt as e: <NEW_LINE> <INDENT> print("shutting down") | Checks for topic and creates the topic if it does not exist | 625941ca71ff763f4b54972c |
def extract_shar (archive, compression, cmd, verbosity, outdir): <NEW_LINE> <INDENT> cmdlist = [cmd, os.path.abspath(archive)] <NEW_LINE> return (cmdlist, {'cwd': outdir}) | Extract a SHAR archive. | 625941cae5267d203edcdd40 |
def flagged(self): <NEW_LINE> <INDENT> return self.filter(flag_date__isnull=False) | Used by dev dashboard. | 625941ca5f7d997b87174b39 |
def atomsGroupedBy(self, prop): <NEW_LINE> <INDENT> d = dict() <NEW_LINE> if hasattr(Atom, prop): <NEW_LINE> <INDENT> getter = lambda x: getattr(x, prop) <NEW_LINE> <DEDENT> elif prop in self.atom_props: <NEW_LINE> <INDENT> getter = lambda x: x[prop] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return d <NEW_LINE> <DE... | Return dictionary mapping representative values of the given
atom property to lists of atoms having that property. If the
property does not exist in this system, returns an empty dictionary. | 625941cafb3f5b602dac3734 |
def set(self, path, value, scope=None): <NEW_LINE> <INDENT> section, _, rest = path.partition(':') <NEW_LINE> if not rest: <NEW_LINE> <INDENT> self.update_config(section, value, scope=scope) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> section_data = self.get_config(section, scope=scope) <NEW_LINE> parts = rest.split(... | Convenience function for setting single values in config files.
Accepts the path syntax described in ``get()``. | 625941caa8370b7717052942 |
def preprocess_and_tokenize_tweet(tweet): <NEW_LINE> <INDENT> cleaned_tweet = tweet.lower() <NEW_LINE> p.set_options(p.OPT.URL, p.OPT.EMOJI, p.OPT.MENTION, p.OPT.HASHTAG) <NEW_LINE> cleaned_tweet = p.clean(cleaned_tweet.encode('ascii', 'ignore')) <NEW_LINE> tweet_words = remove_stopwords_and_tokenize(cleaned_tweet) <NE... | Preprocess tweet, remove url, emoji, mentions, hastags, stopwords
:param tweet: raw tweet
:return: tweet | 625941cad10714528d5ffd84 |
@exporter.export <NEW_LINE> def dewpoint(e): <NEW_LINE> <INDENT> val = np.log(e / sat_pressure_0c) <NEW_LINE> return 0. * units.degC + 243.5 * units.delta_degC * val / (17.67 - val) | Calculate the ambient dewpoint given the vapor pressure.
Parameters
----------
e : array_like
Water vapor partial pressure
Returns
-------
array_like
Dew point temperature
See Also
--------
dewpoint_rh, saturation_vapor_pressure, vapor_pressure
Notes
-----
This function inverts the Bolton 1980 [3] formula f... | 625941ca187af65679ca51c0 |
def registerSession(self, sid, initiator, target, callback, meta=None, block_size=None, stanza_type='iq', wait_for_result_when_send=True): <NEW_LINE> <INDENT> if isinstance(initiator, (str, unicode)): <NEW_LINE> <INDENT> initiator = internJID(initiator) <NEW_LINE> <DEDENT> if isinstance(target, (str, unicode)): <NEW_LI... | Register bytestream session to wait for incoming connection. | 625941ca435de62698dfdcee |
def add_dense_layer(self,inputs,size,use_bias=True,activation=None,weight_initializer=None,bias_initializer=None): <NEW_LINE> <INDENT> with self.graph.as_default(): <NEW_LINE> <INDENT> if weight_initializer is None: <NEW_LINE> <INDENT> weight_initializer = self.DEFAULT_WEIGHT_INITIALIZER <NEW_LINE> <DEDENT> if bias_ini... | Adds a dense (or fully connected) layer to a neural network model.
Reshapes the input to 2 dimensions. If no weight or bias initializer is passed, the initializers defined by self.DEFAULT_WEIGHT_INITIALIZER or self.DEFAULT_BIAS_INITIALIZER are used.
Parameters
----------
inputs : tensorflow.Tensor
input of the de... | 625941ca3617ad0b5ed67f99 |
def build(self): <NEW_LINE> <INDENT> statements = list() <NEW_LINE> statements.extend(self._get_statement_for_effect('Allow', self.allow_methods)) <NEW_LINE> statements.extend(self._get_statement_for_effect('Deny', self.deny_methods)) <NEW_LINE> return dict( principalId=self.user_info.principal_id, context=self.user_in... | Generates the policy document based on the internal lists of allowed and denied
conditions. This will generate a policy with two main statements for the effect:
one statement for Allow and one statement for Deny.
Methods that includes conditions will have their own statement in the policy. | 625941caf8510a7c17cf979e |
def learn(self, K, y): <NEW_LINE> <INDENT> self._libsvm.learn(K, y) | :Parameters:
K: 2d array_like object
precomputed training kernel matrix (if kernel=None);
training data in input space (if kernel is a Kernel object)
y : 1d array_like object float(N)
target values (N) | 625941ca66673b3332b92133 |
def detailed_result(self, result): <NEW_LINE> <INDENT> from datetime import datetime <NEW_LINE> response = requests_get(result['url']) <NEW_LINE> logger.info('GET %s', response.url) <NEW_LINE> logger.info('Response code: %s', response.status_code) <NEW_LINE> response.raise_for_status() <NEW_LINE> soup = BeautifulSoup(r... | This will do geotagging, AND add extra info.
* Adds (lat, lng) to result. | 625941ca4428ac0f6e5ba894 |
def get_relevance_scores(passages: List[str], titles: Union[List[str], str], question: str) -> ndarray: <NEW_LINE> <INDENT> _, _, outputs = process_with_dpr_reader(passages, titles, question) <NEW_LINE> return outputs.relevance_logits.numpy() | Computes the relevance score of the passages with respect to a question.
:param passages:
:param titles: a list of corresponding titles (or a single title if all passages are in the same article),
:param question:
:return: the relevance score of the passages with respect to the question. | 625941ca851cf427c661a5b1 |
def get_version_url(self, full_name, packaging, version, descriptor=None): <NEW_LINE> <INDENT> group, artifact = _parse_full_name(full_name) <NEW_LINE> return self._urls.get_url(group, artifact, packaging, version, descriptor) | Get the URL to a specific version of the given project, optionally using
a descriptor to get a particular variant of the version (sources, javadocs, etc.).
The name of the artifact should be composed of the group ID and artifact ID
(if available). E.g. "com.example.project.service". Depending on the repository
layout,... | 625941ca4c3428357757c3ca |
def isPerfectSquare(n: int) -> bool: <NEW_LINE> <INDENT> return int(n ** (1 / 2)) == n ** (1 / 2) | :param n: entier
:return: carré parfait ? | 625941ca10dbd63aa1bd2c46 |
def matrix_to_bytes(data): <NEW_LINE> <INDENT> pick = pickle.dumps(data) <NEW_LINE> return pick | Convert a numpy matrix to an array of bytes to transfer
over the network*
*This is just a simple implementation. In production one should probably not use the pickle
library. One reason against using pickle is that the process of unpickling data after it
has been sent over the network can be maliciously modified to e... | 625941ca1f037a2d8b9462a0 |
def find_all_prime_upto_x(x): <NEW_LINE> <INDENT> prime_numbers = [2] <NEW_LINE> for integer in range(3, x+1, 2): <NEW_LINE> <INDENT> check = 3 <NEW_LINE> while check <= integer**0.5: <NEW_LINE> <INDENT> if integer % check == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> check += 2 <NEW_LINE> <DEDENT> if check > int... | the function finds all the prime numbers up to the int x
:param x: int
:return: list of ints | 625941ca5fcc89381b1e1760 |
def cancel(self, orderNumber): <NEW_LINE> <INDENT> if self.safe_mode : <NEW_LINE> <INDENT> print("Safe Mode enabled!") <NEW_LINE> print("Please GrapheneExchange(config, safe_mode=False) to remove this and execute the transaction below") <NEW_LINE> <DEDENT> account = self.rpc.get_account(self.config.account) <NEW_LINE> ... | Cancels an order you have placed in a given market. Requires
only the "orderNumber". An order number takes the form
``1.7.xxx``.
:param str orderNumber: The Order Object ide of the form ``1.7.xxxx`` | 625941cad7e4931a7ee9dfc0 |
def where(query_index): <NEW_LINE> <INDENT> return query_index.array() | Extract results from a query_index object into a normal numpy array. This
is not usually necessary, as query objects inherit from numpy arrays.
Parameters
----------
query_index: Indices
An Indices object generated by using operators such as "==" on an
indexed column object. The Column methods between and ma... | 625941ca7d847024c06be35d |
def progress_init(self, symbol, units, total, initmsg = None): <NEW_LINE> <INDENT> if not self._progress or total == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> string = "{} 0.0% {} processed".format(self._pfx, units) <NEW_LINE> self._data[symbol] = Logger.ProgressData(0, units, int(self._part*total), 1, total, t... | Initialize progress logging for a long running computation.
Parameters:
symbol (str) : an identifier assigned to the computation
units (str) : the name of the units of computation, in plural, for the
output messages
total (int) : the total number of units of the computation
initmsg (str) : an o... | 625941ca1f5feb6acb0c4bf4 |
def set_augmented(self, index, value): <NEW_LINE> <INDENT> self.augmented[index] = value | set the augmented value on position index to value | 625941caaad79263cf390ae2 |
def get_available_observers( observers_df, n_required, location, need_legal_background, need_from_county ): <NEW_LINE> <INDENT> if location == "outside_AM": <NEW_LINE> <INDENT> assignment_cols = ["assigned_am"] <NEW_LINE> <DEDENT> elif location == "outside_PM": <NEW_LINE> <INDENT> assignment_cols = ["assigned_pm"] <NEW... | Get available observers that can be assigned to precincts
Parameters
----------
observer_df: pd.DataFrame
The observers dataframe
n_required: int
The number of observers required. This is the maximum that will be returned. If
there are few that these available, it will be padded with np.nan
location: strin... | 625941ca8c3a87329515845c |
def __init__(self, status_callback, eng_list=None): <NEW_LINE> <INDENT> log.debug('read YAML file {}'.format(config.appConfYaml)) <NEW_LINE> self.read() <NEW_LINE> self.__engines = {StylishEngine.id():StylishEngine} <NEW_LINE> self.__timesets = {yatimeset.YandexTimeset.id():yatimeset.YandexTimeset} <NEW_LINE> if eng_li... | init with:
status_callback - function called when status changes
signature: status_call(engineobj, statustext, lasterror)
eng_list - specified list of enabled engines. If None, then
all engines is enabled | 625941ca435de62698dfdcef |
def reduce(self, func, **kwargs): <NEW_LINE> <INDENT> return self._dataset_implementation( functools.partial(DataArrayRolling.reduce, func=func), **kwargs ) | Reduce the items in this group by applying `func` along some
dimension(s).
Parameters
----------
func : function
Function which can be called in the form
`func(x, **kwargs)` to return the result of collapsing an
np.ndarray over an the rolling dimension.
**kwargs : dict
Additional keyword arguments pass... | 625941ca07d97122c417892c |
def p_metodos(p): <NEW_LINE> <INDENT> pass | metodos : imprimir
| object | 625941ca31939e2706e4cf0d |
def small_txpuzzle_randfee(from_node, conflist, unconflist, amount, min_fee, fee_increment): <NEW_LINE> <INDENT> DUST_THRESHOLD = 55 <NEW_LINE> assert int(amount*COIN) > DUST_THRESHOLD <NEW_LINE> rand_fee = float(fee_increment)*(1.1892**random.randint(0,28)) <NEW_LINE> fee = min_fee - fee_increment + satoshi_round(rand... | Create and send a transaction with a random fee.
The transaction pays to a trivial P2SH script, and assumes that its inputs
are of the same form.
The function takes a list of confirmed outputs and unconfirmed outputs
and attempts to use the confirmed list first for its inputs.
It adds the newly created outputs to the u... | 625941ca1d351010ab855bbe |
def test_two_past_questions(self): <NEW_LINE> <INDENT> create_question("Past question 30 days", -30) <NEW_LINE> create_question("Past question 1 day", -1) <NEW_LINE> response = self.client.get(reverse("polls:index")) <NEW_LINE> self.assertQuerysetEqual( response.context["latest_question_list"], ["<Question: Past questi... | The questions index page may display multiple questions. | 625941ca07d97122c417892d |
@time_pass <NEW_LINE> def partial_sign(): <NEW_LINE> <INDENT> true_x = scaled_train_x.drop('UNIQUENO', axis=1).fillna(0) <NEW_LINE> true_x['beta_0'] = 1 <NEW_LINE> true_y = train_y['FLAG'] <NEW_LINE> clf = linear_model.LogisticRegression() <NEW_LINE> clf.fit(true_x, true_y) <NEW_LINE> partial_corr = clf.coef_[0][:(scal... | 计算偏相关系数的符号,确保计算综合指标的时候往同一个方向使劲 | 625941ca4d74a7450ccd4266 |
def is_four_of_a_kind(self): <NEW_LINE> <INDENT> if len(self.numbers) != 2: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for num in self.numbers: <NEW_LINE> <INDENT> if self.numbers[num] == 4: <NEW_LINE> <INDENT> return 'Four Of A Kind' <NEW_LINE> <DEDENT> <DEDENT> return False | checker to see if current hand is a four of a kind catergory
:return: return "Three of A Kind" if there there are 3 suits with same num | 625941ca63f4b57ef00011bd |
def prevalence(ground_truth): <NEW_LINE> <INDENT> return sum(ground_truth) / len(ground_truth) | This function tells us what percentage of the dataset has a True (i.e. 1) state | 625941caf9cc0f698b14069e |
def page(self, log=values.unset, message_date_before=values.unset, message_date=values.unset, message_date_after=values.unset, page_token=values.unset, page_number=values.unset, page_size=values.unset): <NEW_LINE> <INDENT> data = values.of({ 'Log': log, 'MessageDate<': serialize.iso8601_date(message_date_before), 'Mess... | Retrieve a single page of NotificationInstance records from the API.
Request is executed immediately
:param unicode log: Filter by log level
:param date message_date_before: Filter by date
:param date message_date: Filter by date
:param date message_date_after: Filter by date
:param str page_token: PageToken provided ... | 625941caa4f1c619b28b00dd |
def dump(self, path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(path, "wb") as fd: <NEW_LINE> <INDENT> pickle.dump(self, fd) <NEW_LINE> <DEDENT> <DEDENT> except (OSError, IOError) as e: <NEW_LINE> <INDENT> LOGGER.error(_("Failed to dump DataPreprocessor to file. Error: {}").format(e)) | Dump the data processor's state to a file.
:param path: Full path to file | 625941ca956e5f7376d70f10 |
@task <NEW_LINE> def clean(): <NEW_LINE> <INDENT> if os.path.isdir(env.deploy_path): <NEW_LINE> <INDENT> local('rm -rf {deploy_path}'.format(**env)) | Delete any built output. | 625941ca21a7993f00bc7d91 |
def parse_state_name(value): <NEW_LINE> <INDENT> if value.upper() in STATE_NAME: <NEW_LINE> <INDENT> return value.upper() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Not a state name') | Check that <value> is one of the USA states. | 625941cac4546d3d9de72ad6 |
def discrete_loop(self): <NEW_LINE> <INDENT> time = 60.0 <NEW_LINE> step = 1.0 / settings.hz <NEW_LINE> steps = int(time/step) <NEW_LINE> assert steps == 6000 <NEW_LINE> for i in range(steps): <NEW_LINE> <INDENT> self.world.Step(step, settings.velocityIterations, settings.positionIterations) <NEW_LINE> self.step() | Step the system for 60 seconds with control possibly applied. | 625941ca046cf37aa974cdeb |
def forwards(self, orm): <NEW_LINE> <INDENT> for book_version in BookVersion.objects.all(): <NEW_LINE> <INDENT> prev_section = None <NEW_LINE> for toc_item in book_version.get_toc(): <NEW_LINE> <INDENT> if toc_item.is_section(): <NEW_LINE> <INDENT> prev_section = toc_item <NEW_LINE> <DEDENT> elif toc_item.is_chapter():... | Write your forwards methods here. | 625941ca2ae34c7f2600d1d4 |
def file_name_gen(): <NEW_LINE> <INDENT> return ''.join( random.choice(u'qwertyuiopasdfghjklzxcvbnm') for i in range(random.randint(5, 10))) | генерирует рандомное имя файла | 625941ca0a50d4780f666f34 |
def __init__(self, graph_list=None): <NEW_LINE> <INDENT> if graph_list == None: <NEW_LINE> <INDENT> graph_list = {} <NEW_LINE> <DEDENT> self.graph_list = graph_list | Initialize the graph list. Create one if it doesn't already exist. | 625941cafb3f5b602dac3735 |
def ParseOpt_game (self, game): <NEW_LINE> <INDENT> self.game = game | -game gamename | 625941ca3346ee7daa2b2e0d |
def deleteNode(self, node): <NEW_LINE> <INDENT> cur = node <NEW_LINE> while cur.next: <NEW_LINE> <INDENT> cur.val = cur.next.val <NEW_LINE> if not cur.next.next: <NEW_LINE> <INDENT> cur.next = None <NEW_LINE> break <NEW_LINE> <DEDENT> cur = cur.next | Only access to the node to be deleted.
:param node: ListNode
:return: None, Do not return anything, modify node in-place instead. | 625941ca2c8b7c6e89b35864 |
def _get_general_project_removal_reasons(google_project_validity): <NEW_LINE> <INDENT> removal_reasons = [] <NEW_LINE> if google_project_validity is None: <NEW_LINE> <INDENT> return removal_reasons <NEW_LINE> <DEDENT> if google_project_validity["user_has_access"] is False: <NEW_LINE> <INDENT> removal_reasons.append("Us... | Get service account removal reason
Args:
google_project_validity(GoogleProjectValidity): google project validity
Returns:
List[str]: the reason(s) project was removed | 625941ca21bff66bcd6849f6 |
def __init__(self, device_info): <NEW_LINE> <INDENT> super(FoscamCamera, self).__init__() <NEW_LINE> ip_address = device_info.get(CONF_IP) <NEW_LINE> port = device_info.get(CONF_PORT) <NEW_LINE> self._base_url = 'http://{}:{}/'.format(ip_address, port) <NEW_LINE> uri_template = self._base_url + 'cgi-bin/CGIP... | Initialize a Foscam camera. | 625941ca5e10d32532c5efc9 |
def __add__(self, other): <NEW_LINE> <INDENT> return self.__binop(other, operator.add, 0) | implement addition
| 625941ca711fe17d8254240f |
def gncEntrySetDateGDate(*args): <NEW_LINE> <INDENT> return _gnucash_core_c.gncEntrySetDateGDate(*args) | gncEntrySetDateGDate(GncEntry entry, GDate date) | 625941ca5fdd1c0f98dc02d6 |
def test_process_releasedate(self): <NEW_LINE> <INDENT> now = DateTime() <NEW_LINE> aDate = self.app.portal.process_releasedate("4/4/1978") <NEW_LINE> self.assertEquals(aDate.year(), 1978, "Year was %s instead of 1978" % aDate.year()) <NEW_LINE> self.assertEquals(aDate.month(), 4, "Month was %s instead of 4" % aDate.mo... | Test process_releasedate | 625941ca5e10d32532c5efca |
def test_swap_k_list_empty(self): <NEW_LINE> <INDENT> list_input = [] <NEW_LINE> a1.swap_k(list_input, 0) <NEW_LINE> list_output = [] <NEW_LINE> self.assertEqual(list_input,list_output) | Test swap_k such that there is no list. | 625941cabe383301e01b5529 |
def drag(self, event): <NEW_LINE> <INDENT> if not self._local_drag_handle_position: <NEW_LINE> <INDENT> self._local_drag_handle_position = self.mapFromScene( event.buttonDownScenePos(Qt.MouseButton.LeftButton)) <NEW_LINE> <DEDENT> self.compute_angle_for_pos(event.scenePos(), self._local_drag_handle_position) <NEW_LINE>... | :param event:
:return: | 625941cad6c5a102081440ed |
def test_set_active(self): <NEW_LINE> <INDENT> self.obj_ss.SetActive(True) <NEW_LINE> self.assertEqual(self.obj_ss.GetActive(), True) <NEW_LINE> self.assertRegex(self.p_mock.stdout.read(), b'emit /org/gnome/ScreenSaver org.gnome.ScreenSaver.ActiveChanged True\n') <NEW_LINE> self.obj_ss.SetActive(False) <NEW_LINE> self.... | SetActive() | 625941ca3317a56b86939cfc |
def get_local_md5(self) -> str: <NEW_LINE> <INDENT> if not self.local_path: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if not os.path.isfile(self.local_path): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> with open(self.local_path, mode='rb') as f: <NEW_LINE> <INDENT> return hashlib.md5(f.read()).hexdige... | Returns a MD5 hash representation of the local repository file.
Returns:
`str` MD5 hash string of the local repository file.
`None` if no local copy exists. | 625941ca4e4d5625662d447b |
def auth_otppin(wrapped_function, *args, **kwds): <NEW_LINE> <INDENT> options = kwds.get("options") or {} <NEW_LINE> g = options.get("g") <NEW_LINE> if g: <NEW_LINE> <INDENT> token = args[0] <NEW_LINE> pin = args[1] <NEW_LINE> clientip = options.get("clientip") <NEW_LINE> user_object = kwds.get("user") <NEW_LINE> if no... | Decorator to decorate the tokenclass.check_pin function.
Depending on the ACTION.OTPPIN it
* either simply accepts an empty pin
* checks the pin against the userstore
* or passes the request to the wrapped_function
:param wrapped_function: In this case the wrapped function should be
:py:func:`privacyidea.lib.t... | 625941ca2eb69b55b151c951 |
def test_override(self): <NEW_LINE> <INDENT> resp = self.preflight('/test_override') <NEW_LINE> self.assertEqual(resp.headers.get(ACL_ALLOW_HEADERS), 'X-Example-Header-A, X-Example-Header-B') | If there is an Access-Control-Request-Method header in the request
and Access-Control-Request-Method is allowed for cross origin
requests and request method is OPTIONS,
the Access-Control-Allow-Headers header should be echoed back. | 625941ca97e22403b379d03d |
def n_to_m_grams(tokens, n, m): <NEW_LINE> <INDENT> keyphrases = [] <NEW_LINE> for k in range(n, m + 1): <NEW_LINE> <INDENT> keyphrases = list(set(keyphrases) | set(n_grams(tokens, k))) <NEW_LINE> <DEDENT> return keyphrases | Constructs a list of N-grams for N = n..m.
@param tokens: The tokenized text to represent with n-grams.
@type tokens: C{list(string)}
@param n: The minimum length of a n-gram.
@type n: C{int}
@param m: The maximum length of a n-gram.
@type m: C{int}
@return: A list n..m-grams... | 625941ca66656f66f7cbc24e |
def make_histlist(fr_list, bins): <NEW_LINE> <INDENT> hist_list = [] <NEW_LINE> for frame in fr_list: <NEW_LINE> <INDENT> hist = plt.hist(frame.flatten(), bins) <NEW_LINE> hist_list.append(hist) <NEW_LINE> plt.close() <NEW_LINE> <DEDENT> return hist_list | creates a list of all histogram values for fr_list | 625941ca24f1403a92600c0a |
def clone(self, scale=1.0, filterMaskedVerts=False): <NEW_LINE> <INDENT> other = type(self)(self.name, self.vertsPerPrimitive) <NEW_LINE> for prop in ['cameraMode', 'visibility', 'pickable', 'calculateTangents', 'priority', 'MAX_FACES']: <NEW_LINE> <INDENT> setattr(other, prop, getattr(self, prop)) <NEW_LINE> <DEDENT> ... | Create a clone of this mesh, with adapted scale.
If filterVerts is True, all vertices that are not required (do not
belong to any visible face) are removed and vertex mapping is added to
cloned object (see filterMaskedVerts()). For a face mapping, the
facemask of the original mesh can be used. | 625941ca6e29344779a626b5 |
def test_inplace_dict(self): <NEW_LINE> <INDENT> df = ROOT.RDF.MakeNumpyDataFrame({"x": np.array([1, 2, 3], dtype="float32")}) <NEW_LINE> self.assertEqual(df.Mean("x").GetValue(), 2) | Test behaviour with inplace dictionary | 625941ca01c39578d7e74ede |
def crossover(parent1, parent2, rate, lock): <NEW_LINE> <INDENT> if not isinstance(parent1, Model) or not isinstance(parent2, Model): <NEW_LINE> <INDENT> raise TypeError('Two keras.engine.training.Model expected,', type(parent1), 'and', type(parent2), 'found') <NEW_LINE> <DEDENT> with lock: <NEW_LINE> <INDENT> child1 =... | This function performs the crossover between two keras models
:param parent1: the first parent Neural Network of type keras.engine.training.Model
:param parent2: the second parent Neural Network of type keras.engine.training.Model
:param rate: the crossover rate, expressed as a real number between 0 and 1
:param lock: ... | 625941ca76e4537e8c351715 |
def parse_CA(self, content): <NEW_LINE> <INDENT> self.category = content.rstrip('.') <NEW_LINE> return | Parses AC lines. | 625941ca4527f215b584c4fa |
def get_in_queue(request, doc_id): <NEW_LINE> <INDENT> doc = get_object_of_class(doc_id) <NEW_LINE> if not doc.outstanding: <NEW_LINE> <INDENT> element = RequestQueueElement.objects.create(document=doc, user=request.user, date=datetime.date.today()) <NEW_LINE> element.priority = element.default_priority() <NEW_LINE> el... | Get user into queue.
:param request: HTTP request.
:param doc_id: document id.
:return: HTTP redirect to document detail page. | 625941ca67a9b606de4a7f5d |
def GetLabels(self): <NEW_LINE> <INDENT> return _itkLabelGeometryImageFilterPython.itkLabelGeometryImageFilterIUL3ID3_GetLabels(self) | GetLabels(self) -> vectorUL | 625941cabf627c535bc13272 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.