code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get_stock_index(): <NEW_LINE> <INDENT> df = ts.get_index() <NEW_LINE> res = df.to_sql(table_index_stock, engine, if_exists='replace') <NEW_LINE> msg = 'ok' if res is None else res <NEW_LINE> print('写入大盘指数行情: ' + msg + '\n')
获取大盘指数行情 return
625941ec23849d37ff7b359b
def deprecated_flipped_sigmoid_cross_entropy_with_logits(logits, targets, name=None): <NEW_LINE> <INDENT> return nn.sigmoid_cross_entropy_with_logits( logits=logits, targets=targets, name=name)
Computes sigmoid cross entropy given `logits`. This function diffs from tf.nn.sigmoid_cross_entropy_with_logits only in the argument order. Measures the probability error in discrete classification tasks in which each class is independent and not mutually exclusive. For instance, one could perform multilabel classif...
625941ecd58c6744b425816e
def update_user_profile(self, token, username, email, first_name, last_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> token = "Bearer " + token <NEW_LINE> metadata = (('authorization', token),) <NEW_LINE> profile = UserProfile(username=username, email=email, first_name=first_name, last_name=last_name) <NEW_LINE> r...
Update user profile :param token: user token :param username: :param email: :param first_name: :param last_name: :return:
625941ec9c8ee82313fbbc87
def forward(self,input_X): <NEW_LINE> <INDENT> batch_size,in_h,in_w,num_in_channels = input_X.shape <NEW_LINE> if self.padding == 'same': <NEW_LINE> <INDENT> pad = (self.filter_size - 1)/2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pad = 0 <NEW_LINE> <DEDENT> out_h, out_w = _get_out_shape(self.filter_size,pad,self.s...
Compute forward propagation Argument: input_X: 4-D numpy array, of shape (batch_size, height, width, #channels) Return: output: 4-D numpy array, of shape (batch_size, output_height, output_width, num_filters) output_height and output_width are calculated using this formula output_...
625941ecd99f1b3c44c67a95
def keys_rm(self): <NEW_LINE> <INDENT> return ['cpu_percent', 'cpu_times', 'cpu_num', 'cpu_affinity', 'connections', 'gids', 'ionice', 'io_counters', 'memory_percent', 'memory_maps', 'memory_full_info', 'memory_info', 'nice', 'num_fds', 'num_threads', 'num_ctx_switches', 'open_files', 'status', 'threads', 'terminal', '...
attrs that do not need for this app
625941ec30bbd722463cc2d9
def __init__(self, parent=None): <NEW_LINE> <INDENT> super(UpdateLocationsDialog, self).__init__(parent) <NEW_LINE> self.createDialog() <NEW_LINE> self.createConnections()
Dialog to rename file or folder @param currentName: @type currentName: @param folder: @type folder: @param parent: @type parent:
625941ec5e10d32532c5f435
def __getattr__(self, name): <NEW_LINE> <INDENT> name = name.replace('_', '-') <NEW_LINE> def runner(*args, **kwargs): <NEW_LINE> <INDENT> cmdv = [] <NEW_LINE> config = kwargs.pop('config', None) <NEW_LINE> for k in kwargs: <NEW_LINE> <INDENT> raise TypeError('%s() got an unexpected keyword argument %r' % (name, k)) <N...
Allow arbitrary git commands using pythonic syntax. This allows you to do things like: git_obj.rev_parse('HEAD') Since we don't have a 'rev_parse' method defined, the __getattr__ will run. We'll replace the '_' with a '-' and try to run a git command. Any other positional arguments will be passed to the git comman...
625941ecd53ae8145f87a776
def stde_median(data, axis=None): <NEW_LINE> <INDENT> def _stdemed_1D(data): <NEW_LINE> <INDENT> data = np.sort(data.compressed()) <NEW_LINE> n = len(data) <NEW_LINE> z = 2.5758293035489004 <NEW_LINE> k = int(np.round((n+1)/2. - z * np.sqrt(n/4.),0)) <NEW_LINE> return ((data[n-k] - data[k-1])/(2.*z)) <NEW_LINE> <DEDENT...
Returns the McKean-Schrader estimate of the standard error of the sample median along the given axis. masked values are discarded. Parameters ---------- data : ndarray Data to trim. axis : {None,int}, optional Axis along which to perform the trimming. If None,...
625941ec3539df3088e2e85b
def _set_progress_hasVoted(user): <NEW_LINE> <INDENT> def txn(): <NEW_LINE> <INDENT> voter = _get_or_create_voter(user) <NEW_LINE> if not voter.hasVoted: <NEW_LINE> <INDENT> voter.hasVoted = True <NEW_LINE> voter.put() <NEW_LINE> <DEDENT> <DEDENT> db.run_in_transaction(txn)
Sets Voter.hasVoted = True for the given user.
625941ec3cc13d1c6d3c7888
def reorderList(self, head: ListNode) -> None: <NEW_LINE> <INDENT> lst = [] <NEW_LINE> cur = head <NEW_LINE> while(cur): <NEW_LINE> <INDENT> lst.append(cur) <NEW_LINE> cur = cur.next <NEW_LINE> <DEDENT> lst1 = lst[:len(lst)//2] <NEW_LINE> lst2 = lst[len(lst)//2:] <NEW_LINE> lst2.reverse() <NEW_LINE> lst = [] <NEW_LINE>...
Do not return anything, modify head in-place instead.
625941ec5f7d997b87174fad
def update(self): <NEW_LINE> <INDENT> self._data.update() <NEW_LINE> if not self._data.yahoo.RawData: <NEW_LINE> <INDENT> _LOGGER.info("Don't receive weather data from yahoo!") <NEW_LINE> return <NEW_LINE> <DEDENT> self._code = self._data.yahoo.Now["code"] <NEW_LINE> if self._type == "weather_current": <NEW_LINE> <INDE...
Get the latest data from Yahoo! and updates the states.
625941ecf8510a7c17cf9c10
def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkLabelShapeImageFilterIUC2.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj
New() -> itkLabelShapeImageFilterIUC2 Create a new object of the class itkLabelShapeImageFilterIUC2 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in...
625941ec99cbb53fe67930f5
def load_criteria(self): <NEW_LINE> <INDENT> self.loaded_criteria = self.segmentation.get_nuclei_criteria(True) <NEW_LINE> for criteria_raw in self.criteria: <NEW_LINE> <INDENT> if self.loaded_criteria is not None and criteria_raw in self.loaded_criteria.keys(): <NEW_LINE> <INDENT> if self.loaded_criteria[criteria_raw]...
Load selection criteria :return:
625941ec8e7ae83300e4b4df
def _findCaller(): <NEW_LINE> <INDENT> f = currentframe() <NEW_LINE> if f is not None: <NEW_LINE> <INDENT> f = f.f_back <NEW_LINE> <DEDENT> rv = "(unknown file)", 0, "(unknown function)" <NEW_LINE> while hasattr(f, "f_code"): <NEW_LINE> <INDENT> co = f.f_code <NEW_LINE> filename = os.path.normcase(co.co_filename) <NEW_...
Find the stack frame of the caller so that we can note the source file name, line number and function name.
625941ec57b8e32f524839af
def e(z): <NEW_LINE> <INDENT> return z.__len__() - z.index('T') - 1
'T'后面'A'的数量
625941ece5267d203edce1a7
def is_defensive_zone(stateFoot, distDefZone=20.): <NEW_LINE> <INDENT> return stateFoot.distance(stateFoot.my_goal) < distDefZone or distance_horizontale(stateFoot.my_pos, stateFoot.my_goal) < distDefZone-10.
Renvoie vrai ssi la distance entre le joueur et sa cage est inferieure a <distDefZone>
625941ecdc8b845886cb5a47
def _create_nodes(self, cluster, count, policy_data): <NEW_LINE> <INDENT> placement = policy_data.get('placement', None) <NEW_LINE> for m in range(count): <NEW_LINE> <INDENT> name = 'node-%s-%003d' % (cluster.id[:8], cluster.size + m + 1) <NEW_LINE> node = node_mod.Node(name, cluster.profile_id, cluster.id, context=sel...
Utility method for node creation.
625941ec4d74a7450ccd46d5
def getLog(self): <NEW_LINE> <INDENT> return self.session.request('diag/log/')
Gets the entire contents of the replay.log file.
625941ec56b00c62f0f14b6d
def str2dict(s: str, namespace={}, sep: str = '='): <NEW_LINE> <INDENT> def myeval(value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = eval(value, namespace) <NEW_LINE> <DEDENT> except (NameError, SyntaxError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> dct = {} <NEW_LINE> s ...
Convert comma-separated key=value string to dictionary. Examples: >>> str2dict('xc=PBE,nbands=200,parallel={band:4}') {'xc': 'PBE', 'nbands': 200, 'parallel': {'band': 4}} >>> str2dict('a=1.2,b=True,c=ab,d=1,2,3,e={f:42,g:cd}') {'a': 1.2, 'c': 'ab', 'b': True, 'e': {'g': 'cd', 'f': 42}, 'd': (1, 2, 3)}
625941ec6e29344779a62b21
def comment(self, content): <NEW_LINE> <INDENT> pass
called when a comment has been found, content contains the comment
625941ecd7e4931a7ee9e430
def test_2_1x2(self): <NEW_LINE> <INDENT> grid = Grid([[-12],[24]]) <NEW_LINE> self.assertTrue(grid.all_columns_same_max())
If there's only one column, it must be the same
625941ec2ae34c7f2600d641
def pred_output(self, x0, u_hor, p_hor, reshape_2d=False): <NEW_LINE> <INDENT> F = self.F <NEW_LINE> Hu = self.Hu <NEW_LINE> Hp = self.Hp <NEW_LINE> y_hor = np.dot(F, x0) + np.dot(Hu,u_hor) + np.dot(Hp, p_hor) <NEW_LINE> if reshape_2d: <NEW_LINE> <INDENT> y_hor = y_hor.reshape((self.nh, self.dyn.ny)) <NEW_LINE> <DEDENT...
predicted future outputs of the system given * initial state `x0` and * predicted inputs `u_hor` and `p_hor` over the horizon if `reshape_2d` is True, returns a (nh,ny) array instead of the flat (nh*ny,1) column vector (default). formula y = Fx + Hu.u + Hp.p
625941ec21bff66bcd684e5e
def test_server_error(self): <NEW_LINE> <INDENT> token = generate_token() <NEW_LINE> client = Client(token) <NEW_LINE> response = Mock() <NEW_LINE> response.status_code = 500 <NEW_LINE> response.text = ( '<!DOCTYPE html>\n<html>\n<body>\n<meta http-equiv="refresh" ' 'content=\'0;URL=http://www.ebi.ac.uk/errors/failure....
Deal with the generic 50x states
625941ec004d5f362079a840
def query_insert(self, direction='max'): <NEW_LINE> <INDENT> from datetime import datetime <NEW_LINE> if direction=='min': <NEW_LINE> <INDENT> return ResourceBase.objects.aggregate( Min('date'))['date__min'].strftime('%Y-%m-%dT%H:%M:%SZ') <NEW_LINE> <DEDENT> return self._get_repo_filter(ResourceBase.objects).aggregate(...
Query to get latest (default) or earliest update to repository
625941ec45492302aab5e7d9
def release_address(self, public_ip): <NEW_LINE> <INDENT> params = {'PublicIp' : public_ip} <NEW_LINE> return self.get_status('ReleaseAddress', params, verb='POST')
Free up an Elastic IP address :type public_ip: string :param public_ip: The public IP address :rtype: bool :return: True if successful
625941ec4428ac0f6e5bad08
def __init__(self, handler, resource, session): <NEW_LINE> <INDENT> super(HandlerAPI, self).__init__() <NEW_LINE> self.__handler = handler <NEW_LINE> self.__resource = resource <NEW_LINE> self.__session = session <NEW_LINE> self.__populate()
Construct a `HandlerAPI`. :param handler: The handler description from the overall API description document. See `SessionAPI`. :param resource: The parent of `handler` in the API description document. XXX: This does not appear to be needed. :param session: The `SessionAPI`.
625941eca79ad161976cc656
def open_file(self): <NEW_LINE> <INDENT> filters = "{} Data Files (*.csv);;All Files (*.*)".format(self.title) <NEW_LINE> selected_filter = "{} Data Files (*.cpt)".format(self.title) <NEW_LINE> fname = QFileDialog.getOpenFileName(self, 'Open File', self.export_path, filters, selected_filter) <NEW_LINE> if fname[0]: <NE...
Returns: a tuple as (filename, data_dictionary) or None if something went wrong.
625941ec8a349b6b435e8683
def show_bday_boy(self) -> list: <NEW_LINE> <INDENT> bday_boys = list() <NEW_LINE> today = datetime.date.today() <NEW_LINE> thirty_days = today + datetime.timedelta(days=30) <NEW_LINE> today = str(today).split('-') <NEW_LINE> today_month = today[1] <NEW_LINE> today_day = today[2] <NEW_LINE> thirty_days = str(thirty_day...
Shows all people who have a birthday in the next 30 days. :return: list of surname+name
625941ecec188e330fd5aca5
def test_rid(self) -> None: <NEW_LINE> <INDENT> self.assertEqual(parse_general_name("rid:2.5.4.3"), x509.RegisteredID(NameOID.COMMON_NAME))
Test parsing a Registered ID.
625941ec16aa5153ce362989
def worldtopixel(x, y): <NEW_LINE> <INDENT> col = round((x - transform[0]) / transform[1] - 0.5) <NEW_LINE> row = round((y - transform[3]) / transform[5] - 0.5) <NEW_LINE> return row, col
Transform real world coordinates (x, y) into raster pixel coordinates (row, col)
625941ec8c0ade5d55d3eed0
def file_upload(filepath, verbose=False, session=None): <NEW_LINE> <INDENT> cli = get_cli(verbose, session) <NEW_LINE> fileapi = IrmaFilesApi(cli) <NEW_LINE> file = fileapi.create(filepath) <NEW_LINE> return file
Upload file to IRMA server :param filepath: full path qualified file :type filepath: str :param verbose: enable verbose requests (optional default:False) :type verbose: bool :return: return the updated scan object :rtype: IrmaFileExt
625941ecad47b63b2c50a490
def get_attr(self, attr_key): <NEW_LINE> <INDENT> return _ffi_api.Module_GetAttr(self, attr_key)
Get the IRModule attribute. Parameters ---------- attr_key : str The attribute key. Returns ------- attr_value : Any Attribute value
625941ec090684286d50f1ff
def p_elements_char(p): <NEW_LINE> <INDENT> p[0]=[["char",p[1]]]
elements_array : CHAR
625941eca05bb46b383ecd2d
def ecrire_classes(self, classes, server): <NEW_LINE> <INDENT> sorted_sections = sorted(server.sections, key=len, reverse=True) <NEW_LINE> for cla in classes: <NEW_LINE> <INDENT> sec = '' <NEW_LINE> for section in sorted_sections: <NEW_LINE> <INDENT> if section in cla: <NEW_LINE> <INDENT> sec = section <NEW_LINE> break...
Insère une liste de classes (fin d'importation) :param classes: les classes à créer :param server: pointeur vers le serveur (pour accéder à ses données) :type classes: list :type server: pointeur
625941ec7b180e01f3dc4d03
def get_data(self, table, coverage, resolution, category_filters={}, r_compat=False): <NEW_LINE> <INDENT> msoa_workaround = False <NEW_LINE> if resolution == "MSOA11": <NEW_LINE> <INDENT> msoa_workaround = True <NEW_LINE> resolution = "LSOA11" <NEW_LINE> <DEDENT> geography = self.get_geog(coverage, resolution) <NEW_LIN...
Returns a table with categories in columns, filtered by geography and (optionally) category values If r_compat==True, instead of returning a pandas dataframe it returns a dict raw value data and column names that can be converted into an R data.frame
625941ece64d504609d74d51
def encode_auth_token(user_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> payload = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=0, seconds=60), 'iat': datetime.datetime.utcnow(), 'sub': user_id } <NEW_LINE> return jwt.encode( payload, SECRET_KEY, algorithm='HS256' ) <NEW_LINE> <DEDENT> except Excep...
Generates the Auth Token :return: string
625941ecd6c5a10208144560
def testResetMembers(self): <NEW_LINE> <INDENT> self.assertEqual( {'uniqueId': [self.cd]}, cdl_convert.ColorDecision.members ) <NEW_LINE> cdl_convert.ColorDecision.reset_members() <NEW_LINE> self.assertEqual( {}, cdl_convert.ColorDecision.members )
Tess that our membership resets correctly
625941ec45492302aab5e7da
def __init__(self): <NEW_LINE> <INDENT> self.logger = logging.getLogger()
Constructor
625941ec30bbd722463cc2da
def __init__( self, *, tags: Optional[Dict[str, str]] = None, **kwargs ): <NEW_LINE> <INDENT> super(ApimResource, self).__init__(**kwargs) <NEW_LINE> self.id = None <NEW_LINE> self.name = None <NEW_LINE> self.type = None <NEW_LINE> self.tags = tags
:keyword tags: A set of tags. Resource tags. :paramtype tags: dict[str, str]
625941eccb5e8a47e48b7fb3
def get_template(self, level): <NEW_LINE> <INDENT> self.check_level_exists(level) <NEW_LINE> return Template(getattr(self, 'template_%s' % level))
Return the template expression for the given ``level``
625941ec460517430c394688
def rw_active(self): <NEW_LINE> <INDENT> result = False <NEW_LINE> for disk in self.disks: <NEW_LINE> <INDENT> result = disk.rw_active() or result <NEW_LINE> <DEDENT> return result
Indicates whether a read-write cache is active in any of the disks. :rtype: bool
625941ec85dfad0860c3b36d
def getWebDriverInstance(self): <NEW_LINE> <INDENT> baseURL = "http://live.demoguru99.com/index.php/backendlogin/" <NEW_LINE> if self.browser == "iexplorer": <NEW_LINE> <INDENT> driver = webdriver.Ie("C:\\drivers\\IEDriverServer.exe") <NEW_LINE> <DEDENT> elif self.browser == "firefox": <NEW_LINE> <INDENT> driver = webd...
Get WebDriver Instance based on the browser configuration Returns: 'WebDriver Instance'
625941ec167d2b6e312190a6
def _CreateInputParameter(func_name, ast_param, arg, args): <NEW_LINE> <INDENT> ptype = ast_param.type <NEW_LINE> ctype = ptype.cpp_type <NEW_LINE> smartptr = (ctype.startswith('::std::unique_ptr') or ctype.startswith('::std::shared_ptr')) <NEW_LINE> if not ctype: <NEW_LINE> <INDENT> assert ptype.callable, 'Non-callabl...
Return a string to create C++ stack var named arg. args += arg getter.
625941ec3317a56b8693a15d
def GetHostId(self): <NEW_LINE> <INDENT> pass
GetHostId(self: Rebar) -> ElementId The element that contains the rebar. Returns: The element that the rebar object belongs to,such as a structural wall, floor,foundation,beam,brace or column.
625941ec71ff763f4b549ba6
def p_fole_not(self, p): <NEW_LINE> <INDENT> p[0] = {p[1]: p[2]}
fole : NOT fole
625941ecaad79263cf390f5a
def __init__(self, station_file: str, ride_file: str) -> None: <NEW_LINE> <INDENT> self.all_stations = create_stations(station_file) <NEW_LINE> self.all_rides = create_rides(ride_file, self.all_stations) <NEW_LINE> self.visualizer = Visualizer() <NEW_LINE> self.active_rides = []
Initialize this simulation with the given configuration settings.
625941ecbd1bec0571d90b40
def submit(self, order, try_to_match=False): <NEW_LINE> <INDENT> if try_to_match: <NEW_LINE> <INDENT> self.match_order(order) <NEW_LINE> return <NEW_LINE> <DEDENT> if order.is_buy(): <NEW_LINE> <INDENT> self.buy_orders.append(order) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.sell_orders.append(order) <NEW_LINE>...
order: instance of order.
625941ecc432627299f0515b
def spatial_pyramid_pooling_2d(x, pyramid_height, pooling_class, use_cudnn=True): <NEW_LINE> <INDENT> return SpatialPyramidPooling2D(x.shape[1:], pyramid_height, pooling_class, use_cudnn=use_cudnn)(x)
Spatial pyramid pooling function. It outputs a fixed-length vector regardless of input feature map size. It performs pooling operation to the input 4D-array ``x`` with different kernel sizes and padding sizes, and then flattens all dimensions except first dimension of all pooling results, and finally concatenates the...
625941ec07d97122c4178da9
def test_list_overrides_with_page(self, mocker): <NEW_LINE> <INDENT> client = bindings.BodhiClient() <NEW_LINE> client.send_request = mocker.MagicMock(return_value='response') <NEW_LINE> response = client.list_overrides(page=5) <NEW_LINE> assert response == 'response' <NEW_LINE> client.send_request.assert_called_once_w...
Test with the page parameter.
625941ecbe7bc26dc91cdb07
def centroid_data_volume(self, cluster_id): <NEW_LINE> <INDENT> centroid = self._find_cluster(cluster_id) <NEW_LINE> segment_pairs = itertools.permutations(centroid.segments, 2) <NEW_LINE> volume = np.sum( [segment_volume(s, d, self.env) for s, d in segment_pairs]) <NEW_LINE> cluster_pairs = list() <NEW_LINE> for clust...
:param cluster_id: :return: :rtype: pq.bit
625941ec26068e7796caf1f9
def linked_list_merge(head1,head2): <NEW_LINE> <INDENT> if head1 is None: <NEW_LINE> <INDENT> return head2 <NEW_LINE> <DEDENT> if head2 is None: <NEW_LINE> <INDENT> return head1 <NEW_LINE> <DEDENT> if head1 is None and head2 is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> new_list = SingleNode() <NEW_LINE>...
两个有序链表合并 :param head1: :param head2: :return:
625941ec66673b3332b925a3
def find_bindings(self, visitor): <NEW_LINE> <INDENT> bindings = visitor(self.list_bindings(), self._attributes) <NEW_LINE> for binding in self.list_bindings(): <NEW_LINE> <INDENT> obj = binding.obj <NEW_LINE> if isinstance(obj, DirContext): <NEW_LINE> <INDENT> bindings.extend(obj.find_bindings(visitor)) <NEW_LINE> <DE...
Find bindings with attributes matching criteria in visitor. Visitor is a function that is passed the bindings for each level of the heirarchy and the attribute dictionary for those bindings. The visitor examines the bindings and dictionary and returns the bindings it is interested in.
625941ec50812a4eaa59c82e
def importFile(self, srcUrl, sharedFileName=None): <NEW_LINE> <INDENT> self._assertContextManagerUsed() <NEW_LINE> return self._jobStore.importFile(srcUrl, sharedFileName=sharedFileName)
Imports the file at the given URL into job store. See :func:`toil.jobStores.abstractJobStore.AbstractJobStore.importFile` for a full description
625941ec3c8af77a43ae3cb8
def testCfhFifo(t, env): <NEW_LINE> <INDENT> name = env.testname(t) <NEW_LINE> c = env.c1.new_client(name) <NEW_LINE> sess = c.create_session() <NEW_LINE> res = create_obj(sess, [name]) <NEW_LINE> check(res) <NEW_LINE> res = rename_obj(sess, env.c1.homedir + [name], env.opts.usefifo + [name]) <NEW_LINE> check(res, NFS4...
RENAME with non-dir (cfh) should return NFS4ERR_NOTDIR FLAGS: rename fifo all CODE: RNM3f
625941ecbf627c535bc136e1
def on_close(self, view): <NEW_LINE> <INDENT> set_timeout_async(lambda: mediator.remove(view), 1)
Unregister any listeners for the view that was just closed.
625941ec91af0d3eaac9bf2f
def get_desnity(self): <NEW_LINE> <INDENT> return self.density
returns the density of the fluid in pipe
625941ec3d592f4c4ed1d571
def valid_postcode_unit(unit: str): <NEW_LINE> <INDENT> result = bool(re.match( "[A-Z]{2}|BFPO ?[0-9]{1,4}|(KY[0-9]|MSR|VG|AI)[ -]?[0-9]{4}|[A-Z]{2} ?[0-9]{2}|GE ?CX|GIR ?0A{2}|SAN ?TA1", unit )) <NEW_LINE> return result
Validate a british postcode unit :param unit: A string with the UK postcode unit :return: A boolean result with whether the postcode unit is valid or not
625941ec4e4d5625662d48e2
def combineLabel(Y1, Y2): <NEW_LINE> <INDENT> Y = np.zeros(Y1.size) <NEW_LINE> for i in range(Y1.size): <NEW_LINE> <INDENT> if Y1[i] == 1: <NEW_LINE> <INDENT> Y[i] = 1 <NEW_LINE> <DEDENT> if Y2[i] == 1: <NEW_LINE> <INDENT> Y[i] = 2 <NEW_LINE> <DEDENT> <DEDENT> return Y
Combines labels from Ymin and Ymax. This not really needed, but it was needed for an experiment.
625941ecbe7bc26dc91cdb08
def get(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.get_with_http_info(**kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.get_with_http_info(**kwargs) <NEW_LINE> return data
Get a list of all outputs This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get(callback=callback_function) :p...
625941ecbaa26c4b54cb162c
def setBatteryInfo(self, battery_voltage): <NEW_LINE> <INDENT> msg = json.dumps({"battery": battery_voltage}) <NEW_LINE> self.send2All(msg)
Notify the user of battery voltage.
625941ec99fddb7c1c9de8a0
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, AccountSettingsTsp): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941ecfb3f5b602dac3baa
def runner(fun, arg=None, timeout=5): <NEW_LINE> <INDENT> arg = _parse_args(arg) <NEW_LINE> load = {'cmd': 'minion_runner', 'fun': fun, 'arg': arg, 'tmo': timeout, 'id': __opts__['id']} <NEW_LINE> sreq = salt.transport.Channel.factory(__opts__) <NEW_LINE> try: <NEW_LINE> <INDENT> return sreq.send(load) <NEW_LINE> <DEDE...
Execute a runner on the master and return the data from the runner function CLI Example: .. code-block:: bash salt publish.runner manage.down
625941eccc0a2c11143dd3a3
def emit(self, state, action): <NEW_LINE> <INDENT> state = copy.deepcopy(state) <NEW_LINE> for listener in self.listeners: <NEW_LINE> <INDENT> listener(state, action)
Announce to any interested listeners each action and the state before the action
625941ec9f2886367277ad9b
def _html(title: str, field_names: List[str]) -> str: <NEW_LINE> <INDENT> inputs = ''.join(_SINGLE_INPUT_TEMPLATE.substitute(field_name=field_name) for field_name in field_names) <NEW_LINE> quoted_field_names = [f"'{field_name}'" for field_name in field_names] <NEW_LINE> quoted_field_list = f"[{','.join(quoted_field_na...
Returns bare bones HTML for serving up an input form with the specified fields that can render predictions from the configured model.
625941ec442bda511e8be922
def confusion_matrix(self, y_true, y_pred, labels=None, sample_weight=None): <NEW_LINE> <INDENT> from scipy.sparse import coo_matrix <NEW_LINE> if sample_weight is None: <NEW_LINE> <INDENT> sample_weight = np.ones(y_true.shape[0], dtype=np.int64) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sample_weight = np.asarray(...
Get confusion matrix from labels and predictions; mostly stolen from sci-kit learn Args: y_true (array-like): y_pred (array-like): labels (array-like): list/array of labels, only needed for size? Returns: confusion_matrix (np.ndarray)
625941ecd6c5a10208144561
def handle(self, *args, **options): <NEW_LINE> <INDENT> programs = Program.objects.prefetch_related("programruns", "courses") <NEW_LINE> if options["program"]: <NEW_LINE> <INDENT> programs = programs.filter(readable_id=options["program"]) <NEW_LINE> <DEDENT> program_run_results = {} <NEW_LINE> for program in programs: ...
Handle command execution
625941ec711fe17d82542871
def addPrimPath(self, path, instance=ALL_INSTANCES): <NEW_LINE> <INDENT> if path not in self._selection: <NEW_LINE> <INDENT> if path in self._removed: <NEW_LINE> <INDENT> self._removed.discard(path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._added.add(path) <NEW_LINE> <DEDENT> <DEDENT> if instance == ALL_INSTA...
Add a path to the selection. If an instance is given, then only add that instance. If all instances are selected when this happens then the single instance will become the only selected one.
625941ec1b99ca400220afc5
def __init__(self): <NEW_LINE> <INDENT> self.date = str(date.today()) <NEW_LINE> today_date = str(date.today()) <NEW_LINE> today_date = today_date.split("-") <NEW_LINE> self.curr_year = int(today_date[0]) <NEW_LINE> self.curr_month = int(today_date[1]) <NEW_LINE> self.curr_date = int(today_date[2])
initialized the necessary element for the date class
625941ec07f4c71912b11997
def get_emails(self): <NEW_LINE> <INDENT> email_ids = self.get_email_ids() <NEW_LINE> Email = get_email_class() <NEW_LINE> return [email for email in Email.objects.filter(pk__in=email_ids)]
Return the list of Email instances that have been sent to the invitee.
625941ec4f88993c3716c573
def _find_start(score_matrix, align_globally): <NEW_LINE> <INDENT> nrows, ncols = len(score_matrix), len(score_matrix[0]) <NEW_LINE> if align_globally: <NEW_LINE> <INDENT> starts = [(score_matrix[-1][-1], (nrows - 1, ncols - 1))] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> starts = [] <NEW_LINE> for row in range(nrow...
Return a list of starting points (score, (row, col)) (PRIVATE). Indicating every possible place to start the tracebacks.
625941ec627d3e7fe0d69363
def sigmoid(x): <NEW_LINE> <INDENT> return 1.0 / (1.0 + np.exp(-x))
The sigmoid function. Parameters ---------- x : A scalar or ndarray. Returns ------- The sigmoid evaluated at x (or its elements if it is an ndarray).
625941ec097d151d1a223369
def _getChildNodesByName_(self:Node, nodeSel:NodeSel) -> list: <NEW_LINE> <INDENT> return self._getListItemsByName_(self.childNodes, nodeSel)
Return a list of this node's children of a given kind..
625941ec5fdd1c0f98dc0747
def changespeed(self, x, y): <NEW_LINE> <INDENT> self.change_x = x <NEW_LINE> self.change_y = y
Change the speed of the player
625941ec8e05c05ec3eea88b
def _get_label_color( num_labels: Dict[str, List[Any]], colors: Union[List[str], None] = None, cmap: str = "tab20" ) -> Tuple[List["Line2D"], "ListedColormap"]: <NEW_LINE> <INDENT> cmap = ListedColormap(colors) if colors else plt.get_cmap(cmap, lut=num_labels) <NEW_LINE> legend_labels = list() <NEW_LINE> for idx in ran...
Define colours for labels A color map is generated for given number of labels. If 'colors' is defined, then this color definition overwrites automatically generated color map. Args: num_labels: Number of labels colors: List with defined colors cmap: Colour map name Returns: Tuple with l...
625941ec287bf620b61d3f72
def make_ccw(polygon): <NEW_LINE> <INDENT> linear_ring = LinearRing(polygon.exterior.coords) <NEW_LINE> if linear_ring.is_ccw: <NEW_LINE> <INDENT> print(f"{polygon} is already ccw") <NEW_LINE> return polygon <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(f"{polygon} was made ccw") <NEW_LINE> return Polygon(list(li...
test if poylgon is ccw, if not, return ccw copy of polygon
625941ec7b25080760e39968
def setScreenshotArchiveMethod(self, screenshotArchiveMethod): <NEW_LINE> <INDENT> if screenshotArchiveMethod == "remove": <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif screenshotArchiveMethod == "resize": <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif screenshotArchiveMethod.startswith("resize"): <NEW_LINE> <IN...
Set method for archiving screenshots when screenshotLimit is exceeded. Parameters: screenshotArchiveMethod (string) Supported methods are "resize [WxH]" and "remove" where W and H are integers that define maximum width and height for an archived screenshot. The default method ...
625941ec24f1403a92601074
def read(filename): <NEW_LINE> <INDENT> with open(filename, 'rb') as f: <NEW_LINE> <INDENT> bytes = f.read() <NEW_LINE> if PY3: <NEW_LINE> <INDENT> return bytes <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [ord(x) for x in bytes]
Read the file to be programmed and turn it into a binary
625941ec091ae35668667467
def load_config(path): <NEW_LINE> <INDENT> return SourceFileLoader('config', path).load_module()
"Load configuration from path
625941ecff9c53063f47c703
def keyfunc(name: str) -> Tuple[bool, int, str]: <NEW_LINE> <INDENT> base, suffix = os.path.splitext(name) <NEW_LINE> for i, ext in enumerate(PY_EXTENSIONS): <NEW_LINE> <INDENT> if suffix == ext: <NEW_LINE> <INDENT> return (base != "__init__", i, base) <NEW_LINE> <DEDENT> <DEDENT> return (base != "__init__", -1, name)
Determines sort order for directory listing. The desirable properties are: 1) foo < foo.pyi < foo.py 2) __init__.py[i] < foo
625941ecfbf16365ca6f66e1
def test_success_defaults(self): <NEW_LINE> <INDENT> cfg = ConfigParser() <NEW_LINE> cfg.read_string(self.SUCCESS_DEFAULTS_CONFIG) <NEW_LINE> mail = Mail.from_config(cfg) <NEW_LINE> self.assertEqual(mail.server, Mail.DEFAULT_SERVER) <NEW_LINE> self.assertEqual(mail.port, Mail.DEFAULT_PORT)
Create Mail objects with defaults.
625941ecd53ae8145f87a778
def call_on_idle(func, *args, **kwargs): <NEW_LINE> <INDENT> call_on_idle.idle_q.append((func, args, kwargs))
Registers a callable to be executed when the event loop is empty. The callable will only be called once. This is used to execute the _destroy() method of AvoPlotElementBase.
625941ec187af65679ca5632
def CreateContact(self, new_contact, insert_uri='/m8/feeds/contacts/default/full', url_params=None, escape_params=True): <NEW_LINE> <INDENT> return self.Post(new_contact, insert_uri, url_params=url_params, escape_params=escape_params, converter=gdata.contacts.ContactEntryFromString)
Adds an event to Google Contacts. Args: new_contact: atom.Entry or subclass A new event which is to be added to Google Contacts. insert_uri: the URL to post new contacts to the feed url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape...
625941ecb57a9660fec33d9e
def publish(self, pika_log_level: int = logging.ERROR) -> Any: <NEW_LINE> <INDENT> from carrot.models import MessageLog <NEW_LINE> logging.getLogger("pika").setLevel(pika_log_level) <NEW_LINE> connection, channel = self.connection_channel <NEW_LINE> if isinstance(self.task_kwargs, str): <NEW_LINE> <INDENT> try: <NEW_LI...
Publishes the message to RabbitMQ queue and creates a MessageLog object so the progress of the task can be tracked in the Django project's database
625941ece1aae11d1e74a1cf
def serialize(self, order_type): <NEW_LINE> <INDENT> if order_type: <NEW_LINE> <INDENT> root = etree.Element("OrderRequestHeader") <NEW_LINE> for node, node_text in [ ('ProductCode', self.product_code), ('PartnerOrderID', self.partner_order_id) ]: <NEW_LINE> <INDENT> utils.create_subelement_with_text(root, node, node_t...
Serializes the request header. Each request model should call this in order to process the request. The request model will initiate serialization here. :order_type: a True or False value to create the proper XML header for the request. :return: root element for the request header
625941ecbd1bec0571d90b41
def call(self, inputs, **kwargs): <NEW_LINE> <INDENT> x = self.padding(inputs) <NEW_LINE> x = self.down_sample(x) <NEW_LINE> x1, x2 = tf.split(x, num_or_size_splits=2, axis=-1) <NEW_LINE> for i in range(kwargs['num_blocks']): <NEW_LINE> <INDENT> x = self.conv(x1) <NEW_LINE> x1 += x <NEW_LINE> <DEDENT> return self.conca...
Parameters ---------- inputs : tensor kwargs : num_blocks Returns ------- Tensor
625941ec5510c4643540f8e9
def _is_path_in_directories(filename, directories): <NEW_LINE> <INDENT> fixed_path = os.path.normcase(os.path.abspath(filename)) <NEW_LINE> for parent in directories: <NEW_LINE> <INDENT> fixed_parent = os.path.normcase(os.path.abspath(parent)) <NEW_LINE> if os.path.commonprefix([fixed_path, fixed_parent]) == fixed_pare...
Determines if a filename is contained within one of a set of directories. Args: filename: Path of the file (relative or absolute). directories: Iterable collection of paths to directories which the given filename may be under. Returns: True if the supplied filename is in one of the given sub-directories or ...
625941ec8e7ae83300e4b4e1
def extract_jobs(text_response): <NEW_LINE> <INDENT> processed_data = yaml.safe_load(text_response) <NEW_LINE> for i, j in enumerate(processed_data): <NEW_LINE> <INDENT> if 'project' in j.keys(): <NEW_LINE> <INDENT> project_index = i <NEW_LINE> <DEDENT> <DEDENT> extracted_job_name = [] <NEW_LINE> jobs = processed_data[...
Extract jobs name in a list from string :param url: text_response: string containing jobs name in multiple lines :returns: extracted_job_name: List containing jobs name
625941ecbde94217f36832fe
def decryptFile(ifile, key, ofile=None): <NEW_LINE> <INDENT> if ofile is None: <NEW_LINE> <INDENT> ofile = createTmpFile() <NEW_LINE> <DEDENT> p = Popen(['openssl', 'enc', '-d', '-aes-128-cbc', '-in', ifile, '-out', ofile, '-pass', 'stdin'], stdin=PIPE, stdout=PIPE, stderr=PIPE) <NEW_LINE> p.stdin.write(key) <NEW_LINE>...
Decrypt ifile and write it to ofile
625941ec4e696a04525c9960
def trimr(array, percentile, axis=None, fill_value=0): <NEW_LINE> <INDENT> array = np.array(array) <NEW_LINE> val_percentile = np.percentile(array, q=float(percentile), axis=axis, keepdims=True) <NEW_LINE> array[array > val_percentile] = fill_value <NEW_LINE> return array
Trim values in an array that fall above (i.e. to the right) a certain percentile. Parameters ---------- array : `~numpy.ndarray` Array to be trimmed, typically an image. percentile : float in range [0, 100] Percentile above which array elements are set to ``fill_value``. axis : int or None, optional Axis a...
625941ece8904600ed9f2448
def SetRunOneIteration(self, *args): <NEW_LINE> <INDENT> return _itkGrayscaleGeodesicDilateImageFilterPython.itkGrayscaleGeodesicDilateImageFilterID3ID3_SetRunOneIteration(self, *args)
SetRunOneIteration(self, bool _arg)
625941ec7cff6e4e81117e98
def __setitem__(self, key, attributes): <NEW_LINE> <INDENT> if key in ['override_values']: <NEW_LINE> <INDENT> print('Can not assign {} directly, use .append()'.format(key)) <NEW_LINE> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ForemanItem.__setitem__(self, key, attributes)
Function __setitem__ Set a parameter of a foreman object as a dict @param key: The key to modify @param attribute: The data @return RETURN: The API result
625941ec4d74a7450ccd46d7
def query_all(self): <NEW_LINE> <INDENT> cursor = self.conn.cursor() <NEW_LINE> cursor.execute('SELECT * FROM files') <NEW_LINE> self.logger.debug('queried all record') <NEW_LINE> return list(cursor)
Query all records from database. Returns: list of tuple: The required records.
625941ec507cdc57c63071f9
def formatrevnode(ui, rev, node): <NEW_LINE> <INDENT> return '%s' % node
Format given revision and node depending on the current verbosity
625941ece64d504609d74d52
def advance(dt): <NEW_LINE> <INDENT> local_BODIES = BODIES <NEW_LINE> seenit = [] <NEW_LINE> for body1 in local_BODIES.keys(): <NEW_LINE> <INDENT> for body2 in local_BODIES.keys(): <NEW_LINE> <INDENT> if (body1 != body2) and not (body2 in seenit): <NEW_LINE> <INDENT> ([x1, y1, z1], v1, m1) = local_BODIES[body1] <NEW_LI...
advance the system one timestep
625941ec3eb6a72ae02ec9fe
def add_component(self, component): <NEW_LINE> <INDENT> assert component.keyspace == self.keyspace <NEW_LINE> self.components.setdefault(component.cf, []).append(component) <NEW_LINE> return component
Add the ``component`` to the list of components in this manifest.
625941ec3617ad0b5ed68409
def init_mechanism(): <NEW_LINE> <INDENT> helper_data = [] <NEW_LINE> n = int(input("Enter reponse len : ")) <NEW_LINE> F = GF(2)**n <NEW_LINE> PUF = channels.QarySymmetricChannel(F, 0.1) <NEW_LINE> res = PUF(create_random_response(n)) <NEW_LINE> print(f"PUF reponse : {res}") <NEW_LINE> t = int(input("Enter desired err...
Initiating The mechanism :ret: returning tuple containing (PUF, helper_data, H, res)
625941ecd99f1b3c44c67a98
def _check_error(self, failure, name): <NEW_LINE> <INDENT> self._healthy = False <NEW_LINE> log.err(failure, name) <NEW_LINE> cause = self._health_checks[name] = {"status": "NOT OK"} <NEW_LINE> if failure.check(InternalServerError): <NEW_LINE> <INDENT> cause["error"] = "Server error" <NEW_LINE> <DEDENT> elif failure.ch...
Returns an error, and why
625941ec7c178a314d6ef97a
def prepare_data(self, element, n_closest=20): <NEW_LINE> <INDENT> _X = [] <NEW_LINE> _y = [] <NEW_LINE> for id, mol in self.mols.items(): <NEW_LINE> <INDENT> frameview = mol.element_distances(element) <NEW_LINE> for atomlabel, centering in frameview.items(): <NEW_LINE> <INDENT> _y.append(mol.coordination_num(atomlabel...
Uses self.mols to create a training set of input samples (self.X) and target values (self.y). element: The given element to consider. n_closest: the number of closest atoms considered in each sample. self.X: array-like, shape = [n_samples, n_features] A dict of Mol.relative_distances dataframes is extracted fro...
625941ec435de62698dfe15f
def findPlayers(self, n): <NEW_LINE> <INDENT> recruits = list() <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> newFace = Player() <NEW_LINE> newType = randint(0, len(self._playerTypes) - 1) <NEW_LINE> newFace.setStrat(newType, self._playerTypes[newType]) <NEW_LINE> recruits.append(newFace) <NEW_LINE> <DEDENT> return...
Finding several players in one go
625941ec5166f23b2e1a566c
def singleton_sublime(cls): <NEW_LINE> <INDENT> instance = cls() <NEW_LINE> instance.__call__ = lambda: instance <NEW_LINE> return instance
After decoration, the cls is no longer a class, but a callable instance that every time we call it like instance() will return the unique created instance itself So it means the instance has been created whiling decorating :param cls: :return:
625941ec377c676e912726b9