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_LINE> <DEDENT> context['opts'] = opts <NEW_LINE> parent = None <NEW_LINE> if parent_id: <NEW_LINE> <INDENT> parent = get_object_or_404(comments.get_model(), pk=parent_id) <NEW_LINE> <DEDENT> ip_address = request.META.get('REMOTE_ADDR', None) <NEW_LINE> try: <NEW_LINE> <INDENT> ip_ban = BannedIP.objects.get(ip_address=ip_address) <NEW_LINE> <DEDENT> except BannedIP.DoesNotExist: <NEW_LINE> <INDENT> ip_ban = None <NEW_LINE> <DEDENT> if request.method != 'POST' or ip_ban: <NEW_LINE> <INDENT> initial = {} <NEW_LINE> if parent: <NEW_LINE> <INDENT> if parent.title.startswith('Re:'): <NEW_LINE> <INDENT> initial['title'] = parent.title <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> initial['title'] = u'Re: %s' % parent.title <NEW_LINE> <DEDENT> <DEDENT> form = comments.get_form()(context['object'], parent=parent_id, initial=initial) <NEW_LINE> context.update({ 'parent': parent, 'form': form, 'ip_ban': ip_ban, }) <NEW_LINE> return render_to_response( get_templates_from_placement('comment_form.html', context['placement']), context, RequestContext(request) ) <NEW_LINE> <DEDENT> data = request.POST.copy() <NEW_LINE> if request.user.is_authenticated(): <NEW_LINE> <INDENT> if not data.get('name', ''): <NEW_LINE> <INDENT> data["name"] = request.user.get_full_name() or request.user.username <NEW_LINE> <DEDENT> if not data.get('email', ''): <NEW_LINE> <INDENT> data["email"] = request.user.email <NEW_LINE> <DEDENT> <DEDENT> form = comments.get_form()(context['object'], data=data, parent=parent_id) <NEW_LINE> if form.security_errors(): <NEW_LINE> <INDENT> return CommentPostBadRequest( "The comment form failed security verification: %s" % escape(str(form.security_errors()))) <NEW_LINE> <DEDENT> preview = "preview" in data <NEW_LINE> next = data.get("next", "%s%s/" % (context['placement'].get_absolute_url(), slugify(_('comments')))) <NEW_LINE> if form.errors or preview: <NEW_LINE> <INDENT> context.update({ "form" : form, 'parent': parent, "next": next, }) <NEW_LINE> return render_to_response( get_templates_from_placement(form.errors and 'comment_form.html' or 'comment_preview.html', context['placement']), context, RequestContext(request) ) <NEW_LINE> <DEDENT> comment = form.get_comment_object() <NEW_LINE> comment.ip_address = request.META.get("REMOTE_ADDR", None) <NEW_LINE> if request.user.is_authenticated(): <NEW_LINE> <INDENT> comment.user = request.user <NEW_LINE> <DEDENT> responses = signals.comment_will_be_posted.send( sender = comment.__class__, comment = comment, request = request ) <NEW_LINE> for (receiver, response) in responses: <NEW_LINE> <INDENT> if response == False: <NEW_LINE> <INDENT> return CommentPostBadRequest( "comment_will_be_posted receiver %r killed the comment" % receiver.__name__) <NEW_LINE> <DEDENT> <DEDENT> if opts.premoderated: <NEW_LINE> <INDENT> comment.is_public = False <NEW_LINE> <DEDENT> comment.save() <NEW_LINE> signals.comment_was_posted.send( sender = comment.__class__, comment = comment, request = request ) <NEW_LINE> return HttpResponseRedirect(next) | 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 + width, ypos + height)])) <NEW_LINE> patches.append(mpatch.Polygon([(xpos, ypos + height), (xpos - off, ypos + height + off), (xpos - off, ypos + off), (xpos, ypos)])) <NEW_LINE> <DEDENT> patches.append(mpatch.Rectangle((xpos, ypos), width, height)) <NEW_LINE> return ax.add_collection(mcoll.PatchCollection(patches, **kwargs)) | 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 zip(normal, wide)) <NEW_LINE> vaped = vape_me.translate(widemap) <NEW_LINE> return vaped | 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, check=False) for x in gens] <NEW_LINE> if gens[1] in L.ideal(gens[0]): <NEW_LINE> <INDENT> gens = gens[:1] <NEW_LINE> <DEDENT> elif gens[0] in L.ideal(gens[1]): <NEW_LINE> <INDENT> gens = gens[1:] <NEW_LINE> <DEDENT> self.__reduced_generators = tuple(gens) <NEW_LINE> return self.__reduced_generators | 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*b + 1,)
TESTS:
Number fields defined by non-monic and non-integral
polynomials are supported (:trac:`252`)::
sage: K.<a> = NumberField(2*x^2 - 1/3)
sage: L.<b> = K.extension(5*x^2 + 1)
sage: P = L.primes_above(2)[0]
sage: P.gens_reduced()
(2, 15*a*b + 3*a + 1) | 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_LINE> <INDENT> raise TypeError("Second-order gradient for while loops not supported.") <NEW_LINE> <DEDENT> if isinstance(grad, ops.Tensor): <NEW_LINE> <INDENT> grad_ctxt.AddName(grad.name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not isinstance(grad, (ops.IndexedSlices, ops.SparseTensor)): <NEW_LINE> <INDENT> raise TypeError("Type %s not supported" % type(grad)) <NEW_LINE> <DEDENT> grad_ctxt.AddName(grad.values.name) <NEW_LINE> grad_ctxt.AddName(grad.indices.name) <NEW_LINE> if isinstance(grad, ops.IndexedSlices): <NEW_LINE> <INDENT> dense_shape = grad.dense_shape <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dense_shape = grad.shape <NEW_LINE> <DEDENT> if dense_shape is not None: <NEW_LINE> <INDENT> grad_ctxt.AddName(dense_shape.name) <NEW_LINE> <DEDENT> <DEDENT> enter_fn = control_flow_ops._Enter <NEW_LINE> grad_ctxt.Enter() <NEW_LINE> result = enter_fn(grad, grad_ctxt.name, is_constant=False, parallel_iterations=grad_ctxt.parallel_iterations, name="b_exit") <NEW_LINE> grad_ctxt.Exit() <NEW_LINE> return result | 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 FROM {}'.format(self.table)) <NEW_LINE> s3_path = 's3://{}/{}'.format(self.s3_bucket, self.s3_key) <NEW_LINE> if self.use_partitioned: <NEW_LINE> <INDENT> rendered_partition = self.partition_template.format(**context) <NEW_LINE> s3_path = '{}/{}'.format(s3_path, rendered_partition) <NEW_LINE> <DEDENT> if self.json_paths: <NEW_LINE> <INDENT> json_paths = f's3://{self.s3_bucket}/{self.json_paths}' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> json_paths = 'auto' <NEW_LINE> <DEDENT> self.log.info('Coping data from {} to {} on table Redshift'.format(s3_path, self.table)) <NEW_LINE> formatted_sql = StageToRedshiftOperator.copy_sql.format( self.table, s3_path, credentials.access_key, credentials.secret_key, json_paths ) <NEW_LINE> redshift.run(formatted_sql) <NEW_LINE> self.log.info('Successfully Copied data from {} to {} table on Redshift'.format(s3_path, self.table)) | 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', help='train a non-bayesian net using maximum likelihood') <NEW_LINE> group.add_argument('--svi', action='store_true', help='train a bayesian net using stochastic variational inference') <NEW_LINE> group.add_argument('--hmc', action='store_true', help='train a bayesian net using hamiltonian monte carlo') <NEW_LINE> return parser.parse_args() | 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[0].stats.sac.evdp == 0: <NEW_LINE> <INDENT> err_out = open('/Users/ja17375/DiscrePy/Sheba/Events_with_evdp_of_0.txt','w+') <NEW_LINE> err_out.write('Station: {}, has event starting at {} with an evdp of 0!\n'.format(self.station,self.BHN[0].stats.starttime)) <NEW_LINE> traveltime = model.get_travel_times(10,self.BHN[0].stats.sac.gcarc,[phase])[0].time <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> traveltime = model.get_travel_times((self.BHN[0].stats.sac.evdp),self.BHN[0].stats.sac.gcarc,[phase])[0].time <NEW_LINE> <DEDENT> return traveltime | 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_LINE> with open(path_file, 'w') as report_file: <NEW_LINE> <INDENT> report_file.write(report) | 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> <INDENT> value = xml2dict(element) <NEW_LINE> <DEDENT> result[key] = value <NEW_LINE> <DEDENT> return result | 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 <NEW_LINE> <DEDENT> if 'No Reported Evidence' in clinSig: <NEW_LINE> <INDENT> return 5 <NEW_LINE> <DEDENT> if 'Disputed' in clinSig: <NEW_LINE> <INDENT> return 6 <NEW_LINE> <DEDENT> if 'Refuted' in clinSig: <NEW_LINE> <INDENT> return 7 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 8 | 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: <NEW_LINE> <INDENT> tree.message_of_the_day = message_of_the_day <NEW_LINE> <DEDENT> if status or reason: <NEW_LINE> <INDENT> if status is None: <NEW_LINE> <INDENT> status = 'no change' <NEW_LINE> <DEDENT> if reason is None: <NEW_LINE> <INDENT> reason = 'no change' <NEW_LINE> <DEDENT> l = model.DbLog( tree=tree.tree, when=relengapi_time.now(), who=str(current_user), status=status, reason=reason, tags=tags) <NEW_LINE> session.add(l) <NEW_LINE> <DEDENT> tree_cache_invalidate(tree.tree) | 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(packet) != length: <NEW_LINE> <INDENT> raise PacketError('Packet has invalid length') <NEW_LINE> <DEDENT> if length > 8192: <NEW_LINE> <INDENT> raise PacketError('Packet length is too long (%d)' % length) <NEW_LINE> <DEDENT> self.clear() <NEW_LINE> packet = packet[20:] <NEW_LINE> while packet: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> (key, attrlen) = struct.unpack('!BB', packet[0:2]) <NEW_LINE> <DEDENT> except struct.error: <NEW_LINE> <INDENT> raise PacketError('Attribute header is corrupt') <NEW_LINE> <DEDENT> if attrlen < 2: <NEW_LINE> <INDENT> raise PacketError( 'Attribute length is too small (%d)' % attrlen) <NEW_LINE> <DEDENT> value = packet[2:attrlen] <NEW_LINE> attribute = self.dict.attributes.get(self._DecodeKey(key)) <NEW_LINE> if key == 26: <NEW_LINE> <INDENT> for (key, value) in self._PktDecodeVendorAttribute(value): <NEW_LINE> <INDENT> self.setdefault(key, []).append(value) <NEW_LINE> <DEDENT> <DEDENT> elif key == 80: <NEW_LINE> <INDENT> self.message_authenticator = True <NEW_LINE> self.setdefault(key, []).append(value) <NEW_LINE> <DEDENT> elif attribute and attribute.type == 'tlv': <NEW_LINE> <INDENT> self._PktDecodeTlvAttribute(key,value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.setdefault(key, []).append(value) <NEW_LINE> <DEDENT> packet = packet[attrlen:] | 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> params = locals() <NEW_LINE> for key, val in six.iteritems(params['kwargs']): <NEW_LINE> <INDENT> if key not in all_params: <NEW_LINE> <INDENT> raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_traceflow" % key ) <NEW_LINE> <DEDENT> params[key] = val <NEW_LINE> <DEDENT> del params['kwargs'] <NEW_LINE> if ('traceflow_id' not in params or params['traceflow_id'] is None): <NEW_LINE> <INDENT> raise ValueError("Missing the required parameter `traceflow_id` when calling `get_traceflow`") <NEW_LINE> <DEDENT> collection_formats = {} <NEW_LINE> path_params = {} <NEW_LINE> if 'traceflow_id' in params: <NEW_LINE> <INDENT> path_params['traceflow-id'] = params['traceflow_id'] <NEW_LINE> <DEDENT> query_params = [] <NEW_LINE> header_params = {} <NEW_LINE> form_params = [] <NEW_LINE> local_var_files = {} <NEW_LINE> body_params = None <NEW_LINE> header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) <NEW_LINE> auth_settings = ['BasicAuth'] <NEW_LINE> return self.api_client.call_api( '/traceflows/{traceflow-id}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='Traceflow', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) | 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=True)
>>> result = thread.get()
:param async_req bool
:param str traceflow_id: (required)
:return: Traceflow
If the method is called asynchronously,
returns the request thread. | 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.X_train[j]) ** 2).sum()) <NEW_LINE> <DEDENT> <DEDENT> return dists | 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 the Euclidean distance between the ith test point and the jth training
point. | 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 " + str(message), DEBUG_INFO) <NEW_LINE> x = int(constrain(x, 0, 121)) <NEW_LINE> y = int(constrain(y, 0, 7)) <NEW_LINE> args = [x, y, message] <NEW_LINE> sendSerial(COMMAND_CODES["LCD_DRAW_STRING"], args) <NEW_LINE> if update: <NEW_LINE> <INDENT> LCDupdate() | 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 (default) if you want Sparki to update the display
returns:
nothing | 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.delete() <NEW_LINE> messages.add_message( request, messages.SUCCESS, 'Galley deleted.', ) <NEW_LINE> return redirect( reverse( 'typesetting_article', kwargs = {'article_id': article.pk}, ) ) | 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 = Bus(1, 0) <NEW_LINE> regwr = Bus(1, 0) <NEW_LINE> exts = Bus(2, 0) <NEW_LINE> alusrcb = Bus(1, 0) <NEW_LINE> alus = Bus(4, 0) <NEW_LINE> aluflagwr = Bus(1, 0) <NEW_LINE> shop = Bus(2, 0) <NEW_LINE> shctrl = Bus(2, 0) <NEW_LINE> accen = Bus(1, 0) <NEW_LINE> memwr = Bus(1, 0) <NEW_LINE> memty = Bus(2, 0) <NEW_LINE> regsrc = Bus(1, 0) <NEW_LINE> pcsrc = Bus(2, 0) <NEW_LINE> scc = ControllerSingleCycle(instruction,c,v,n,z,pcsrc,pcwr,regsa, regdst,regsb,regwrs,regwr,exts,alusrcb, alus,shop,shctrl,accen,aluflagwr,memty, memwr,regsrc,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: <NEW_LINE> <INDENT> self.dateCounter = 0 | 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 <NEW_LINE> <DEDENT> if json_schema.INTEGER in json_schema.get_type(simple_json_schema): <NEW_LINE> <INDENT> mapping = self._get_mapping(remote_schema, path, {'type': json_schema.NUMBER}) <NEW_LINE> if not mapping is None: <NEW_LINE> <INDENT> return mapping <NEW_LINE> <DEDENT> <DEDENT> raise Exception("A compatible column for path {} and JSONSchema {} in table {} cannot be found.".format( path, simple_json_schema, remote_schema['path'] )) | 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 mode. (Basically, all of the methods that
are sensible for a read-only file.) | 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, lambda x: x + 2, inverse=True)
sage: D # indirect doctest
An invertible discrete dynamical system with unspecified ground set | 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["server"] <NEW_LINE> <DEDENT> username = input("Yhat username" + _username + ": ") <NEW_LINE> apikey = input("Yhat apikey" + _apikey + ": ") <NEW_LINE> server = input("Yhat server" + _server + ": ") <NEW_LINE> if username == "": <NEW_LINE> <INDENT> username = re.search(r"[^[]*\[([^]]*)\]", _username).group(1) <NEW_LINE> <DEDENT> if apikey == "": <NEW_LINE> <INDENT> apikey = re.search(r"[^[]*\[([^]]*)\]", _apikey).group(1) <NEW_LINE> <DEDENT> if server == "": <NEW_LINE> <INDENT> server = re.search(r"[^[]*\[([^]]*)\]", _server).group(1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not "http://" in server and not "https://" in server: <NEW_LINE> <INDENT> server = "http://" + server <NEW_LINE> <DEDENT> o = urlparse(server) <NEW_LINE> server = "%s://%s" % (o.scheme, o.netloc) <NEW_LINE> <DEDENT> yhat_dir = os.path.join(os.environ['HOME'], '.yhat') <NEW_LINE> if not os.path.exists(yhat_dir): <NEW_LINE> <INDENT> os.makedirs(yhat_dir) <NEW_LINE> <DEDENT> with open(os.path.join(yhat_dir, '.config'), 'w') as f: <NEW_LINE> <INDENT> data = json.dumps({"username": username, "apikey": apikey, "server": server}) <NEW_LINE> data = base64.encodestring(data) <NEW_LINE> f.write(data) | 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) <NEW_LINE> out_no_exog = evaluate(forecaster, cv, y, X=None, scoring=scoring) <NEW_LINE> scoring_name = f"test_{scoring.name}" <NEW_LINE> assert np.all(out_exog[scoring_name] != out_no_exog[scoring_name]) | 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 errorString: basestring | 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_header_value <NEW_LINE> <DEDENT> hsts_policy = self.app.config.get('hsts_policy', constants.DEFAULT_HSTS_POLICY) <NEW_LINE> if self.request.scheme.lower() == 'https' and hsts_policy: <NEW_LINE> <INDENT> include_subdomains = bool(hsts_policy.get('includeSubdomains', False)) <NEW_LINE> subdomain_string = '; includeSubdomains' if include_subdomains else '' <NEW_LINE> hsts_value = 'max-age=%d%s' % (int(hsts_policy.get('max_age')), subdomain_string) <NEW_LINE> self.response.headers['Strict-Transport-Security'] = hsts_value <NEW_LINE> <DEDENT> self.response.headers['X-XSS-Protection'] = '1; mode=block' <NEW_LINE> self.response.headers['X-Content-Type-Options'] = 'nosniff' <NEW_LINE> csp_policy = self.app.config.get('csp_policy', constants.DEFAULT_CSP_POLICY) <NEW_LINE> report_only = False <NEW_LINE> if 'reportOnly' in csp_policy: <NEW_LINE> <INDENT> report_only = csp_policy.get('reportOnly') <NEW_LINE> del csp_policy['reportOnly'] <NEW_LINE> <DEDENT> header_name = ('Content-Security-Policy%s' % ('-Report-Only' if report_only else '')) <NEW_LINE> policies = [] <NEW_LINE> for (k, v) in csp_policy.iteritems(): <NEW_LINE> <INDENT> policies.append('%s %s' % (k, v)) <NEW_LINE> <DEDENT> self.response.headers.add(header_name, '; '.join(policies)) | 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 state dict the same as the dygraph mode. | 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> <INDENT> print('beta: ', beta) <NEW_LINE> <DEDENT> prefac = ( phys.c*(3/8)*phys.thomson_xsec/4 * ( 8*np.pi*T**2 /(phys.ele_compton*phys.me)**3 ) ) <NEW_LINE> diff_term = diff_expansion(beta, photeng, T, as_pairs=as_pairs) <NEW_LINE> term = np.transpose(prefac*np.transpose(diff_term[0])) <NEW_LINE> err = np.transpose(prefac*np.transpose(diff_term[1])) <NEW_LINE> print('... Complete! *****') <NEW_LINE> return term, err | 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.size == photeng.size values. Otherwise, gets the spectrum at each photeng for each eleckineng, returning an array of length eleckineng.size*photeng.size.
Returns
-------
tuple of ndarrays
dN/(dt dE) of the outgoing photons (dt = 1 s) and the error, with abscissa given by (eleckineng, photeng).
Notes
-----
Insert note on the suitability of the method. | 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_interactions_for_fingerprint") <NEW_LINE> return jsonify({"status": "error", "msg": "get_interactions failed"}), 500 <NEW_LINE> <DEDENT> return jsonify(interactions) | 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: firme_msoffice", 'data': repr(locals()), 'location': __file__}) <NEW_LINE> request = self._construya_solicitud( identidad, documento, algoritmo_hash, hash_doc, resumen, id_funcionalidad) <NEW_LINE> try: <NEW_LINE> <INDENT> dev = self._firme_msoffice(request) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.error({'message': "Firmador: firmando en msoffice", 'data': e, 'location': __file__}) <NEW_LINE> dev = self.DEFAULT_ERROR <NEW_LINE> <DEDENT> logger.debug({'message': "Firmador: firme_msoffice result", 'data': dev, 'location': __file__}) <NEW_LINE> return dev | 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._environment = create_environment_fn(game_name) <NEW_LINE> self.num_actions = self._environment.action_space.n <NEW_LINE> self.epsilon_eval = epsilon_eval <NEW_LINE> self.action_vals = np.zeros((self.num_actions,), dtype='f8') <NEW_LINE> self.no_op = no_op <NEW_LINE> self.best_sampling = best_sampling <NEW_LINE> self._representation_checkpoint = representation_checkpoint <NEW_LINE> if self._representation_checkpoint: <NEW_LINE> <INDENT> self._control_graph = tf.Graph() <NEW_LINE> with self._control_graph.as_default(): <NEW_LINE> <INDENT> self._control_sess = tf.Session( 'local', config=tf.ConfigProto(allow_soft_placement=True)) <NEW_LINE> self._control_agent = create_agent(self._control_sess, self._environment, self.random_state) <NEW_LINE> self._control_sess.run(tf.global_variables_initializer()) <NEW_LINE> <DEDENT> <DEDENT> self._initialize_checkpointer_and_maybe_resume(checkpoint_file_prefix) <NEW_LINE> self._save_init_state() | 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 checkpoint, if available, and initialize the
Checkpointer object.
Args:
random_state: np.random.RandomState, for maintaining the random seed.
no_op: bool, whether to apply no-ops in beginning of episodes.
best_sampling: bool, whether to sample episodes from the best node, to
train all nodes.
representation_checkpoint: string, full path to the checkpoint to load for
the network weights, where all but last layer will be frozen.
create_environment_fn: function, receives a game name and creates an Atari
2600 Gym environment.
game_name: str, name of the Atari game to run (required).
game_version: str, version of the game to run.
sticky_actions: bool, whether to use sticky actions.
epsilon_eval: float, the epsilon exploration probability used to evaluate
policies.
checkpoint_file_prefix: str, the prefix to use for checkpoint files. | 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, True) <NEW_LINE> self.assert_particle_published(driver, self.METBK_SAMPLE_DATA1, self.assert_data_particle_sample, True) <NEW_LINE> self.assert_particle_not_published(driver, self.METBK_SAMPLE_DATA1, self.assert_data_particle_sample, True) <NEW_LINE> self.assert_particle_published(driver, self.METBK_SAMPLE_DATA2, self.assert_data_particle_sample, False) | 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_finished <NEW_LINE> <DEDENT> <DEDENT> return last_finished | 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"{datadir}/games"): <NEW_LINE> <INDENT> os.mkdir(f"{datadir}/games") <NEW_LINE> <DEDENT> rawdir = f"{datadir}/raw/" <NEW_LINE> if not os.path.exists(rawdir): <NEW_LINE> <INDENT> os.mkdir(rawdir) <NEW_LINE> <DEDENT> for s in seasons: <NEW_LINE> <INDENT> print(f"Downloading season {s}...") <NEW_LINE> if ( (liga == 3) or ((liga == 1) and (s == 1991)) or ((liga == 2) and (s <= 1993)) ): <NEW_LINE> <INDENT> n_matchdays = 38 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> n_matchdays = 34 <NEW_LINE> <DEDENT> for sp in range(1, n_matchdays + 1): <NEW_LINE> <INDENT> request = MyBrowser.Request(mkURL(s, sp, liga)) <NEW_LINE> rawfile = f"{rawdir}kicker_{s}_{sp}.html" <NEW_LINE> if not os.path.exists(rawfile): <NEW_LINE> <INDENT> dl_and_save(rawfile, request) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> print("Finished Downloading Match Results") <NEW_LINE> get_game_results(seasons, rawdir, path, liga, resultsonly) | 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, attendance, referee) | 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.DISABLED, disabledfill='#EEE', fill='#EEE') <NEW_LINE> ids.append(id) <NEW_LINE> box = canvas.bbox(id) <NEW_LINE> offset = box[2] - box[0] <NEW_LINE> if offset > largest: <NEW_LINE> <INDENT> largest = offset <NEW_LINE> <DEDENT> if lineoffset < box[3] - box[1]: <NEW_LINE> <INDENT> lineoffset = box[3] - box[1] <NEW_LINE> <DEDENT> n = n + 1 <NEW_LINE> <DEDENT> lineoffset = lineoffset + 10 <NEW_LINE> column = 0 <NEW_LINE> n = 0 <NEW_LINE> low = 0 <NEW_LINE> self.unitbuttons = dict() <NEW_LINE> for p in texts: <NEW_LINE> <INDENT> id = ids[n] <NEW_LINE> box = canvas.bbox(id) <NEW_LINE> x = 10 + column * (largest + 10) <NEW_LINE> y = 10 <NEW_LINE> canvas.move(id, x - box[0], y - box[1]) <NEW_LINE> box = canvas.bbox(id) <NEW_LINE> boxid = canvas.create_rectangle(box[0] - 4, box[1] - 4, box[0] + largest + 4, box[1] + lineoffset - 6, activefill='#444', activeoutline='#444', fill='#222', outline='#222', state=Tix.NORMAL) <NEW_LINE> def handler(event, self=self, button=boxid, canvas=canvas): <NEW_LINE> <INDENT> self.__unitbuttonselected(event, button, canvas) <NEW_LINE> <DEDENT> tag = 'unitbtn_' + str(boxid) <NEW_LINE> canvas.addtag_withtag(tag, boxid) <NEW_LINE> canvas.tag_bind(tag, sequence='<ButtonRelease-1>', func=handler) <NEW_LINE> canvas.tag_lower(boxid, id) <NEW_LINE> self.unitbuttons[boxid] = [p, id, boxid, n] <NEW_LINE> if box[1] + lineoffset - 5 > low: <NEW_LINE> <INDENT> low = box[1] + lineoffset - 5 <NEW_LINE> <DEDENT> n = n + 1 <NEW_LINE> column = column + 1 <NEW_LINE> <DEDENT> return low | 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.variables.append(variables) <NEW_LINE> if optimizer: <NEW_LINE> <INDENT> self.optimizers.append(optimizer) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not self.default_optimizer: <NEW_LINE> <INDENT> raise ValueError( 'default_optimizer is None', 'default_optimzier can not be None if optimizer is not passed to add_variables') <NEW_LINE> <DEDENT> self.optimizers.append( self.default_optimizer(learning_rate, **other_params)) <NEW_LINE> <DEDENT> return self | 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, value to pass the the default optimizer | 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> return name[:pos] <NEW_LINE> <DEDENT> <DEDENT> return name | 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(region_filename) | 裁剪图片,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 == 'osrm': <NEW_LINE> <INDENT> distances = osrm_distance_matrix(A, chunksize=args.osrm_max_table_size, osrm_base_url=args.osrm_base_url) <NEW_LINE> <DEDENT> (nx, ny) = distances.shape <NEW_LINE> self.matrix = {} <NEW_LINE> for from_node in range(nx): <NEW_LINE> <INDENT> self.matrix[from_node] = {} <NEW_LINE> for to_node in range(ny): <NEW_LINE> <INDENT> if from_node == to_node: <NEW_LINE> <INDENT> self.matrix[from_node][to_node] = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.matrix[from_node][to_node] = distances[from_node, to_node] | 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=passphrase) <NEW_LINE> params['peerkey'] = "1" <NEW_LINE> params['rsn_pairwise'] = "TKIP CCMP" <NEW_LINE> hostapd.add_ap(apdev[0], params) <NEW_LINE> dev[0].connect(ssid, psk=passphrase, scan_freq="2412", peerkey=True, pairwise="CCMP") <NEW_LINE> dev[1].connect(ssid, psk=passphrase, scan_freq="2412", peerkey=True, pairwise="TKIP") <NEW_LINE> hwsim_utils.test_connectivity_sta(dev[0], dev[1]) <NEW_LINE> dev[0].request("STKSTART " + dev[1].p2p_interface_addr()) <NEW_LINE> time.sleep(0.5) <NEW_LINE> dev[1].request("STKSTART " + dev[0].p2p_interface_addr()) <NEW_LINE> time.sleep(0.5) | 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_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> g.addChain( v ) <NEW_LINE> <DEDENT> <DEDENT> elif k == 'params': <NEW_LINE> <INDENT> for vv in v: <NEW_LINE> <INDENT> if len(vv) == 1: <NEW_LINE> <INDENT> g.addVariable( vv[0] ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> g.addVariable( vv ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif k == 'rgroup': <NEW_LINE> <INDENT> for vv in v: <NEW_LINE> <INDENT> g.addRate( vv, is_const = False ) <NEW_LINE> <DEDENT> <DEDENT> elif k == 'const_rgroup': <NEW_LINE> <INDENT> for vv in v: <NEW_LINE> <INDENT> g.addRate( vv, is_const = True ) <NEW_LINE> <DEDENT> <DEDENT> elif k == 'pgroup': <NEW_LINE> <INDENT> for vv in v: <NEW_LINE> <INDENT> g.addProbability( vv, is_const = False ) <NEW_LINE> <DEDENT> <DEDENT> elif k == 'const_pgroup': <NEW_LINE> <INDENT> for vv in v: <NEW_LINE> <INDENT> g.addProbability( vv, is_const = True ) <NEW_LINE> <DEDENT> <DEDENT> elif k == 'const': <NEW_LINE> <INDENT> for vv in v: <NEW_LINE> <INDENT> if len(vv) == 1: <NEW_LINE> <INDENT> g.addConst( vv[0] ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> g.addConst( vv ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif k == 'rule': <NEW_LINE> <INDENT> for vv in v: <NEW_LINE> <INDENT> g.addRule( vv ) <NEW_LINE> <DEDENT> <DEDENT> elif k == 'nonterminal': <NEW_LINE> <INDENT> for vv in v: <NEW_LINE> <INDENT> g.addNonTerminal( vv ) <NEW_LINE> <DEDENT> <DEDENT> elif k == 'update-rules': <NEW_LINE> <INDENT> g.setUpdateRules( v ) <NEW_LINE> <DEDENT> elif k == 'update-rates': <NEW_LINE> <INDENT> g.setUpdateRates( v ) <NEW_LINE> <DEDENT> elif k == 'parametric': <NEW_LINE> <INDENT> g.setIsParametric( v ) <NEW_LINE> <DEDENT> elif k == 'pseudo-counts': <NEW_LINE> <INDENT> g.setPseudoCounts( v ) <NEW_LINE> <DEDENT> elif k == 'observed-counts': <NEW_LINE> <INDENT> g.setObservedCounts( v ) <NEW_LINE> <DEDENT> elif k == 'observed-chain': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise "unknown component %s" % k <NEW_LINE> <DEDENT> <DEDENT> for t, c in g.getChains().items(): <NEW_LINE> <INDENT> c.addParameters(g) <NEW_LINE> <DEDENT> p[0] = g | 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, value)) is given
to interpret_opcodes() which will then yield collectd `Values´ or `Notification´ instances.
If the `input´ initial value isn't None nor a basestring then it's directly given to
interpret_opcodes(), you have to make sure the `input´ has the correct format.
:return: A generator yielding collectd `Values´ or `Notification´ instances.
:raise:
When a read on the socket is needed, it's not impossible to raise some IO exception.
Otherwise no raise should occur to return the generator.
But the returned generator can raise (subclass-)`CollectdException´ instance if a decode problem occurs. | 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 <NEW_LINE> Meta.postgres = url.scheme.startswith("postgresql") | 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 VS Input size') <NEW_LINE> plt.xlabel('Input size (n)') <NEW_LINE> plt.ylabel('No of Combination') <NEW_LINE> plt.grid() <NEW_LINE> for x, y in zip(X, Y): <NEW_LINE> <INDENT> plt.plot((x,), (y,), 'ro') <NEW_LINE> plt.text(x, y, '(%d, %d)' % (int(x), int(y)), transform=trans_offset) <NEW_LINE> <DEDENT> plt.show() <NEW_LINE> return | 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_vars_configuration = local_vars_configuration <NEW_LINE> self._name = None <NEW_LINE> self._experiment = None <NEW_LINE> self._detector = None <NEW_LINE> self._voltages = None <NEW_LINE> self._created_by = None <NEW_LINE> self._comments = None <NEW_LINE> self._date = None <NEW_LINE> self._id = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.name = name <NEW_LINE> self.experiment = experiment <NEW_LINE> self.detector = detector <NEW_LINE> if voltages is not None: <NEW_LINE> <INDENT> self.voltages = voltages <NEW_LINE> <DEDENT> if created_by is not None: <NEW_LINE> <INDENT> self.created_by = created_by <NEW_LINE> <DEDENT> if comments is not None: <NEW_LINE> <INDENT> self.comments = comments <NEW_LINE> <DEDENT> if date is not None: <NEW_LINE> <INDENT> self.date = date <NEW_LINE> <DEDENT> if id is not None: <NEW_LINE> <INDENT> self.id = id | 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) <NEW_LINE> <DEDENT> beats = pattern.evidence[o.QRS] <NEW_LINE> idx = beats.index(qrs) <NEW_LINE> if idx > 0: <NEW_LINE> <INDENT> tnet.add_constraint(beats[idx-1].time, qrs.time, Iv(C.TACHY_RR.start, 0.9*C.BRADY_RR.end)) <NEW_LINE> <DEDENT> if pattern.istate == 0: <NEW_LINE> <INDENT> if idx == 2: <NEW_LINE> <INDENT> refrr = beats[1].time.end - beats[0].time.start <NEW_LINE> <DEDENT> elif pattern.evidence[o.Cardiac_Rhythm][0] is not pattern.finding: <NEW_LINE> <INDENT> refrr = pattern.hypothesis.meas.rr[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> refrr = None <NEW_LINE> <DEDENT> if refrr is not None: <NEW_LINE> <INDENT> short = min(0.1*refrr, C.TMARGIN) <NEW_LINE> tnet.add_constraint(beats[idx-1].time, qrs.time, Iv(C.TACHY_RR.start, max(C.TACHY_RR.start, refrr-short))) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return tconst | 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)) <NEW_LINE> if length <= start + window: <NEW_LINE> <INDENT> break | 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, 2))
[(0, 5), (2, 7), (4, 8)]
>>> list(make_windows(7, 8, 0))
[(0, 7)] | 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')
>>> print s.createPatternRepresentation()
-***xx*-xx
>>> s.setNTaxa(6)
>>> print s.createPatternRepresentation()
------ | 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 node.state in visited: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> visited.append(node.state) <NEW_LINE> <DEDENT> if problem.isGoalState(node.state): <NEW_LINE> <INDENT> ans = [] <NEW_LINE> while node.parent is not None: <NEW_LINE> <INDENT> ans.append(node.action) <NEW_LINE> node = node.parent <NEW_LINE> <DEDENT> ans.reverse() <NEW_LINE> return ans <NEW_LINE> <DEDENT> for triple in problem.getSuccessors(node.state): <NEW_LINE> <INDENT> newnode = Node(triple[0], triple[1], triple[2], node) <NEW_LINE> queue.push(newnode) <NEW_LINE> <DEDENT> <DEDENT> return [] | 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 Exception as e: <NEW_LINE> <INDENT> raise e | 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_index(inplace=True) <NEW_LINE> result['obj'] = ResumeResult.objects .filter(resume__submitted=True).order_by('id') <NEW_LINE> result['obj'] = result.apply(_update_by_item, axis=1) <NEW_LINE> ResumeResult.objects.bulk_update(result['obj'], ['score', 'rank'], batch_size=256) | 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( 'public/lib/candy/res/default.css')) <NEW_LINE> frag.add_css(self._get_resource_string('public/css/chat.css')) <NEW_LINE> frag.add_javascript(self._get_resource_string(self.STUDENT_JS_PATH)) <NEW_LINE> js_dep_paths = [ 'public/lib/candy/libs/libs.min.js', 'public/lib/candy/candy.bundle.js', ] <NEW_LINE> for js_dep_path in js_dep_paths: <NEW_LINE> <INDENT> frag.add_javascript(self._get_resource_string(js_dep_path)) <NEW_LINE> <DEDENT> frag.initialize_js('Chat') <NEW_LINE> return frag | 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_class = shift_scores[y[i]] <NEW_LINE> loss += -correct_class + np.log(np.sum(np.exp(shift_scores))) <NEW_LINE> for j in range(num_class): <NEW_LINE> <INDENT> temp = np.exp(shift_scores[j])/np.sum(np.exp(shift_scores)) <NEW_LINE> if j == y[i]: <NEW_LINE> <INDENT> dW[:,j] += (-1 + temp) * X[i,:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dW[:,j] += temp * X[i,:] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> loss /= num_train <NEW_LINE> dW /= num_train <NEW_LINE> loss += reg * np.sum(W * W) <NEW_LINE> dW += 2*reg*W <NEW_LINE> return loss, dW | 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,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
- reg: (float) regularization strength
Returns a tuple of:
- loss as single float
- gradient with respect to weights W; an array of same shape as W | 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 = None <NEW_LINE> try: <NEW_LINE> <INDENT> vluns = common.client.getHostVLUNs(chap_username) <NEW_LINE> host_info = common.client.getHost(chap_username) <NEW_LINE> if not host_info['initiatorChapEnabled']: <NEW_LINE> <INDENT> LOG.warn(_LW("Host has no CHAP key, but CHAP is enabled.")) <NEW_LINE> <DEDENT> <DEDENT> except hpexceptions.HTTPNotFound: <NEW_LINE> <INDENT> chap_password = volume_utils.generate_password(16) <NEW_LINE> LOG.warn(_LW("No host or VLUNs exist. Generating new CHAP key.")) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> chap_exists = False <NEW_LINE> active_vluns = 0 <NEW_LINE> for vlun in vluns: <NEW_LINE> <INDENT> if not vlun['active']: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> active_vluns += 1 <NEW_LINE> if ('remoteName' in vlun and re.match('iqn.*', vlun['remoteName'])): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> chap_password = common.client.getVolumeMetaData( vlun['volumeName'], CHAP_PASS_KEY)['value'] <NEW_LINE> chap_exists = True <NEW_LINE> break <NEW_LINE> <DEDENT> except hpexceptions.HTTPNotFound: <NEW_LINE> <INDENT> LOG.debug("The VLUN %s is missing CHAP credentials " "but CHAP is enabled. Skipping." % vlun['remoteName']) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> LOG.warn(_LW("Non-iSCSI VLUN detected.")) <NEW_LINE> <DEDENT> <DEDENT> if not chap_exists: <NEW_LINE> <INDENT> chap_password = volume_utils.generate_password(16) <NEW_LINE> LOG.warn(_LW("No VLUN contained CHAP credentials. " "Generating new CHAP key.")) <NEW_LINE> <DEDENT> <DEDENT> vol_name = common._get_3par_vol_name(volume['id']) <NEW_LINE> common.client.setVolumeMetaData( vol_name, CHAP_USER_KEY, chap_username) <NEW_LINE> common.client.setVolumeMetaData( vol_name, CHAP_PASS_KEY, chap_password) <NEW_LINE> model_update['provider_auth'] = ('CHAP %s %s' % (chap_username, chap_password)) <NEW_LINE> return model_update | 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_years_participated_with_http_info(team_key, **kwargs) <NEW_LINE> return data | 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_=True)
>>> result = thread.get()
:param async_ bool
:param str team_key: TBA Team Key, eg `frc254` (required)
:param str if_modified_since: Value of the `Last-Modified` header in the most recently cached response by the client.
:return: list[int]
If the method is called async_hronously,
returns the request thread. | 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=False) | 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: <NEW_LINE> <INDENT> new_score = game_loop(window_surface, high_score) <NEW_LINE> if new_score > high_score: <NEW_LINE> <INDENT> high_score = new_score <NEW_LINE> save_high_score(high_score) <NEW_LINE> <DEDENT> info_screen(window_surface, 'GAME OVER', 'press return key to continue') | 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) <NEW_LINE> if positional_args > 6: <NEW_LINE> <INDENT> self.add_message( msg_id="client-method-has-more-than-5-positional-arguments", node=node, confidence=None ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> logger.debug("Pylint custom checker failed to check if kwargs is used for multiple parameters.") <NEW_LINE> pass | 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.skate_date.skate_date, event_start_time=start_time[0], amount=price) <NEW_LINE> cart.save() <NEW_LINE> return False | 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.