code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def close(self): <NEW_LINE> <INDENT> self._cur.close() <NEW_LINE> self._conn.close() <NEW_LINE> self.connected = False | Close the database connection. | 625941b730dc7b766590179d |
@csrf_protect <NEW_LINE> @transaction.commit_on_success <NEW_LINE> def post_comment(request, context, parent_id=None): <NEW_LINE> <INDENT> opts = CommentOptionsObject.objects.get_for_object(context['object']) <NEW_LINE> if opts.blocked: <NEW_LINE> <INDENT> raise Http404('Comments are blocked for this object.') <NEW_LIN... | Mostly copy-pasted from django.contrib.comments.views.comments | 625941b707d97122c41786be |
def _calculate_closest_point(self, pos): <NEW_LINE> <INDENT> v1 = pos - self.wp_start <NEW_LINE> v2 = self.wp_end - self.wp_start <NEW_LINE> t = v1 @ v2 / v2.squaredNorm() <NEW_LINE> pt = self.wp_start + t * v2 <NEW_LINE> return (t, pt) | Calculate closest point | 625941b756b00c62f0f14490 |
def is_light(self): <NEW_LINE> <INDENT> return False | :return: True if this is a light | 625941b731939e2706e4cca3 |
def draw_volume(ax, xpos, ypos, width, height, depth, **kwargs): <NEW_LINE> <INDENT> patches = [] <NEW_LINE> off = depth / np.sqrt(2) <NEW_LINE> if depth > 0: <NEW_LINE> <INDENT> patches.append(mpatch.Polygon([(xpos, ypos + height), (xpos - off, ypos + height + off), (xpos - off + width, ypos + height + off), (xpos + w... | Draw a volume | 625941b73eb6a72ae02ec30d |
def string_similarity(first, second): <NEW_LINE> <INDENT> return SequenceMatcher(a=first, b=second).ratio() | Returns the degree of similarity between two strings | 625941b74a966d76dd550e3f |
@raises(TypeError) <NEW_LINE> def test_register_noncallable_plugin(): <NEW_LINE> <INDENT> pyblish.plugin.register_plugin("NotValid") | Registered plug-ins must be callable | 625941b7a17c0f6771cbde87 |
def upload_image(data): <NEW_LINE> <INDENT> q=qiniu.Auth(access_key,secret_key) <NEW_LINE> token=q.upload_token(bucket_name) <NEW_LINE> ret,info=qiniu.put_data(token,None,data) <NEW_LINE> if 200==info.status_code: <NEW_LINE> <INDENT> return ret.get('key') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception('上... | 上传图片方法 | 625941b7e1aae11d1e749ae7 |
def vaporize(vape_me): <NEW_LINE> <INDENT> normal = u' 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~' <NEW_LINE> wide = u' 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!゛#$%&()*+、ー。/:;〈=〉?@[\\]^_‘{|}~' <NEW_LINE> widemap = dict((ord(x[0]), x[1]) for x in... | Solution shamelessly stolen from http://stackoverflow.com/a/8327034
by Ignacio Vazquez-Abrams | 625941b763f4b57ef0000f55 |
def gens_reduced(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> dummy = self.is_principal() <NEW_LINE> return self.__reduced_generators <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> L = self.number_field() <NEW_LINE> gens = L.pari_rnf().rnfidealtwoelt(self.pari_rhnf()) <NEW_LINE> gens = [L(x, chec... | Return a small set of generators for this ideal. This will always
return a single generator if one exists (i.e. if the ideal is
principal), and otherwise two generators.
EXAMPLE::
sage: K.<a, b> = NumberField([x^2 + 1, x^2 - 2])
sage: I = K.ideal((a + 1)*b/2 + 1)
sage: I.gens_reduced()
(1/2*b*a + 1/2*... | 625941b7377c676e91271fdd |
def get_last_reset_date(self): <NEW_LINE> <INDENT> last_reset_date = pd.DataFrame(index=self.index) <NEW_LINE> last_reset_date.loc[self.reset_date, 'last_reset_date'] = list(self.reset_date) <NEW_LINE> last_reset_date.ffill(inplace=True) <NEW_LINE> self.__last_reset_date = last_reset_date | last_reset_date: DataFrame of the last reset date for each trade day
NB! use reset_date but not last_reset_date sometimes is for
faster calculations | 625941b791f36d47f21ac329 |
@ops.RegisterGradient("Exit") <NEW_LINE> def _ExitGrad(op, grad): <NEW_LINE> <INDENT> graph = ops.get_default_graph() <NEW_LINE> grad_ctxt = graph._get_control_flow_context() <NEW_LINE> if not grad_ctxt.back_prop: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if op._get_control_flow_context().grad_state: <NEW_LIN... | Gradients for an exit op are calculated using an Enter op. | 625941b7dc8b845886cb5367 |
def norm1(tuple): <NEW_LINE> <INDENT> return dist(tuple, tuple) | Norm 1 | 625941b77d43ff24873a2ad7 |
def execute(self, context): <NEW_LINE> <INDENT> aws_hook = AwsHook(self.aws_credentials_id) <NEW_LINE> credentials = aws_hook.get_credentials() <NEW_LINE> redshift = PostgresHook(postgres_conn_id=self.redshift_conn_id) <NEW_LINE> self.log.info('Clearing data from {}'.format(self.table)) <NEW_LINE> redshift.run('DELETE ... | Executes task for staging to redshift.
Args:
context (:obj:`dict`): Dict with values to apply on content.
| 625941b78e71fb1e9831d5e0 |
def parse_args(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description='Bayesian neural networks demo.') <NEW_LINE> group = parser.add_mutually_exclusive_group() <NEW_LINE> group.add_argument('--show', action='store_true', help='show the dataset') <NEW_LINE> group.add_argument('--mle', action='store_true', ... | Returns an object describing the command line. | 625941b7d7e4931a7ee9dd4f |
def _set_n_classes(self, y): <NEW_LINE> <INDENT> self._classes = 2 <NEW_LINE> if y is not None: <NEW_LINE> <INDENT> check_classification_targets(y) <NEW_LINE> self._classes = len(np.unique(y)) <NEW_LINE> warnings.warn( "y should not be presented in unsupervised learning.") <NEW_LINE> <DEDENT> return self | Set the number of classes if `y` is presented, which is not
expected. It could be useful for multi-class outlier detection.
Parameters
----------
y : numpy array of shape (n_samples,)
Ground truth.
Returns
-------
self | 625941b7d10714528d5ffb12 |
def disconnect(self): <NEW_LINE> <INDENT> self.wrapped.Disconnect() | Stop and delete this session. | 625941b763f4b57ef0000f56 |
def model_traveltimes(self,phase): <NEW_LINE> <INDENT> model = ob.taup.tau.TauPyModel(model="iasp91") <NEW_LINE> if self.BHN[0].stats.sac.evdp >= 1000: <NEW_LINE> <INDENT> traveltime = model.get_travel_times((self.BHN[0].stats.sac.evdp/1000),self.BHN[0].stats.sac.gcarc,[phase])[0].time <NEW_LINE> <DEDENT> elif self.BHN... | Function to run TauP traveltime models for the SKS phase.
Returns SKS predictided arrivals (seconds), origin time of the event (t0) as a UTCDateTime obejct and the SKS arrival as a UTCDateTime object
tr - trace object for which SKS arrival time will be predicted | 625941b726068e7796caeb0b |
def generate_file(self, output, report_name, report): <NEW_LINE> <INDENT> current_dir = os.getcwd() <NEW_LINE> dir_to = os.path.join(current_dir, 'reports', output) <NEW_LINE> if not os.path.exists(dir_to): <NEW_LINE> <INDENT> os.makedirs(dir_to) <NEW_LINE> <DEDENT> path_file = os.path.join(dir_to, report_name) <NEW_LI... | Generate the report file in the given path. | 625941b726068e7796caeb0c |
def test_no_ellipses(self): <NEW_LINE> <INDENT> config_dict = make_ci_json_config(2591, path=None) <NEW_LINE> module_list = config_dict["module_list"] <NEW_LINE> module_list_split = module_list.split(",") <NEW_LINE> assert not any([".." in x for x in module_list_split]) | Ensure the literal 'obspy....' is not in the module list. | 625941b7090684286d50eb13 |
def id(self): <NEW_LINE> <INDENT> return 'VQI algorithms' | Returns the unique provider id, used for identifying the provider. This
string should be a unique, short, character only string, eg "qgis" or
"gdal". This string should not be localised. | 625941b7097d151d1a222c8f |
def xml2dict(node): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for element in node.iterchildren(): <NEW_LINE> <INDENT> key = element.tag.split('}')[1] if '}' in element.tag else element.tag <NEW_LINE> if element.text and element.text.strip(): <NEW_LINE> <INDENT> value = element.text <NEW_LINE> <DEDENT> else: <NEW_LINE>... | Converts an lxml.etree to dict for a quick test of conversion results | 625941b7d164cc6175782b81 |
def MyFn(clinSig): <NEW_LINE> <INDENT> if 'Definitive' in clinSig: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> if 'Strong' in clinSig: <NEW_LINE> <INDENT> return 2 <NEW_LINE> <DEDENT> if 'Moderate' in clinSig: <NEW_LINE> <INDENT> return 3 <NEW_LINE> <DEDENT> if 'Limited' in clinSig: <NEW_LINE> <INDENT> return 4 <N... | This function orders the Clinical Validity classification based on ranking | 625941b7fbf16365ca6f5fef |
def update_tree_status(session, tree, status=None, reason=None, tags=[], message_of_the_day=None): <NEW_LINE> <INDENT> if status is not None: <NEW_LINE> <INDENT> tree.status = status <NEW_LINE> <DEDENT> if reason is not None: <NEW_LINE> <INDENT> tree.reason = reason <NEW_LINE> <DEDENT> if message_of_the_day is not None... | Update the given tree's status; note that this does not commit
the session. Supply a tree object or name. | 625941b77c178a314d6ef28c |
def test_command_has_correct_address(self): <NEW_LINE> <INDENT> address = self.command[1][0] <NEW_LINE> self.assertEqual(0xdeadbeef, address) | Checks that the address is put at the correct place in the command. | 625941b75166f23b2e1a4f8c |
def DecodePacket(self, packet): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> (self.code, self.id, length, self.authenticator) = struct.unpack('!BBH16s', packet[0:20]) <NEW_LINE> <DEDENT> except struct.error: <NEW_LINE> <INDENT> raise PacketError('Packet header is corrupt') <NEW_LINE> <DEDENT> if len(... | Initialize the object from raw packet data. Decode a packet as
received from the network and decode it.
:param packet: raw packet
:type packet: string | 625941b715baa723493c3da5 |
def get_traceflow_with_http_info(self, traceflow_id, **kwargs): <NEW_LINE> <INDENT> all_params = ['traceflow_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_LINE> ... | Get the Traceflow round status and result summary # noqa: E501
Get the Traceflow round status and result summary # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_traceflow_with_http_info(traceflow_id, async_req... | 625941b7b7558d58953c4d4f |
def compute_distances_two_loops(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> for i in range(num_test): <NEW_LINE> <INDENT> for j in range(num_train): <NEW_LINE> <INDENT> dists[i, j] = np.sqrt(((X[i] - self.... | Compute the distance between each test point in X and each training point
in self.X_train using a nested loop over both the training data and the
test data.
Inputs:
- X: A numpy array of shape (num_test, D) containing test data.
Returns:
- dists: A numpy array of shape (num_test, num_train) where dists[i, j]
is th... | 625941b78e71fb1e9831d5e1 |
def LCDdrawString(x, y, message, update=True): <NEW_LINE> <INDENT> if not EXT_LCD_1: <NEW_LINE> <INDENT> printDebug("LCDdrawString not implemented on Sparki", DEBUG_CRITICAL) <NEW_LINE> raise NotImplementedError <NEW_LINE> <DEDENT> printDebug("In LCDdrawString, x is " + str(x) + ", y is " + str(y) + ", message is " + s... | Prints message on the LCD on Sparki at the given x,y coordinate
arguments:
x - int x coordinate (the location where the text starts) -- can be from 0 to 121 (inclusive)
y - int y coordinate (the line number where the text states) -- can be from 0 to 7 (inclusive)
message - string that you want to display
update - True... | 625941b7099cdd3c635f0a90 |
@decorators.has_journal <NEW_LINE> @decorators.production_user_or_editor_required <NEW_LINE> def typesetting_delete_galley(request, galley_id): <NEW_LINE> <INDENT> galley = get_object_or_404( core_models.Galley, pk=galley_id, article__journal=request.journal, ) <NEW_LINE> article = galley.article <NEW_LINE> galley.dele... | Allows users with permission to delete files | 625941b7ac7a0e7691ed3f0d |
def __init__(self, *args): <NEW_LINE> <INDENT> if len(args) > 2: <NEW_LINE> <INDENT> self.parse_input(task_id=int(args[0]), input_str=" ".join([str(x) for x in args[1:] if x is not None])) | :param task_id: Task id
:param p_time: processing time
:param r_time: ready time
:param d_time: due time
:param w: weight of task | 625941b78a43f66fc4b53e9d |
def test_constructor(self): <NEW_LINE> <INDENT> instruction = Bus(32) <NEW_LINE> c = Bus(1) <NEW_LINE> v = Bus(1) <NEW_LINE> n = Bus(1) <NEW_LINE> z = Bus(1) <NEW_LINE> pcwr = Bus(1, 0) <NEW_LINE> regsa = Bus(1, 0) <NEW_LINE> regsb = Bus(1, 0) <NEW_LINE> regdst = Bus(2, 0) <NEW_LINE> regwrs = Bus(2, 0) <NEW_LINE> wdbs ... | tests 4 bad constructors - not all possible constructors tested | 625941b776d4e153a657e963 |
def handle_starttag(self, tag, attributes): <NEW_LINE> <INDENT> if tag == 'td': <NEW_LINE> <INDENT> for key, value in attributes: <NEW_LINE> <INDENT> if key == 'class' and value == 'xl65': <NEW_LINE> <INDENT> self.isDate = True <NEW_LINE> self.dateCounter += 1 <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else... | attributes would be: class=, height=, align, style, whatever. Value is the part after.
The tags attributes are listed as tuples.
:param tag:
:param attributes:
:return: | 625941b73d592f4c4ed1ceb4 |
def _serialize_table_record_field_name(self, remote_schema, path, value_json_schema): <NEW_LINE> <INDENT> simple_json_schema = json_schema.simple_type(value_json_schema) <NEW_LINE> mapping = self._get_mapping(remote_schema, path, simple_json_schema) <NEW_LINE> if not mapping is None: <NEW_LINE> <INDENT> return mapping ... | Returns the appropriate remote field (column) name for `path`.
:param remote_schema: TABLE_SCHEMA(remote)
:param path: (string, ...)
:value_json_schema: dict, JSON Schema
:return: string | 625941b7d10714528d5ffb13 |
def file(fn): <NEW_LINE> <INDENT> return renpy.loader.load(fn) | :doc: file
Returns a read-only file-like object that accesses the file named `fn`. The file is
accessed using Ren'Py's standard search method, and may reside in an RPA archive.
or as an Android asset.
The object supports a wide subset of the fields and methods found on Python's
standard file object, opened in binary ... | 625941b77b25080760e3928e |
def force_refresh(self): <NEW_LINE> <INDENT> raise NotImplementedError | Force refresh of the worker. | 625941b763d6d428bbe44323 |
def delete(self, section, user=None): <NEW_LINE> <INDENT> if (user, section) in self.values: <NEW_LINE> <INDENT> del self.values[user, section] <NEW_LINE> <DEDENT> self.db.deleteConfig(section, user) <NEW_LINE> self.core.evm.dispatchEvent("config:deleted", section, user) | Deletes values saved in db and cached values for given user, NOT meta data
Does not trigger an error when nothing was deleted. | 625941b7925a0f43d2549ca7 |
def reset_modified_properties(self): <NEW_LINE> <INDENT> self.modified_properties = set([]) | On init, or save, reset our modified properties. | 625941b7eab8aa0e5d26d992 |
def _repr_(self): <NEW_LINE> <INDENT> if self._X is None: <NEW_LINE> <INDENT> return "An invertible discrete dynamical system with unspecified ground set" <NEW_LINE> <DEDENT> return "An invertible discrete dynamical system with ground set " + repr(self._X) | String representation of ``self``.
EXAMPLES::
sage: D = DiscreteDynamicalSystem(NN, lambda x: (x + 2 if x % 4 < 2 else x - 2), inverse=True)
sage: D # indirect doctest
An invertible discrete dynamical system with ground set
Non negative integer semiring
sage: D = DiscreteDynamicalSystem(None, lam... | 625941b76e29344779a62449 |
def ravel(u): <NEW_LINE> <INDENT> ur = nm.ravel(u)[:, None] <NEW_LINE> return ur | Returns view into the input array reshaped from (m, n, 1) to (n*m, 1)
to (m, n, 1) .
Parameters
----------
u : array_like
Returns
-------
u : ndarray | 625941b7283ffb24f3c55740 |
def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | Compare two graphs for inequality.
@param other: The other graph.
@type other: L{Graph}
@return: True if not equal, false otherwise.
@rtype: C{bool} | 625941b782261d6c526ab2d7 |
def setup(): <NEW_LINE> <INDENT> _username = "" <NEW_LINE> _apikey = "" <NEW_LINE> _server = " [%s]" % "http://cloud.yhathq.com" <NEW_LINE> if has(): <NEW_LINE> <INDENT> creds = read() <NEW_LINE> _username = " [%s]" % creds["username"] <NEW_LINE> _apikey = " [%s]" % creds["apikey"] <NEW_LINE> _server = " [%s]" % creds[... | Prompts the user for their credentials and the saves them to a Yhat "dot"
file. | 625941b70a50d4780f666cc3 |
def test_evaluate_no_exog_against_with_exog(): <NEW_LINE> <INDENT> y, X = load_longley() <NEW_LINE> forecaster = ARIMA(suppress_warnings=True) <NEW_LINE> cv = SlidingWindowSplitter() <NEW_LINE> scoring = MeanAbsolutePercentageError(symmetric=True) <NEW_LINE> out_exog = evaluate(forecaster, cv, y, X=X, scoring=scoring) ... | Check that adding exogenous data produces different results. | 625941b7004d5f362079a16b |
def explicitly_close_queues(self): <NEW_LINE> <INDENT> self.safe_close_queue('input', self.input_queue) <NEW_LINE> self.safe_close_queue('output', self.output_queue) | Explicitly join queues, so that we'll get "stuck" in something that's
more easily debugged than multiprocessing.
NOTE: It's tempting to call self.output_queue.cancel_join_thread(),
but this seems to leave us in a bad state in practice (reproducible
via existing tests). | 625941b72c8b7c6e89b355f7 |
def to_datetime(self): <NEW_LINE> <INDENT> return datetime.datetime.fromtimestamp(0, _utc) + datetime.timedelta( seconds=self.to_unix() ) | Get the timestamp as a UTC datetime.
Python 2 is not supported.
:rtype: datetime. | 625941b78a349b6b435e7fa8 |
def _setError(self, error, errorString): <NEW_LINE> <INDENT> self._error = error <NEW_LINE> self._errorString = errorString <NEW_LINE> self.errorOccured.emit(error, errorString) <NEW_LINE> self._setFinished(True) | Sets the error state of this reply to error and the textual
representation of the error to errorString.
This wil also cause error() and finished() signals to be emitted, in that
order.
@param error: The error number
@type error: int
@param errorString: The errorstring (dev errorstring, not public)
@type errorStri... | 625941b75510c4643540f22c |
def _SetCommonResponseHeaders(self): <NEW_LINE> <INDENT> frame_policy = self.app.config.get('framing_policy', constants.DENY) <NEW_LINE> frame_header_value = constants.X_FRAME_OPTIONS_VALUES.get(frame_policy, '') <NEW_LINE> if frame_header_value: <NEW_LINE> <INDENT> self.response.headers['X-Frame-Options'] = frame_head... | Sets various headers with security implications. | 625941b70a366e3fb873e64b |
def luminance(rgb): <NEW_LINE> <INDENT> Y = sum(coeff*color for coeff,color in zip([0.2126,0.7152,0.0722],rgb)) <NEW_LINE> return Y | find luminance from rgba color using BT.709 standard, formula:
Y = (0.2126R+0.7152G+0.0722B)*alpha assume all elements are put on top of
white background. See <https://en.wikipedia.org/wiki/YUV> | 625941b7462c4b4f79d1d504 |
def dygraph_params_to_static(model, dygraph_tensor_dict): <NEW_LINE> <INDENT> state_dict = model.state_dict() <NEW_LINE> ret_dict = dict() <NEW_LINE> for name, parm in state_dict.items(): <NEW_LINE> <INDENT> ret_dict[parm.name] = dygraph_tensor_dict[name] <NEW_LINE> <DEDENT> return ret_dict | Simple tool for convert dygraph paramters to static paramters dict.
**NOTE** The model must both support static graph and dygraph mode.
Args:
model (nn.Layer): the model of a neural network.
dygraph_tensor_dict (string): path of which locate the saved paramters in static mode.
Returns:
[tensor dict]: a s... | 625941b7498bea3a759b98e6 |
def thomson_spec_diff(eleckineng, photeng, T, as_pairs=False): <NEW_LINE> <INDENT> print('***** Computing Spectra by Expansion in beta ...', end='') <NEW_LINE> gamma = eleckineng/phys.me + 1 <NEW_LINE> beta = np.sqrt(eleckineng/phys.me*(gamma+1)/gamma**2) <NEW_LINE> testing = False <NEW_LINE> if testing: <NEW_LINE> <IN... | Thomson ICS spectrum of secondary photons by beta expansion.
Parameters
----------
eleckineng : ndarray
Incoming electron kinetic energy.
photeng : ndarray
Outgoing photon energy.
T : float
CMB temperature.
as_pairs : bool
If true, treats eleckineng and photeng as a paired list: produces eleckineng.s... | 625941b799cbb53fe6792a1b |
def gelu(x): <NEW_LINE> <INDENT> import math <NEW_LINE> return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0))) | Implementation of the gelu activation function.
For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
Also see https://arxiv.org/abs/1606.08415 | 625941b75f7d997b871748cf |
def get_interactions(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fingerprint = get_and_check_fingerprint(validate_token=False) <NEW_LINE> interactions = get_db().get_interactions_fingerprint(fingerprint) <NEW_LINE> <DEDENT> except Exception as _: <NEW_LINE> <INDENT> LOG.exception("Got exception on get_db().get_inte... | Return a list of all the interactions for an associated fingerprint
Returns:
str: json list containing one dictionary for each event | 625941b7be383301e01b52c1 |
def firme_msoffice(self, identidad, documento, algoritmo_hash='Sha512', hash_doc=None, resumen='', id_funcionalidad=-1): <NEW_LINE> <INDENT> logger.info({'message': "Firmador: firme_msoffice", 'data': {'identity': identidad, 'hash_doc': hash_doc}, 'location': __file__}) <NEW_LINE> logger.debug({'message': "Firmador: fi... | Firma un documento del tipo Microsoft office.
.. note::
Los parámetros exceptuando formato (no existe en este método) son idénticos que los
de firme, además los resultados retornados son también idénticos. | 625941b74c3428357757c15f |
def __init__(self, random_state, no_op, best_sampling=True, representation_checkpoint=None, create_environment_fn=create_atari_environment, game_name='Pong', game_version='v0', sticky_actions=False, epsilon_eval=0.01, checkpoint_file_prefix='ckpt'): <NEW_LINE> <INDENT> self.random_state = random_state <NEW_LINE> self._... | Initialize the Runner object in charge of running a full experiment.
This constructor will take the following actions:
1. Initialize an environment.
2. Initialize a `tf.Session`.
3. Initialize a logger.
4. Initialize two agents, one as an actor, one as a policy evaluator.
5. Reload from the latest checkpoi... | 625941b7de87d2750b85fbc2 |
def list(self): <NEW_LINE> <INDENT> self._require('id') <NEW_LINE> self._pretty_print(self.dbaas.quota.show, self.id) | List all quotas for a tenant | 625941b701c39578d7e74c78 |
def length_ll(self): <NEW_LINE> <INDENT> current = self.head <NEW_LINE> length = 0 <NEW_LINE> while current: <NEW_LINE> <INDENT> length += 1 <NEW_LINE> current = current.next <NEW_LINE> <DEDENT> return length | method to get lenght of the list | 625941b76aa9bd52df036bd6 |
def test_got_data(self): <NEW_LINE> <INDENT> driver = InstrumentDriver(self._got_data_event_callback) <NEW_LINE> self.assert_initialize_driver(driver) <NEW_LINE> self.assert_raw_particle_published(driver, True) <NEW_LINE> self.assert_particle_published(driver, self.METBK_STATUS_DATA, self.assert_data_particle_status, T... | Verify sample data passed through the got data method produces the correct data particles | 625941b7f9cc0f698b14043a |
def get_last_finished_gameweek(): <NEW_LINE> <INDENT> event_data = fetcher.get_event_data() <NEW_LINE> last_finished = 0 <NEW_LINE> for gw in sorted(event_data.keys()): <NEW_LINE> <INDENT> if event_data[gw]["is_finished"]: <NEW_LINE> <INDENT> last_finished = gw <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return last_... | query the API to see what the last gameweek marked as 'finished' is. | 625941b792d797404e303fbe |
def crawler(path, seasons, liga, resultsonly=False): <NEW_LINE> <INDENT> print(f"CRAWLING LIGA {liga} FROM {seasons[0]} to {seasons[-1]}") <NEW_LINE> datadir = f"{path}/data/league_{liga}" <NEW_LINE> if not os.path.exists(datadir): <NEW_LINE> <INDENT> os.mkdir(datadir) <NEW_LINE> <DEDENT> if not os.path.exists(f"{datad... | Crawls through the seasons.
1. Download game results if not yet existent
- assign game_id
- collect link to match information
2. process game results and export to HD
3. download match details if not yet existent
4. process match details
- lineups
- goals
- bookings
- other (date, place, attenda... | 625941b7cb5e8a47e48b78e4 |
def design_variables(self): <NEW_LINE> <INDENT> dvars = set() <NEW_LINE> for p in self.potentials.pair.potentials: <NEW_LINE> <INDENT> for x in p.coeff.design_variables(): <NEW_LINE> <INDENT> if not x.const: <NEW_LINE> <INDENT> dvars.add(x) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return tuple(dvars) | Return all unique, non-constant :class:`~relentless.variable.DesignVariable`\s
parametrized by the pair potentials of the relative entropy.
Returns
-------
tuple
The :class:`~relentless.variable.DesignVariable` parameters. | 625941b78a43f66fc4b53e9e |
def setupunitbuttons(self, canvas): <NEW_LINE> <INDENT> y = 10 <NEW_LINE> ids = list() <NEW_LINE> texts = ('Previous page', 'Next page') <NEW_LINE> largest = 0 <NEW_LINE> lineoffset = 0 <NEW_LINE> n = 0 <NEW_LINE> for p in texts: <NEW_LINE> <INDENT> id = canvas.create_text(14, 14, anchor=Tix.NW, text=p, state=Tix.DISAB... | This method draws the unit stats navigation 'buttons' on the specified canvas and binds events to the them | 625941b724f1403a9260099e |
def add_variables(self, variables, optimizer=None, learning_rate=None, other_params={}): <NEW_LINE> <INDENT> chck_vars = self.check_variables(variables) <NEW_LINE> if chck_vars: <NEW_LINE> <INDENT> raise ValueError('Expected all new variables, got overlap', *[v.name for v in chck_vars]) <NEW_LINE> <DEDENT> self.variabl... | Adds Variables and optimizers with different parameters.
variables (list of tf.variables): the variables to optimize wrt.
Either:
optimizer (tf.train.Optimizer): The corresponding optimizer.
Or:
learning_rate (float): A learning rate to pass to the default_optimizer
other_params (dict): A dictionary of param_name, va... | 625941b7f8510a7c17cf9539 |
def remove_slogan(name): <NEW_LINE> <INDENT> pos = name.find(',') <NEW_LINE> if pos < 0: <NEW_LINE> <INDENT> pos = name.find(' - ') <NEW_LINE> <DEDENT> if 0 < pos < len(name) - 1: <NEW_LINE> <INDENT> _name_parts = name[pos + 1:].split() <NEW_LINE> if _name_parts[0].lower() in {'a', 'an', 'the'}: <NEW_LINE> <INDENT> ret... | Remove slogan from :name
====================
Args:
name (str): company name
Returns:
(str): the processed company name without slogan | 625941b7c4546d3d9de72865 |
def crop(self,filename,left, upper, right,lower,target_filename): <NEW_LINE> <INDENT> im=Image.open(filename) <NEW_LINE> box = (left, upper, right,lower) <NEW_LINE> region = im.crop(box) <NEW_LINE> region_filename=os.path.join(self.target_dir,target_filename) <NEW_LINE> print(region_filename) <NEW_LINE> region.save(reg... | 裁剪图片,filename为绝对路径,target_filename为文件名 | 625941b7e8904600ed9f1d5d |
def get_encrypt(self, plain_text): <NEW_LINE> <INDENT> return self.dynamicCall('GetEncrpyt(p)', plain_text) | 기능: 평문을 암호화한다(계좌비밀번호 암호화 등에 사용된다.)
:param plain_text: 평문
:return: 암호화된 문자열 | 625941b7d99f1b3c44c673cc |
def __init__(self, A, args): <NEW_LINE> <INDENT> if args.distance_func == 'euclidean': <NEW_LINE> <INDENT> distances = euclidean_distance_matrix(A) <NEW_LINE> <DEDENT> elif args.distance_func == 'haversine': <NEW_LINE> <INDENT> distances = haversine_distance_matrix(A) <NEW_LINE> <DEDENT> elif args.distance_func == 'osr... | Initialize distance matrix. | 625941b710dbd63aa1bd29e4 |
def test_peerkey_pairwise_mismatch(dev, apdev): <NEW_LINE> <INDENT> skip_with_fips(dev[0]) <NEW_LINE> wt = Wlantest() <NEW_LINE> wt.flush() <NEW_LINE> wt.add_passphrase("12345678") <NEW_LINE> ssid = "test-peerkey" <NEW_LINE> passphrase = "12345678" <NEW_LINE> params = hostapd.wpa2_params(ssid=ssid, passphrase=passphras... | RSN TKIP+CCMP AP and PeerKey between two STAs using different ciphers | 625941b72eb69b55b151c6df |
def search(self, x): <NEW_LINE> <INDENT> current_node = self.head <NEW_LINE> while current_node: <NEW_LINE> <INDENT> if current_node.value == x: <NEW_LINE> <INDENT> return current_node <NEW_LINE> <DEDENT> current_node = current_node.next <NEW_LINE> <DEDENT> return | 通过值搜索出节点
| 625941b7d8ef3951e3243372 |
def p_grammar(p): <NEW_LINE> <INDENT> g = Model.Grammar() <NEW_LINE> for k,v in p[3].items(): <NEW_LINE> <INDENT> if k == 'name': <NEW_LINE> <INDENT> g.setName(v) <NEW_LINE> <DEDENT> elif k == 'chain': <NEW_LINE> <INDENT> if type(v) == ListType: <NEW_LINE> <INDENT> for gg in v: <NEW_LINE> <INDENT> g.addChain( gg ) <NEW... | grammar : BO GRAMMAR grammar_components BC
| 625941b7d4950a0f3b08c18f |
def interpret(self, input=None): <NEW_LINE> <INDENT> if isinstance(input, (type(None), basestring)): <NEW_LINE> <INDENT> input = self.decode(input) <NEW_LINE> <DEDENT> return self.interpret_opcodes(input) | Interprets an explicit or implicit `input´ "sequence" if given.
:param input:
If None or not given -> A fresh packet will be read from the socket. Then the packet will be decode().
If a basestring -> It will also be decode().
After what the result of decode() (a generator which yields 2-tuple(value_type, ... | 625941b7d164cc6175782b82 |
def _update_meta(conn_string: str) -> None: <NEW_LINE> <INDENT> url = urlparse(conn_string) <NEW_LINE> Meta.conn_string = conn_string <NEW_LINE> Meta.DBNAME = url.path[1:] <NEW_LINE> Meta.DBUSER = url.username <NEW_LINE> Meta.DBPWD = url.password <NEW_LINE> Meta.DBHOST = url.hostname <NEW_LINE> Meta.DBPORT = url.port <... | Update Meta class. | 625941b760cbc95b062c637e |
def monster_kill(self): <NEW_LINE> <INDENT> self.__monster_kills += 1 <NEW_LINE> self.__progress +=1 | Adds 1 to the monster kills and 1 to the progress | 625941b71f037a2d8b946034 |
def readKnobs(self,s): <NEW_LINE> <INDENT> pass | self.readKnobs(s) -> None.
Read the knobs from a string (TCL syntax).
@param s: A string.
@return: None. | 625941b716aa5153ce3622ad |
def on_body(self, body: bytes): <NEW_LINE> <INDENT> self.instance.extend_body(body) | Called when part of the body has been received.
:param bytes body: The body bytes. | 625941b785dfad0860c3ac8d |
def plotResult(X=[],Y=[]): <NEW_LINE> <INDENT> fig = plt.figure(figsize=(12, 14)) <NEW_LINE> ax = plt.subplot(2, 1, 2) <NEW_LINE> trans_offset = mtrans.offset_copy(ax.transData, fig=fig, x=0.03, y=0.15, units='inches') <NEW_LINE> plt.plot(stick_length_input,processing_time,'ro-') <NEW_LINE> plt.title('No of Combination... | This method will plot the result of two array
X dimension and Y dimension | 625941b74f6381625f11487b |
def __init__(self, name=None, experiment='xenonnt', detector=None, voltages=None, created_by=None, comments=None, date=None, id=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_var... | Xenon1tVoltageMap - a model defined in OpenAPI | 625941b7aad79263cf39086f |
def verify_password(self, password): <NEW_LINE> <INDENT> return check_password_hash(self.password_hash, password) | :summary: 验证密码
:param password:
:return: | 625941b756b00c62f0f14492 |
def _qrs_ext_tconst(ventricular): <NEW_LINE> <INDENT> def tconst(pattern, qrs): <NEW_LINE> <INDENT> BASIC_TCONST(pattern, qrs) <NEW_LINE> tnet = pattern.last_tnet <NEW_LINE> tnet.set_before(qrs.end, pattern.hypothesis.end) <NEW_LINE> if ventricular: <NEW_LINE> <INDENT> tnet.add_constraint(qrs.start, qrs.end, C.VQRS_DUR... | Returns the temporal constraints function of the extrasystole beat,
requiring an anticipated beat. It accepts a parameter to determine if the
anticipated beat must be ventricular. | 625941b785dfad0860c3ac8e |
def random_value(self) -> AnyStr: <NEW_LINE> <INDENT> length = self._max_length if self._max_length is not None else len(self._default) <NEW_LINE> random_string = rand_string(length) <NEW_LINE> return random_string if self._decode else random_string.encode() | Returns a random string or bytes. The length of the string is either the max length if given or the length
of the default attribute. | 625941b731939e2706e4cca5 |
def make_windows(length, window, slide): <NEW_LINE> <INDENT> if slide == 0: <NEW_LINE> <INDENT> windows = xrange(0, length, window) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> windows = xrange(0, length, slide) <NEW_LINE> <DEDENT> for start in windows: <NEW_LINE> <INDENT> yield (start, min(start + window, length)) <N... | For a given length, return an iterator for intervals of length `window` with
a slide of `slide`.
>>> list(make_windows(8, 4, 0))
[(0, 4), (4, 8)]
>>> list(make_windows(8, 5, 0))
[(0, 5), (5, 8)]
>>> list(make_windows(8, 8, 0))
[(0, 8)]
>>> list(make_windows(8, 4, 2))
[(0, 4), (2, 6), (4, 8)]
>>> list(make_windows(8, 5... | 625941b7cc40096d61595788 |
def setNTaxa(self, n): <NEW_LINE> <INDENT> SplitBase.setNTaxa(self, n) | Sets the number of taxa currently supported by this Split object to n.
Note that this function clears the object (erases all information
previously stored in it), even if n equals the number of taxa
currently supported by the split.
>>> from phycas.Phylogeny import *
>>> s = Split()
>>> s.createFromPattern('-***xx*-xx... | 625941b732920d7e50b28001 |
def breadthFirstSearch(problem): <NEW_LINE> <INDENT> start_state = problem.getStartState() <NEW_LINE> queue = util.Queue() <NEW_LINE> root = Node(start_state, None, 0, None) <NEW_LINE> queue.push(root) <NEW_LINE> visited = [] <NEW_LINE> while not queue.isEmpty(): <NEW_LINE> <INDENT> node = queue.pop() <NEW_LINE> if nod... | Search the shallowest nodes in the search tree first. | 625941b756ac1b37e6264015 |
def isWin(self): <NEW_LINE> <INDENT> return self.pos in self.data['win_states'] | test if the current node is a win-state | 625941b799fddb7c1c9de1c8 |
def get_model_config(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> model_config = {} <NEW_LINE> model_config['model_name'] = model_name <NEW_LINE> model_config = json.dumps(model_config) <NEW_LINE> with open('config.json', 'w') as file: <NEW_LINE> <INDENT> file.write(model_config) <NEW_LINE> <DEDENT> <DEDENT> except ... | Write the current model config
| 625941b7ab23a570cc24ffb5 |
def write_change(result: pd.DataFrame) -> None: <NEW_LINE> <INDENT> for key in ['score', 'rank']: <NEW_LINE> <INDENT> if key not in result.columns: <NEW_LINE> <INDENT> raise KeyError(f'Incomplete result dataframe: {key} not found') <NEW_LINE> <DEDENT> <DEDENT> with transaction.atomic(): <NEW_LINE> <INDENT> result.sort_... | write changes to ResumeResult ORM
use transaction to secure atomic | 625941b7d164cc6175782b83 |
def student_view(self, context): <NEW_LINE> <INDENT> user_id = self._get_current_user_id() <NEW_LINE> room_id = self.user_id_to_room_id.get(user_id, '') <NEW_LINE> frag = Fragment(self._jinja_env.get_template( self.STUDENT_TEMPLATE_PATH).render({'room_id': room_id})) <NEW_LINE> frag.add_css(self._get_resource_string( '... | Provide the default student view. | 625941b7377c676e91271fe0 |
def delete(self, request, *args, **kwargs): <NEW_LINE> <INDENT> self.object = self.get_object() <NEW_LINE> success_url = self.get_success_url() <NEW_LINE> self.object.is_active = False <NEW_LINE> self.object.save() <NEW_LINE> return HttpResponseRedirect(success_url) | Soft Delete.
Set is_active to False of the fetched object and then redirect to the
success URL. | 625941b7009cb60464c631f2 |
def __call__(self, pwSeed): <NEW_LINE> <INDENT> return self.getPassword(pwSeed) | Create a new password as a 'call' | 625941b77c178a314d6ef28d |
def message_ports_out(self): <NEW_LINE> <INDENT> return _foo_swig.packet_pad_sptr_message_ports_out(self) | message_ports_out(self) -> pmt_t | 625941b794891a1f4081b8dd |
def softmax_loss_naive(W, X, y, reg): <NEW_LINE> <INDENT> loss = 0.0 <NEW_LINE> dW = np.zeros_like(W) <NEW_LINE> num_train = X.shape[0] <NEW_LINE> num_class = W.shape[1] <NEW_LINE> for i in range(num_train): <NEW_LINE> <INDENT> scores = np.dot(X[i,:],W) <NEW_LINE> shift_scores = scores - max(scores) <NEW_LINE> correct_... | Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a minibatch of data.
- y: A numpy array of shape (N,) contain... | 625941b715baa723493c3da7 |
def _do_export(self, common, volume): <NEW_LINE> <INDENT> model_update = {} <NEW_LINE> if not self.configuration.hp3par_iscsi_chap_enabled: <NEW_LINE> <INDENT> model_update['provider_auth'] = None <NEW_LINE> return model_update <NEW_LINE> <DEDENT> chap_username = volume['host'].split('@')[0] <NEW_LINE> chap_password = ... | Gets the associated account, generates CHAP info and updates. | 625941b7adb09d7d5db6c5c9 |
def test_admin_can_add_meal(self): <NEW_LINE> <INDENT> res = self.client.post( '/api/v2/admin/menu', data=json.dumps( self.data["menu"]), headers=self.auth_header, content_type='application/json') <NEW_LINE> self.assertEqual(res.status_code, 201) <NEW_LINE> self.assertTrue(b'New meal added!', res.data) | This tests whether an admin user can add a meal option to the menu | 625941b7004d5f362079a16c |
def exchangeClicked(self): <NEW_LINE> <INDENT> if type(self.game.current_player) is Player: <NEW_LINE> <INDENT> self.game.current_player.exchange_letters() | Function that gets called when 'Exchange' is clicked | 625941b78da39b475bd64dac |
def get_team_years_participated(self, team_key, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_'): <NEW_LINE> <INDENT> return self.get_team_years_participated_with_http_info(team_key, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.get_team_y... | get_team_years_participated # noqa: E501
Gets a list of years in which the team participated in at least one competition. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
async_hronous HTTP request, please pass async_=True
>>> thread = api.get_team_years_participated(team_key, async_=... | 625941b78e71fb1e9831d5e3 |
def __init__(__self__, *, ssm_controls: Optional['outputs.RemediationConfigurationExecutionControlsSsmControls'] = None): <NEW_LINE> <INDENT> if ssm_controls is not None: <NEW_LINE> <INDENT> pulumi.set(__self__, "ssm_controls", ssm_controls) | :param 'RemediationConfigurationExecutionControlsSsmControlsArgs' ssm_controls: Configuration block for SSM controls. See below. | 625941b730c21e258bdfa2d2 |
@cli.command(name='imposm-import') <NEW_LINE> @click.pass_context <NEW_LINE> def imposm_import(ctx): <NEW_LINE> <INDENT> tasks.imposm_import(ctx.obj['CONFIG'].db_config(), ctx.obj['CONFIG']) | Import OSM data into import schema (see imposm-deploy). | 625941b7d99f1b3c44c673cd |
def __init__( self, reddit: "Reddit", subreddit: "Subreddit", name: str, revision: Optional[str] = None, _data: Optional[Dict[str, Any]] = None, ): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self._revision = revision <NEW_LINE> self.subreddit = subreddit <NEW_LINE> super().__init__(reddit, _data=_data, _str_field=... | Construct an instance of the WikiPage object.
:param revision: A specific revision ID to fetch. By default, fetches the most
recent revision. | 625941b799fddb7c1c9de1c9 |
def main(): <NEW_LINE> <INDENT> pygame.init() <NEW_LINE> window_surface = pygame.display.set_mode((MAX_X, MAX_Y), 0, 32) <NEW_LINE> pygame.display.set_caption('asteroids') <NEW_LINE> high_score = get_high_score() <NEW_LINE> info_screen(window_surface, 'ASTEROIDS', 'press return key to start') <NEW_LINE> while True: <NE... | The entry point for the entire game. | 625941b74428ac0f6e5ba627 |
def visit_functiondef(self, node): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if node.parent.name.endswith("Client") and node.is_method() and node.parent.name not in self.ignore_clients: <NEW_LINE> <INDENT> if len(node.args.args) > 6: <NEW_LINE> <INDENT> positional_args = len(node.args.args) - len(node.args.defaults)... | Visits every method in the client and checks that it doesn't have more than 5
positional arguments.
:param node: function node
:type node: ast.FunctionDef
:return: None | 625941b72eb69b55b151c6e0 |
def add_to_cart(self, price): <NEW_LINE> <INDENT> start_time = self.session_model.objects.filter( skate_date=self.object.skate_date.skate_date).values_list('start_time', flat=True) <NEW_LINE> cart = self.cart_model(customer=self.request.user, item='Womens Hockey', skater_name=self.object.skater, event_date=self.object.... | Adds Womens Hockey session to shopping cart. | 625941b723849d37ff7b2ec7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.