code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def find_permanent_position(self): <NEW_LINE> <INDENT> while 1: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> return False
Find a permanent position :return:
625941f6167d2b6e312191f6
def showplot(**kwargs): <NEW_LINE> <INDENT> interactive = kwargs.get('interactive') <NEW_LINE> if interactive is not None: <NEW_LINE> <INDENT> matplotlib.interactive(interactive) <NEW_LINE> <DEDENT> print("Showing plot...") <NEW_LINE> pyplot.show() <NEW_LINE> if interactive: <NEW_LINE> <INDENT> import code <NEW_LINE> c...
Show the plot.
625941f6b57a9660fec33eef
def create_platform_version(PlatformName=None, PlatformVersion=None, PlatformDefinitionBundle=None, EnvironmentName=None, OptionSettings=None): <NEW_LINE> <INDENT> pass
Create a new version of your custom platform. See also: AWS API Documentation :example: response = client.create_platform_version( PlatformName='string', PlatformVersion='string', PlatformDefinitionBundle={ 'S3Bucket': 'string', 'S3Key': 'string' }, EnvironmentName='string', Op...
625941f6d53ae8145f87a8c4
def parse_packet(self, packet): <NEW_LINE> <INDENT> reading = self.split_packet(packet) <NEW_LINE> if reading.crc != self.calc_CRC(reading.stripped): <NEW_LINE> <INDENT> self.sensor.close() <NEW_LINE> raise IOError('Data not transmistted correctly,' 'CRC doesn\'t match packet') <NEW_LINE> <DEDENT> reading_info = self.p...
Convert Packet from binary to data dict
625941f65fdd1c0f98dc0898
def __delattr__(self, name): <NEW_LINE> <INDENT> raise AttributeError
No deletions of existing parameters.
625941f6dd821e528d63b805
def EndAMF3Array(self): <NEW_LINE> <INDENT> return super(IAMFWriter, self).EndAMF3Array()
Method IAMFWriter.EndAMF3Array
625941f676d4e153a657f194
@login_required <NEW_LINE> def gentityaltcode_delete(request, gentityaltcode_id): <NEW_LINE> <INDENT> galtcode = get_object_or_404(GentityAltCode, id=gentityaltcode_id) <NEW_LINE> related_station = galtcode.related_station <NEW_LINE> if galtcode and related_station: <NEW_LINE> <INDENT> if request.user.has_row_perm(rela...
Delete existing gentityaltcode. Permissions are checked against the relative station that the gentityaltcode is part of.
625941f6507cdc57c630734d
def slots2node(self, cx, slots): <NEW_LINE> <INDENT> return_node = None <NEW_LINE> for node in nx.bfs_tree(cx.graph, cx): <NEW_LINE> <INDENT> if cx.getslots(node) == slots and type(node) != int: <NEW_LINE> <INDENT> return_node = node <NEW_LINE> <DEDENT> <DEDENT> return return_node
Get a CX node from a tuple of slots.
625941f68a349b6b435e87d4
def read_bitcoin_config(dbdir): <NEW_LINE> <INDENT> from ConfigParser import SafeConfigParser <NEW_LINE> class FakeSecHead(object): <NEW_LINE> <INDENT> def __init__(self, fp): <NEW_LINE> <INDENT> self.fp = fp <NEW_LINE> self.sechead = '[all]\n' <NEW_LINE> <DEDENT> def readline(self): <NEW_LINE> <INDENT> if self.sechead...
Read the daral.conf file from dbdir, returns dictionary of settings
625941f63c8af77a43ae3e0a
def create_movie_of_configuration(self): <NEW_LINE> <INDENT> trajectory = [] <NEW_LINE> for i in range(self.current_xi_grid.shape[0]): <NEW_LINE> <INDENT> conf = np.array([list(self.current_xi_grid[i,:])]) <NEW_LINE> function_arguments = pd.DataFrame(data=conf, columns=['camp_dx','camp_dy','camp_origin_height','alpha',...
Create 'movie.traj'.
625941f6566aa707497f4bc1
def hello(self, name="world"): <NEW_LINE> <INDENT> print("Hello,", name, "!")
Says hello
625941f6a8370b7717052eff
def player_drop_carrot(self): <NEW_LINE> <INDENT> if self.held_carrots > 0: <NEW_LINE> <INDENT> self.held_carrots -= 1 <NEW_LINE> x, y = self.player.grid_pixels <NEW_LINE> carrot = self.place_carrot(x, y) <NEW_LINE> carrot.player_placed = True
Place a carrot at the players position :return:
625941f691f36d47f21acb5c
def get_iface_index(self, ifname): <NEW_LINE> <INDENT> iface = self._get_iface_by_name(ifname) <NEW_LINE> if iface: <NEW_LINE> <INDENT> return iface.ifindex <NEW_LINE> <DEDENT> return None
Return the interface index for ifname
625941f64a966d76dd551679
def clean_tdnf_metadata(root: Path, always: bool) -> None: <NEW_LINE> <INDENT> paths = [ *root.glob("var/log/tdnf.*"), root / "var/cache/tdnf", ] <NEW_LINE> cond = always or not os.access(root / "usr/bin/tdnf", os.F_OK, follow_symlinks=False) <NEW_LINE> if not cond or not any(path.exists() for path in paths): <NEW_LINE...
Remove tdnf metadata if /bin/tdnf is not present in the image
625941f621a7993f00bc835f
def url(self, privacy=False, *args, **kwargs): <NEW_LINE> <INDENT> params = { 'image': 'yes' if self.include_image else 'no', } <NEW_LINE> params.update(self.url_parameters(privacy=privacy, *args, **kwargs)) <NEW_LINE> if self.channels: <NEW_LINE> <INDENT> params['channel'] = ','.join( [NotifyMattermost.quote(x, safe='...
Returns the URL built dynamically based on specified arguments.
625941f6796e427e537b0c2e
def main(self): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description='Maven PGP key processor') <NEW_LINE> parser.add_argument('-c', dest='config', default=None, help='JSON config file') <NEW_LINE> parser.add_argument('-s', dest='sqlite', default=None, help='SQlite DB') <NEW_LINE> parser.add_argument('--dat...
Main entry point :return:
625941f6a219f33f34628fc2
def build_singularity_image( name_of_docker_image: str, singularity_image_name: str, singularity_image_folder: PathType, ) -> PathType: <NEW_LINE> <INDENT> if isinstance(singularity_image_folder, Path): <NEW_LINE> <INDENT> singularity_image_folder = str(singularity_image_folder) <NEW_LINE> <DEDENT> singularity_image_pa...
This function builds a singularity image from a dockerhub image using singularity pull. The resulting .sif is stored in <singularity_image_folder> and the filepath is returned.
625941f6187af65679ca5783
def get_number(x, y, size, cached=True): <NEW_LINE> <INDENT> seq = get_radius_sequence_number(x, y, size) <NEW_LINE> pos = get_position_on_radius(x, y, size, seq) <NEW_LINE> if pos == 0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> return pos + get_previous_sequence_last_number(seq, size, cached)
:param x: position of number in row :param y: position of number in column :param size: diameter of spiral :return: number positioned on the specified coordinates of spiral Return example: 43 44 45 46 47 48 49 42 21 22 23 24 25 26 41 20 7 8 9 10 27 40 19 6 1 2 11 28 39 18 5 4 3 12 29 38 17 16 15 14 13 30 37 36...
625941f6b830903b967e9f65
def shape(self): <NEW_LINE> <INDENT> path = QtGui.QPainterPath(self.sourcePoint) <NEW_LINE> path.lineTo(self.destPoint) <NEW_LINE> stroker = QtGui.QPainterPathStroker() <NEW_LINE> stroker.setWidth(2) <NEW_LINE> stroked = stroker.createStroke(path) <NEW_LINE> stroked.addRect(self.destPoint.x()-10, self.destPoint.y()-10,...
The QT shape function.
625941f6d6c5a102081446b2
def leastsquares(x, y): <NEW_LINE> <INDENT> if len(x) != len(y): <NEW_LINE> <INDENT> raise ValueError('Point arrays must be equal length') <NEW_LINE> <DEDENT> numberOfPoints = len(x) <NEW_LINE> sumX = sum(x) <NEW_LINE> sumY = sum(y) <NEW_LINE> sumXYProduct = sum(x[i] * y[i] for i in range(numberOfPoints)) <NEW_LINE> su...
Example implementation of the Least Squares method for calculating a best-fit line through a set of points. Linear least squares Args: x: array of floats representing x values for each point y: array of floats representing y values for each point Returns: (float, float): representing the y-intercept and s...
625941f626068e7796caf34b
def get_success_url(self): <NEW_LINE> <INDENT> messages.add_message( self.request, messages.SUCCESS, _("Successful creation")) <NEW_LINE> if 'save-and-add' in self.request.POST: <NEW_LINE> <INDENT> return reverse('invoice-list') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return reverse('invoice-edit', args=[self.obj...
.
625941f6283ffb24f3c55f5c
def __str__(self): <NEW_LINE> <INDENT> return self._str
Return str representation of encapsulated model.
625941f692d797404e3047ef
def _parse_topology(top, **kwargs): <NEW_LINE> <INDENT> if isinstance(top, (string_types, os.PathLike)): <NEW_LINE> <INDENT> ext = _get_extension(top) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ext = None <NEW_LINE> <DEDENT> if isinstance(top, Topology): <NEW_LINE> <INDENT> topology = top <NEW_LINE> <DEDENT> elif is...
Get the topology from a argument of indeterminate type If top is a string, we try loading a pdb, if its a trajectory we extract its topology. Returns ------- topology : md.Topology
625941f6b5575c28eb68e669
def test_split_line(self): <NEW_LINE> <INDENT> text = " 1 2 3 4 5 6 7 8 9 0 " <NEW_LINE> for size, prefix, expect in ( (3, 0, ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]), (3, 3, ["2", "3", "4", "5", "6", "7", "8", "9", "0"]), (4, 0, ["1", "2 3", "4", "5", "6 7", "8", "9", "0"]), (2, 7, ["3", "4", "",...
Tests splitting and stripping elements on a non-delineated line
625941f626068e7796caf34c
def train(self): <NEW_LINE> <INDENT> for a in range(self.actionNum): <NEW_LINE> <INDENT> self.fas[a].train()
train individual models for each actions seperately.
625941f68e05c05ec3eea9dd
def array_filter(_filter: FilterT) -> FilterT: <NEW_LINE> <INDENT> @wraps(_filter) <NEW_LINE> def wrapper(val: object, *args: Any, **kwargs: Any) -> Any: <NEW_LINE> <INDENT> if not isinstance(val, (list, tuple, Undefined, range)): <NEW_LINE> <INDENT> raise FilterValueError(f"expected an array, found {type(val).__name__...
A filter function decorator that raises a FilterValueError if the filter value is not array-like.
625941f6091ae356686675b5
def calculate_crc8(value: str) -> int: <NEW_LINE> <INDENT> crc = 0 <NEW_LINE> for c in bytearray(value.encode("ASCII")): <NEW_LINE> <INDENT> for i in range(8, 0, -1): <NEW_LINE> <INDENT> t = c ^ crc <NEW_LINE> crc >>= 1 <NEW_LINE> if (t & 0x01) != 0: <NEW_LINE> <INDENT> crc ^= 0x8C <NEW_LINE> <DEDENT> c >>= 1 <NEW_LINE...
Calculate the CRC8 of a string representation of an int
625941f610dbd63aa1bd3204
def load_devices_online_status(self, general_devices): <NEW_LINE> <INDENT> last_online_table = Table(cfg.LAST_ONLINE_TABLE, self.metadata, autoload=True) <NEW_LINE> for device_column in last_online_table.columns: <NEW_LINE> <INDENT> device_name = device_column.name <NEW_LINE> if device_name in general_devices.keys(): <...
Set values of General devices according to table last_online.
625941f685dfad0860c3b4c0
def dash_create(dash_name): <NEW_LINE> <INDENT> defaults = dashconf["defaults"] <NEW_LINE> today = date.today().strftime("%FT%T") <NEW_LINE> log.info("Dashboard: %s" % dash_name) <NEW_LINE> dash = {"name": dash_name, "defaultGraphParams": { "width": defaults["width"], "height": defaults["height"], "from": "-%s%s" % (de...
Create dashboard for specified host and dashboard profile.
625941f656ac1b37e6264824
def encode_labels(self, sent_str_list, word_to_ix): <NEW_LINE> <INDENT> num_sents = len(sent_str_list) <NEW_LINE> max_len = max([len(sent_str.split()) for sent_str in sent_str_list]) <NEW_LINE> L = np.zeros((num_sents, max_len), dtype=np.int32) <NEW_LINE> for i, sent_str in enumerate(sent_str_list): <NEW_LINE> <INDENT>...
Arguments: - sent_str_list: list of n sents in string format return: - labels: int32 (n, sent_length)
625941f6460517430c3947d5
def IsInModulo(timestep, frequencyArray): <NEW_LINE> <INDENT> for frequency in frequencyArray: <NEW_LINE> <INDENT> if frequency > 0 and (timestep % frequency == 0): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
Return True if the given timestep is in one of the provided frequency. This can be interpreted as follow:: isFM = IsInModulo(timestep, [2,3,7]) is similar to:: isFM = (timestep % 2 == 0) or (timestep % 3 == 0) or (timestep % 7 == 0)
625941f6a8ecb033257d372d
def code_verificate(name, passwd, file_name, code_type=1005, app_id=3510, app_key='7281f8452aa559cdad6673684aa8f575', time_out=60): <NEW_LINE> <INDENT> yundama_obj = YDMHttp(name, passwd, app_id, app_key) <NEW_LINE> cur_uid = yundama_obj.login() <NEW_LINE> print('uid: %s' % cur_uid) <NEW_LINE> rest = yundama_obj.balanc...
:param name: 云打码注册用户名,这是普通用户注册,而非开发者用户注册名 :param passwd: 用户密码 :param file_name: 需要识别的图片名 :param app_id: 软件ID,这里默认是填的我的,如果需要,可以自行注册一个开发者账号,填自己的。 软件开发者会有少额提成,希望大家支持weibospider的发展(提成的20%会给celery项目以支持其发展) :param app_key: 软件key,这里默认是填的我的,如果需要,可以自行注册一个开发者账号,填自己的 :param code_type: 1005表示五位字符验证码。价格和验证码类别,详细请看http://www.yundama...
625941f63317a56b8693a2aa
def start(self): <NEW_LINE> <INDENT> pass
If this is overridden, it is called during the CPU boot-up sequence to initialize the actual device.
625941f62c8b7c6e89b35e1e
def convert_values(self, value, field): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if field and field.get_internal_type() == 'DateTimeField': <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> elif field and field.get_internal_type() == 'DateField' and isinstance(value, ...
Coerce the value returned by the database backend into a consistent type that is compatible with the field type. In our case, cater for the fact that SQL Server < 2008 has no separate Date and Time data types. TODO: See how we'll handle this for SQL Server >= 2008
625941f6d58c6744b42582bf
def __str__(self): <NEW_LINE> <INDENT> return '[Rectangle] ({}) {}/{} - {}/{}'.format(self.id, self.x, self.y, self.width, self.height)
printable string of rectangle
625941f6a4f1c619b28b068b
def theano_poly(X, Y=None, degree=3, coef0=1, gamma=1): <NEW_LINE> <INDENT> if Y is None: <NEW_LINE> <INDENT> Y = X <NEW_LINE> <DEDENT> assert X.shape[1] == Y.shape[1], 'X and Y must be of same dimension' <NEW_LINE> x = T.matrix('x') <NEW_LINE> y = T.matrix('y') <NEW_LINE> x_dot_y = T.dot(x,y.T) <NEW_LINE> f = theano.f...
GPU implementation of polynomial kernel: K(x,y) = Sum[ (gamma*xi*yi + coef0)^degree ] i ---------------------------------------------------------------------- usage: K = theano_poly(X, [Y=None, degree=3, coef0=1, gamma=1]) input: X - numpy array 2D MxN array containi...
625941f6adb09d7d5db6cdee
def bar(self, subset=None, axis=0, color='#d65f5f', width=100, align='left', vmin=None, vmax=None): <NEW_LINE> <INDENT> if align not in ('left', 'zero', 'mid'): <NEW_LINE> <INDENT> raise ValueError("`align` must be one of {'left', 'zero',' mid'}") <NEW_LINE> <DEDENT> if not (is_list_like(color)): <NEW_LINE> <INDENT> co...
Draw bar chart in the cell backgrounds. Parameters ---------- subset : IndexSlice, optional A valid slice for `data` to limit the style application to. axis : int, str or None, default 0 Apply to each column (`axis=0` or `'index'`) or to each row (`axis=1` or `'columns'`) or to the entire DataFrame at ...
625941f676d4e153a657f195
def func_SendOtp(obj_model,obj_doc): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> otp="" <NEW_LINE> if "user_email" in obj_doc: <NEW_LINE> <INDENT> receiver_email = obj_doc["user_email"] <NEW_LINE> sender_email = "gk.411995@gmail.com" <NEW_LINE> password = "12wedfvbabc" <NEW_LINE> myQuery = {"user_email":receiv...
Purpose: validate and sends otps, handle both email and phone number. for phone number request:{ "user_id": "9818051081", "ip_add" : "user ip address" } for email request:{ "user_email": "gk.441@gmail.com", "ip_add" : "user ip address" }
625941f6fb3f5b602dac3cfd
def from_numpy(array): <NEW_LINE> <INDENT> df = pd.DataFrame( array, index=[i for i in range(array.shape[0])], columns=[chr(i + 65) for i in range(array.shape[1])] ) <NEW_LINE> return df
Creates a Dataframe from a np.ndarray array: The np.ndarray to create the dataframe from Returns: the created Dataframe
625941f676e4537e8c351cdb
def create(self, validated_data): <NEW_LINE> <INDENT> user_data = validated_data.pop('user') <NEW_LINE> user = User.objects.create(**user_data) <NEW_LINE> user.set_password(user_data.pop('password')) <NEW_LINE> user.tag = "user" <NEW_LINE> user.save() <NEW_LINE> userprofile = UserProfile.objects.create(user=user, **val...
覆写create() 创建UserProfile实例的同时创建User实例,并给User实例设置密码和增加相应权限
625941f638b623060ff0b44f
def __init__(self, restart=None, ignore_bad_restart_file=False, label='espresso', atoms=None, **kwargs): <NEW_LINE> <INDENT> FileIOCalculator.__init__(self, restart, ignore_bad_restart_file, label, atoms, **kwargs) <NEW_LINE> self.calc = None
All options for pw.x are copied verbatim to the input file, and put into the correct section. Use ``input_data`` for parameters that are already in a dict, all other ``kwargs`` are passed as parameters. Accepts all the options for pw.x as given in the QE docs, plus some additional options: input_data: dict A flat...
625941f696565a6dacc8fd2b
def write_frame(self, frame, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError('Method not implemented')
Write a frame into the trajectory file opened by the handler. The handler should be initialized in mode 'w' or 'a'. Parameters ---------- frame : Frame kwargs : dict
625941f660cbc95b062c6ba6
def __changes_zero(self) -> None: <NEW_LINE> <INDENT> self.__number_of_changes = 0 <NEW_LINE> self.__current_changes = set()
Zeroing number of changes
625941f65f7d997b87175101
def get_valid_pos(self, my_color): <NEW_LINE> <INDENT> pos = 0 <NEW_LINE> emp = self.__get_empty() <NEW_LINE> if my_color == self.BLACK: <NEW_LINE> <INDENT> my = self.black_board <NEW_LINE> opp = self.white_board <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> my = self.white_board <NEW_LINE> opp = self.black_board <NEW_...
根据棋子颜色获得该棋子所能下棋的位置 :param my_color: 我的棋子的颜色 :return valid_pos: 能够落子的位置
625941f61f5feb6acb0c51ac
def search_date_range(): <NEW_LINE> <INDENT> results = [] <NEW_LINE> os.system('cls' if os.name == 'nt' else 'clear') <NEW_LINE> start_date = input("Enter beginning date to search (DD/MM/YYYY): ") <NEW_LINE> end_date = input("Enter end date to search (DD/MM/YYYY): ") <NEW_LINE> try: <NEW_LINE> <INDENT> start_date_test ...
Searches for entries given date range. Returns a list of results
625941f6ec188e330fd5adf3
def train(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False): <NEW_LINE> <INDENT> X = [] <NEW_LINE> y = [] <NEW_LINE> for class_dir in os.listdir(train_dir): <NEW_LINE> <INDENT> if not os.path.isdir(os.path.join(train_dir, class_dir)): continue <NEW_LINE> for img_path in image_files...
Trains a k-nearest neighbors classifier for face recognition. :param train_dir: directory that contains a sub-directory for each known person, with its name. (View in source code to see train_dir example tree structure) Structure: <train_dir>/ ├── <person1>/ │ ├── <somename1>.jpeg │ ├── <somename...
625941f65fcc89381b1e1d28
def manage_offer(self, params): <NEW_LINE> <INDENT> results = self.get_offers(offer=params['offer']) <NEW_LINE> if results.status_code == 200 and params['force']: <NEW_LINE> <INDENT> return self.create_or_modify_offer(offer=params['offer'], data=params['offer_data'], modify=True) <NEW_LINE> <DEDENT> return self.create_...
handle creating or modifying offers
625941f6b545ff76a8914478
def within_between_subjects(self, distance_matrix, metadata, group): <NEW_LINE> <INDENT> within_groups = {} <NEW_LINE> between_groups = [] <NEW_LINE> metalabels = metadata[group].unique() <NEW_LINE> for label in metalabels: <NEW_LINE> <INDENT> label_index = metadata[group]==label <NEW_LINE> if distance_matrix.loc[label...
Compiles for comparison each within subject and between subjects. Parameters ------------ distance_matrix : pandas DataFrame, aithcison distance matrix generated from aitchison_distance_matrix method in EDA module. metadata : pandas DataFrame, the metadata for the sample highlighting...
625941f68c3a873295158a26
def get_least_cost_node(costs): <NEW_LINE> <INDENT> min_cost = float('inf') <NEW_LINE> cost_node = None <NEW_LINE> for node in costs: <NEW_LINE> <INDENT> cost = costs[node] <NEW_LINE> if cost < min_cost and node not in processd: <NEW_LINE> <INDENT> cost_node = node <NEW_LINE> min_cost = cost_node <NEW_LINE> <DEDENT> <D...
Возвращает узел с минимальной стоимостью из тех ухлов, которые еще не были в обработке.
625941f626238365f5f0f4da
def touch(self): <NEW_LINE> <INDENT> if not self.elasticsearch_client.indices.exists(index=self.marker_index): <NEW_LINE> <INDENT> self.elasticsearch_client.indices.create(index=self.marker_index) <NEW_LINE> <DEDENT> self.elasticsearch_client.index( index=self.marker_index, doc_type=self.marker_doc_type, id=self.marker...
Mark the task as having completed successfully.
625941f69b70327d1c4e143b
def pct_std_barplot(x, y, hue, data, ax=None, order=None): <NEW_LINE> <INDENT> sns.barplot(x=x, y=y, hue=hue, ax=ax, order=order, data = (data[[x, hue]] .reset_index(drop=True) .groupby([x])[hue] .value_counts(normalize=True) .rename('Percentage').mul(100) .reset_index() .sort_values(hue))) <NEW_LINE> plt.title("Percen...
Standardize by percentage using Pandas functions. Plot using Seaborn. Function arguments are extentions of Seaborns'.
625941f60a366e3fb873ee83
@cli.command('ce') <NEW_LINE> @click.pass_context <NEW_LINE> def cli_ce(ctx): <NEW_LINE> <INDENT> ctx.obj['run']( tokenizer=common.CHARACTER_TOKENIZER, evaluate=evaluate_entropy, )
Character Entropy Challenge.
625941f67b180e01f3dc4e51
def win_get_caret_size(): <NEW_LINE> <INDENT> point = _Point() <NEW_LINE> _audll.AU3_WinGetCaretPos(pointer(point)) <NEW_LINE> return point.x, point.y
Returns the coordinates of the caret in the foreground window. :return:
625941f692d797404e3047f0
def isPalindrome(self, x): <NEW_LINE> <INDENT> if x < 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if len(str(x)) == 1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> strNum = str(x) <NEW_LINE> half = int(len(strNum)/2) <NEW_LINE> for i in range(half): <NEW_LINE> <INDENT> if strNum[i] != strNum[len(strN...
:type x: int :rtype: bool
625941f691af0d3eaac9c081
def p_tyvar(p): <NEW_LINE> <INDENT> p[0] = "'" + p[2] <NEW_LINE> if debug: print(" TYVAR : ", p[0])
tyvar : "'" vid
625941f624f1403a926011c3
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, SegmentCollection): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict()
Returns true if both objects are equal
625941f6d486a94d0b98e7aa
def maxSubArray(self, nums): <NEW_LINE> <INDENT> global_max, local_max = nums[0], nums[0] <NEW_LINE> for x in xrange(1, len(nums)): <NEW_LINE> <INDENT> local_max = max(nums[x], local_max + nums[x]) <NEW_LINE> global_max = max(global_max, local_max) <NEW_LINE> <DEDENT> return global_max
:type nums: List[int] :rtype: int
625941f65510c4643540fa36
def etag (tag): <NEW_LINE> <INDENT> return "</%s>" % tag
Format ending tag. @param tag: tag name @type tag: string @return: formatted ending tag @rtype: string
625941f623e79379d52eebbe
def compute_distance_matrix(input1, input2, metric='euclidean'): <NEW_LINE> <INDENT> assert isinstance(input1, torch.Tensor) <NEW_LINE> assert isinstance(input2, torch.Tensor) <NEW_LINE> assert input1.dim() == 2, 'Expected 2-D tensor, but got {}-D'.format( input1.dim() ) <NEW_LINE> assert input2.dim() == 2, 'Expected 2...
A wrapper function for computing distance matrix. Args: input1 (torch.Tensor): 2-D feature matrix. input2 (torch.Tensor): 2-D feature matrix. metric (str, optional): "euclidean" or "cosine". Default is "euclidean". Returns: torch.Tensor: distance matrix. Examples:: >>> from torchreid impor...
625941f629b78933be1e5d07
def genSine(A, f, phi, fs, t): <NEW_LINE> <INDENT> y=np.array([]) <NEW_LINE> N= fs * t <NEW_LINE> y = A * np.cos( (2* np.pi*f* np.arange(N)/fs) + phi) <NEW_LINE> return (y)
Inputs: A (float) = amplitude of the sinusoid (1) f (float) = frequency of the sinusoid in Hz (10) phi (float) = initial phase of the sinusoid in radians (1) fs (float) = sampling frequency of the sinusoid in Hz (50) t (float) = duration of the sinusoid (is second) (.1) Output: The function sh...
625941f6046cf37aa974d3a4
def nx_graph(self, edges_df, minimum_edgeweight): <NEW_LINE> <INDENT> filtered = edges_df[edges_df["weight"] > minimum_edgeweight] <NEW_LINE> nx_graph = nx.from_pandas_edgelist(filtered, "nodeA", "nodeB", ["weight"]) <NEW_LINE> pos = nx.nx_agraph.graphviz_layout(nx_graph, prog = "neato") <NEW_LINE> nx.draw(nx_graph, po...
This function creates our networkx graph and saves it into "viz" Input: Our csv list of weighted edges with columns "nodeA", "nodeB" and "weight (edges_df) Output: A network graph saved in the viz directory
625941f6fb3f5b602dac3cfe
def favicon(request): <NEW_LINE> <INDENT> with open(join(dirname(dirname(__file__)), 'static', 'img', 'favicon', 'favicon.ico'), 'rb') as f: <NEW_LINE> <INDENT> return HttpResponse( f.read(), content_type='image/x-icon', )
favicon.ico must be served from the root for legacy reasons.
625941f6d4950a0f3b08c9a9
def _getMeanOnePoint(self,universe,selection1,selection_str,dt,totalFrames): <NEW_LINE> <INDENT> repInd = self._repeatedIndex(selection1,dt,totalFrames) <NEW_LINE> sumsdt = 0 <NEW_LINE> n = 0.0 <NEW_LINE> sumDeltaO = 0.0 <NEW_LINE> valOList = [] <NEW_LINE> for j in range(totalFrames/dt-1): <NEW_LINE> <INDENT> a = self....
This function get one point of the graphic C_OH vs t. It's uses the _getOneDeltaPoint() function to calculate the average.
625941f601c39578d7e7549f
def reportFac(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> textlistado = 'FACTURA' <NEW_LINE> var.rep = canvas.Canvas('informes/factura.pdf', pagesize=A4) <NEW_LINE> Printer.cabecera(self) <NEW_LINE> Printer.pie(textlistado) <NEW_LINE> codfac = var.ui.lblCodFac.text() <NEW_LINE> Printer.cabecerafac(codfac) <NEW_...
Modulo que llama a la BBDD captura datos de las facturas de un cliente ordenados alfabeticamente y los va mostrando en el informe. :return: None :rtype: None La variable i representa los valores del eje x. La variable j representa los valores del eje j. Los informes se guardan en la carpeta informe y al mismo tiempo ...
625941f6e1aae11d1e74a321
def __repr__(self): <NEW_LINE> <INDENT> return _format( "CIMQualifierDeclaration(" "name={s.name!A}, " "value={s.value!A}, " "type={s.type!A}, " "is_array={s.is_array!A}, " "array_size={s.array_size!A}, " "scopes={s.scopes!A}, " "tosubclass={s.tosubclass!A}, " "overridable={s.overridable!A}, " "translatable={s.translat...
Return a string representation of this CIM qualifier type, that is suitable for debugging. The scopes will be ordered by their names in the result.
625941f656b00c62f0f14cc1
def reach_end(t, state): <NEW_LINE> <INDENT> return state[0] - surface.x[-1]
Returns zero when the skier gets to the end of the approach length.
625941f663f4b57ef0001769
def get_input_files(self): <NEW_LINE> <INDENT> options = { "title": "Select file", } <NEW_LINE> selectors = tkfd.askopenfilenames(**options) <NEW_LINE> self.input_selectors = selectors <NEW_LINE> self.infile.delete(0, tk.END) <NEW_LINE> self.infile.insert(0, selectors) <NEW_LINE> return None
Pop up the 'open file' dialog, assign whatever's picked to the input file entry box, and set an attribute with an iterable of the file selectors.
625941f60a50d4780f6674fb
def __insertMany(self, sql, values): <NEW_LINE> <INDENT> count = self._cursor.executemany(sql, values) <NEW_LINE> return count
@summary: 向数据表插入多条记录 @param sql:要插入的SQL格式 @param values:要插入的记录数据tuple(tuple)/list[list] @return: count 受影响的行数
625941f630bbd722463cc42d
def unconv2d(x, output_dims, ksize, stride=1, norm=None, activation=None, name=None, reuse=False, use_bias=False, is_training=True, kernel_initializer=None, data_format=None): <NEW_LINE> <INDENT> input_shape = x.get_shape().as_list() <NEW_LINE> if not data_format or data_format == 'channel_last': <NEW_LINE> <INDENT> da...
:param x: 4D tensor, [batch_size, height, width, channels] :param output_dims: int, output_dims :param ksize: int, size of kernel :param stride: stride of kernel :param norm: string, use norm or not, and what kind of norm methods will be used :param activation: function, the activation function :param name: string, nam...
625941f6435de62698dfe2b1
def get_services(self): <NEW_LINE> <INDENT> raise NotImplementedError
Returns the list of available services :rtype: :class:`list` of :class:`str` :return: List of available services
625941f6e5267d203edce2f8
def add_micro_block(self, micro_block: MicroBlock) -> bool: <NEW_LINE> <INDENT> with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s: <NEW_LINE> <INDENT> s.connect(self.chainbase_address) <NEW_LINE> s.sendall(send_handler(MsgType.TYPE_MICRO_BLOCK_WRITE, micro_block.b)) <NEW_LINE> *_, msgtype, content = recv_pars...
add the micro_block to the chainbase :param micro_block: binary micro_block :return: True | False
625941f64c3428357757c987
def _plot_auc_dev(self, train_auc, val_auc, stop): <NEW_LINE> <INDENT> plt.plot(range(1, len(train_auc)+1), train_auc, color='#1f77b4', label='Training', ls='', marker='^') <NEW_LINE> plt.plot(range(1, len(val_auc)+1), val_auc, color='#ff7f0e', label='Validierung', ls='', marker='^') <NEW_LINE> plt.xlabel('Epoche') <NE...
Plot ROC-AUC-Score development
625941f6236d856c2ad44e48
def chebyshev(p1, p2): <NEW_LINE> <INDENT> return np.max(np.abs(np.asarray(p1) - np.asarray(p2)))
Computes the Chebyshev distance, between two n-dimensional points :param p1: first point :param p2: second point :return: Chebyshev distance value
625941f68c3a873295158a27
def p_addEndFunc(p): <NEW_LINE> <INDENT> global contCuadruplos <NEW_LINE> cuadruplos.append('endFunc') <NEW_LINE> contCuadruplos +=1
addEndFunc :
625941f6a17c0f6771cbe6b2
def find_nearestXYContour(self, X, Y): <NEW_LINE> <INDENT> if not self.Initialise: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.Target = self.Canvas.Drawer.Contours[0] <NEW_LINE> self.Target_X = numpy.asarray([self.Target.X[i][0] for i in range(0, len(self.Target.X))]) <NEW_LINE> self.Target_Y = numpy.asarray(self...
########################################################################################## This tries to find the closest X and Y of the a the first contour plots... Multiple contours are not supporte yet abd frankly don't make to much sense therefore we will simply grab contour [0] ####################################...
625941f6e8904600ed9f259c
def setConfig(self, field, value, local=True, die=True): <NEW_LINE> <INDENT> flags = "" <NEW_LINE> if not local: <NEW_LINE> <INDENT> flags += "--global " <NEW_LINE> <DEDENT> cmd = "cd %s; git config %s %s %s" % (self.BASEDIR, flags, field, value) <NEW_LINE> j.tools.executorLocal.execute(cmd, die=die)
Sets provided field with value to the git config :param field: field name to be set :param value: value of field to be set :param local: Set value as local config, set to false for global config :param die: raise exception on error
625941f667a9b606de4a8519
def _process_long_opt(option_parser, rargs, values, dests): <NEW_LINE> <INDENT> arg = rargs.pop(0) <NEW_LINE> if "=" in arg: <NEW_LINE> <INDENT> (opt, next_arg) = arg.split("=", 1) <NEW_LINE> rargs.insert(0, next_arg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> opt = arg <NEW_LINE> <DEDENT> opt = option_parser._match...
Mimic function of the same name in ``OptionParser``, capturing the arguments consumed in *arg_map*
625941f6442bda511e8bea72
def overlay_image(img, canvas=None, left=0, top=0): <NEW_LINE> <INDENT> if canvas is None: <NEW_LINE> <INDENT> canvas = QImage(img.size(), QImage.Format.Format_RGB32) <NEW_LINE> canvas.fill(Qt.GlobalColor.white) <NEW_LINE> <DEDENT> left, top = int(left), int(top) <NEW_LINE> imageops.overlay(img, canvas, left, top) <NEW...
Overlay the `img` onto the canvas at the specified position
625941f67d43ff24873a3309
def _update_feature_log_prob(self): <NEW_LINE> <INDENT> smoothed_fc = self.feature_count_ + self.alpha <NEW_LINE> smoothed_cc = self.class_count_ + self.alpha * 2 <NEW_LINE> self.feature_log_prob_ = (np.log(smoothed_fc) - np.log(smoothed_cc.reshape(-1, 1)))
Apply smoothing to raw counts and recompute log probabilities
625941f65166f23b2e1a57bd
def test_no_asset_names(self): <NEW_LINE> <INDENT> cla = CriticalLineAlgorithm() <NEW_LINE> cla.allocate(asset_prices=self.data) <NEW_LINE> weights = cla.weights.values[0] <NEW_LINE> assert (weights >= 0).all() <NEW_LINE> assert len(weights) == self.data.shape[1] <NEW_LINE> np.testing.assert_almost_equal(np.sum(weights...
Test CLA when not supplying a list of asset names.
625941f699fddb7c1c9de9f1
def get_model_name(cube, url): <NEW_LINE> <INDENT> url = parse_url(url) <NEW_LINE> try: <NEW_LINE> <INDENT> model_full_name = cube.attributes.get('title', url) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> model_full_name = url <NEW_LINE> <DEDENT> for mod_name, uri in titles.items(): <NEW_LINE> <INDENT...
Return a model short and long name from a cube. Examples -------- >>> import iris >>> import warnings >>> url = ('http://omgsrv1.meas.ncsu.edu:8080/thredds/dodsC/fmrc/sabgom/' ... 'SABGOM_Forecast_Model_Run_Collection_best.ncd') >>> with warnings.catch_warnings(): ... warnings.simplefilter("ignore") # Supp...
625941f6ab23a570cc2507ec
def build(self, visitor): <NEW_LINE> <INDENT> raise NotImplementedError
Build string expression, using the visitor to encode values
625941f6e1aae11d1e74a322
def run(self, circuits: Union[QasmQobj, QuantumCircuit, List[QuantumCircuit]], shots: Optional[int] = None, memory: Optional[bool] = None, **run_config: Dict[str, Any] ) -> QIJob: <NEW_LINE> <INDENT> run_config_dict = self._get_run_config( shots=shots, memory=memory, **run_config) <NEW_LINE> if isinstance(circuits, Qas...
Submits a quantum job to the Quantum Inspire platform. The execution is asynchronous, and a handle to a job instance is returned. :param circuits: An individual or a list of :class:`~qiskit.circuits.QuantumCircuit` objects to run on the backend. A :class:`~qiskit.qobj.QasmQobj` object is also supported but is...
625941f6377c676e9127280a
def test_import_tarball_bad_dirname(clean_dir, parse_and_run): <NEW_LINE> <INDENT> student_tarball = os.path.join(clean_dir, "jtd111.tar.gz") <NEW_LINE> init_and_build_roster(parse_and_run) <NEW_LINE> parse_and_run(["new", "a1"]) <NEW_LINE> temp = tempfile.mkdtemp() <NEW_LINE> with tarfile.open(student_tarball, "w:gz")...
Test importing a single tarball that contains a directory with a bad name
625941f666673b3332b926f5
def _compute_gls_weights(self): <NEW_LINE> <INDENT> errors = self.transformed_data - np.asarray(self.projection) <NEW_LINE> if self._ncomp == self._nvar: <NEW_LINE> <INDENT> raise ValueError('gls can only be used when ncomp < nvar ' 'so that residuals have non-zero variance') <NEW_LINE> <DEDENT> var = (errors ** 2.0).m...
Computes GLS weights based on percentage of data fit
625941f68e05c05ec3eea9de
def memoize_to_disk_and_cache(fcn): <NEW_LINE> <INDENT> return memoize_to_disk(fcn, local_cache=True)
Memoize to disk AND keep a local cache (as you would with the @memoize decorator).
625941f6d53ae8145f87a8c6
def test_valid_location(self): <NEW_LINE> <INDENT> loc = generate_location() <NEW_LINE> url = reverse('mapquiz:location', args=(loc.code,)) <NEW_LINE> client = Client() <NEW_LINE> response = client.get(url) <NEW_LINE> self.assertEqual(response.status_code, 200)
Can reach a valid location by uri code
625941f6099cdd3c635f12bb
def get_values_from_oids(self, oids): <NEW_LINE> <INDENT> snmp = SNMP(host=self) <NEW_LINE> return snmp.get_values(oids)
Get the requested values from OIDs list
625941f64d74a7450ccd482a
def sample_company(self): <NEW_LINE> <INDENT> payload = { "company_name": fake.name() } <NEW_LINE> res = self.client.post(COMPANY_URL, payload) <NEW_LINE> return Company.objects.get(id=res.data['id'])
Create and return a sample company
625941f6507cdc57c630734f
def _TestCase3(iTolerance): <NEW_LINE> <INDENT> tStart = rxcs.console.module_progress('LNA test (case 3) SNR') <NEW_LINE> mSig = np.random.randn(1e3, 1e3) <NEW_LINE> vCoef = np.array([3, 1, 0.01, 10]) <NEW_LINE> mExp = 3 * mSig + mSig**2 + 0.01*mSig**3 + 10*mSig**4 <NEW_LINE> _checkLNA(mSig, vCoef, mExp, iTolerance) <N...
This is test case function #3. |br| Args: iTolerance: maximum tolerance of a difference between an expected value and a real value Returns: Nothing
625941f69c8ee82313fbbddc
def test_curly_wrapper_raw_strings(self): <NEW_LINE> <INDENT> self.assertEqual(r"\$%{()}", PrepHandeCcmcFciqmc._curly_wrapper(r"\$%", "()"))
Test PrepHandeCcmcFciqmc._curly_wrapper, pass raw str.
625941f65e10d32532c5f588
def extend_django_sqlite(): <NEW_LINE> <INDENT> def float_max(value_x, value_y): <NEW_LINE> <INDENT> return float(max(float(value_x), float(value_y))) <NEW_LINE> <DEDENT> def json_contains(column_value, value): <NEW_LINE> <INDENT> return json.loads(value) in json.loads(column_value) <NEW_LINE> <DEDENT> def json_extract...
给 django sqlite 补上一些基础函数
625941f68e7ae83300e4b633
def __init__(self, peer, data, file, random_id=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.result = None <NEW_LINE> self.content_related = True <NEW_LINE> self.peer = peer <NEW_LINE> self.random_id = random_id if random_id is not None else int.from_bytes(os.urandom(8), 'big', signed=True) <NEW_LINE> s...
:param InputEncryptedChat peer: :param int random_id: :param bytes data: :param InputEncryptedFile file: :returns messages.SentEncryptedMessage: Instance of either SentEncryptedMessage, SentEncryptedFile.
625941f6f7d966606f6aa670
def desc_database(self, db_name): <NEW_LINE> <INDENT> hive_sql = "set hive.cli.print.header=true;desc database %s;" % ( db_name) <NEW_LINE> _logger.debug("executed hive sql:%s" % (hive_sql)) <NEW_LINE> cr = self.execute(sql=hive_sql) <NEW_LINE> if cr.status == 0: <NEW_LINE> <INDENT> return self._parse_database(cr.stdou...
substitute for `desc database`
625941f6d18da76e23532b43
def get_max_syllables(self): <NEW_LINE> <INDENT> max_syllables = self.all_syllables_ipa <NEW_LINE> for ipa_syllable in max_syllables: <NEW_LINE> <INDENT> orth_syllables = max_syllables[ipa_syllable] <NEW_LINE> max_orth_syllable = max(orth_syllables, key=orth_syllables.get) <NEW_LINE> self.all_syllables_ipa[ipa_syllable...
Args: Self all_syllables_ipa : output of get_all_syllables() Returns: Dictionary of all the phonetical syllables found in the word collection of a specific language. The values are the orthographical syllabe with maximum occurences for each phonetical syllable.
625941f6566aa707497f4bc3
def ensure_autocrypt_uid(keyinfo, ac_uid): <NEW_LINE> <INDENT> if keyinfo.is_subkey: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> found = 0 <NEW_LINE> for uid in keyinfo.uids: <NEW_LINE> <INDENT> if uid.email == ac_uid.email: <NEW_LINE> <INDENT> uid.comment = uid.comment + '(Autocrypt)' <NEW_LINE> found += 1 <NEW_LIN...
Ensure we include the email from the Autocrypt header in a UID.
625941f6fff4ab517eb2faa5
def rerun_pyomo_model(model_data, backend_model, opt): <NEW_LINE> <INDENT> backend_model.__calliope_run_config = calliope.AttrDict.from_yaml_string( model_data.attrs["run_config"] ) <NEW_LINE> timings = {} <NEW_LINE> log_time(logger, timings, "model_creation") <NEW_LINE> inputs = access_pyomo_model_inputs(backend_model...
Rerun the Pyomo backend, perhaps after updating a parameter value, (de)activating a constraint/objective or updating run options in the model model_data object (e.g. `run.solver`). Returns ------- new_model : calliope.Model New calliope model, including both inputs and results, but no backend interface.
625941f6711fe17d825429c0
def main(args=None): <NEW_LINE> <INDENT> args = parse(args or sys.argv[1:]) <NEW_LINE> model, state = load_model(args, verbose=True) <NEW_LINE> if model: model.share_memory() <NEW_LINE> world = torch.cuda.device_count() <NEW_LINE> if args.command == 'export' or world <= 1: <NEW_LINE> <INDENT> worker(0, args, 1, model, ...
Entry point for the retinanet command
625941f6bd1bec0571d90c93
def test_fromSeq(self): <NEW_LINE> <INDENT> f = self.ClassToTest() <NEW_LINE> self.assertEqual(f.fromSeq('aaabbbaaa'), {'a':6,'b':3}) <NEW_LINE> self.assertEqual(f.fromSeq('aab', sub), {'a':4,'b':2}) <NEW_LINE> self.assertEqual(f.fromSeq('acc', weight=3.5), {'a':7.5,'b':2,'c':7})
Freqs fromSeq should add items from sequence, according to weight
625941f655399d3f05588d1d
def _cursor_can_select_row(self, row_number, cursor_ref): <NEW_LINE> <INDENT> for cur in self._get_all_cursors(): <NEW_LINE> <INDENT> if cur.row == row_number and cur != cursor_ref: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Returns True if the line at 'row_number' is free of any cursor other than cursor_ref
625941f630dc7b7665901fc3