code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def _create_test_db(self, verbosity, autoclobber, keepdb=False): <NEW_LINE> <INDENT> suffix = self.sql_table_creation_suffix() <NEW_LINE> test_database_name = self._get_test_db_name() <NEW_LINE> qn = self.connection.ops.quote_name <NEW_LINE> with self._nodb_connection.cursor() as cursor: <NEW_LINE> <INDENT> try: <NEW_L...
Internal implementation - create the test db tables.
625941cb29b78933be1e576c
def _get_args_from_model(self): <NEW_LINE> <INDENT> if not self.model or inspect.isclass(self.model): <NEW_LINE> <INDENT> raise TypeError(self.model) <NEW_LINE> <DEDENT> return tuple(self._get_column(col) for col in self.model.column_names())
Returns the values of all the columns for the model set on the instance. Replacing any ``None`` values with ``'NULL'``. :raises TypeError: If no model is set or the model is a ``class`` not an instance.
625941cb38b623060ff0aead
def test_world_info(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> node = None <NEW_LINE> roscomp.init("test_node") <NEW_LINE> node = CompatibleNode('test_node') <NEW_LINE> msg = node.wait_for_message( "/carla/world_info", CarlaWorldInfo, timeout=TIMEOUT, qos_profile=QoSProfile(depth=10, durability=DurabilityPolic...
Tests world_info
625941cb44b2445a33932156
def test_repeated_node_delete(self): <NEW_LINE> <INDENT> node_id = str(uuid.uuid4()) <NEW_LINE> for i in range(self.REPEAT_COUNT): <NEW_LINE> <INDENT> self.test_node_update_properties_by_id(node_id) <NEW_LINE> self.g.node_delete(node_id=node_id) <NEW_LINE> with self.g.session_scope(): <NEW_LINE> <INDENT> self.assertIs(...
Test repeated node deletion correctness
625941cb91f36d47f21ac5b2
def upd_clistmask(self): <NEW_LINE> <INDENT> for i, (row, col) in enumerate(self.clist): <NEW_LINE> <INDENT> item = self.tableWidget.item(row, col) <NEW_LINE> try: <NEW_LINE> <INDENT> if item.checkState() == 2: <NEW_LINE> <INDENT> self.clist.mask[i] = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.clist.mask[...
Update the cellslist mask according to the checked state of cells. Iterate over all entries in the (unmasked) cellslist, examine whether the corresponding cell is checked or unchecked in the GUI and set the clist mask entries accordingly. Parameters ---------- None Returns ------- void
625941cb26238365f5f0ef2d
def getGuessedWord(secretWord, lettersGuessed): <NEW_LINE> <INDENT> CurrentGuess = '' <NEW_LINE> for letter in secretWord: <NEW_LINE> <INDENT> if letter in lettersGuessed: <NEW_LINE> <INDENT> CurrentGuess = CurrentGuess + letter <NEW_LINE> <DEDENT> if letter not in lettersGuessed: <NEW_LINE> <INDENT> CurrentGuess = Cur...
secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far.
625941cbcb5e8a47e48b7b6b
def on_modified(self, event: FileSystemEvent): <NEW_LINE> <INDENT> src_path = event.src_path <NEW_LINE> src_path = self.debounce(src_path) <NEW_LINE> if src_path: <NEW_LINE> <INDENT> if self.log_level > 2: <NEW_LINE> <INDENT> logd(f"File {src_path} modified") <NEW_LINE> <DEDENT> md_files = self.get_md_files(src_path) <...
Event fired when a file is modified
625941cbcc40096d61595a10
def data(self, connection, data): <NEW_LINE> <INDENT> data = data[:100] <NEW_LINE> data = re.sub('[^\w\d\-\?,.!:;" ]', '', data) <NEW_LINE> data = data.strip() <NEW_LINE> if data: <NEW_LINE> <INDENT> self.on_read(connection, data)
Received data from a connection. Clean it up and pass it to application.
625941cb460517430c394246
def version(self) -> str: <NEW_LINE> <INDENT> cmd = [str(self.lxd_path), "version"] <NEW_LINE> try: <NEW_LINE> <INDENT> proc = subprocess.run(cmd, capture_output=True, check=True, text=True) <NEW_LINE> <DEDENT> except subprocess.CalledProcessError as error: <NEW_LINE> <INDENT> raise LXDError( "Failed to query LXD versi...
Query LXD version. The version is of the format: <major>.<minor>[.<micro>] Version examples: - 4.13 - 4.0.5 - 2.0.12 :returns: Version string.
625941cb45492302aab5e382
@view_config(route_name='images', request_method='GET', renderer='json') <NEW_LINE> def list_images(request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> conn = connect(request) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return Response('Backend not found', 404) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if con...
List images from each backend.
625941cb009cb60464c63472
def eval(self,prompt='>>> '): <NEW_LINE> <INDENT> output = input(prompt) <NEW_LINE> if output in self.options: <NEW_LINE> <INDENT> output = self.options[output]() <NEW_LINE> <DEDENT> return output
evalutates a string to see if it contains an option and returns either that option or the string
625941cbe64d504609d74900
def process(self, entry_meta_filename=None, entry_results1_filename=None, entry_results2_filename=None, entry_info_filename=None, meta_template=None): <NEW_LINE> <INDENT> error_log = [] <NEW_LINE> meta = None <NEW_LINE> results1 = None <NEW_LINE> results2 = None <NEW_LINE> if entry_meta_filename: <NEW_LINE> <INDENT> me...
Process submission entry and apply all check-ups Parameters ---------- entry_meta_filename : str, optional File path to the meta file Default value None entry_results1_filename : str, optional File path to system output file Default value None entry_results2_filename : str, optional File path to ...
625941cbcc40096d61595a11
def wrap_360(x): <NEW_LINE> <INDENT> x = np.where(x<0.,x+360.,x) <NEW_LINE> x = np.where(x>=360.,x-360.,x) <NEW_LINE> return(x)
Wrap an angle to between 0 and 360
625941cb3cc13d1c6d3c743a
def check_missing(): <NEW_LINE> <INDENT> config = LeapSettings() <NEW_LINE> alert_missing = config.get_alert_missing_scripts() <NEW_LINE> launcher = vpnlaunchers.get_platform_launcher() <NEW_LINE> missing_scripts = launcher.missing_updown_scripts <NEW_LINE> missing_other = launcher.missing_other_files <NEW_LINE> if ale...
Checks for the need of installing missing scripts, and raises a dialog to ask user for permission to do it.
625941cb16aa5153ce362538
def Train(x_train,y_train): <NEW_LINE> <INDENT> clf= svm.SVC(C=1,kernel='rbf',gamma=0.000001,decision_function_shape='ovo') <NEW_LINE> clf.fit(x_train,y_train.ravel()) <NEW_LINE> return clf
kernel='linear'时,为线性核,C越大分类效果越好,但有可能会过拟合(defaul C=1)。 kernel='rbf'时(default),为高斯核 gamma值越小,分类界面越连续;gamma值越大,分类界面越“散”,分类效果越好,但有可能会过拟合。 decision_function_shape='ovr'时,为one v rest,即一个类别与其他类别进行划分, decision_function_shape='ovo'时,为one v one,即将类别两两之间进行划分,用二分类的方法模拟多分类的结果。 :param x_train: 数据集 :param y_train: 分类标签 :re...
625941cb67a9b606de4a7f7a
def normal(self, size, avg=0.0, std=1.0, ndim=None, dtype=None, nstreams=None): <NEW_LINE> <INDENT> avg = as_tensor_variable(avg) <NEW_LINE> std = as_tensor_variable(std) <NEW_LINE> if dtype is None: <NEW_LINE> <INDENT> dtype = scal.upcast(config.floatX, avg.dtype, std.dtype) <NEW_LINE> <DEDENT> avg = cast(avg, dtype) ...
Parameters ---------- size Can be a list of integers or Theano variables (ex: the shape of another Theano Variable). dtype The output data type. If dtype is not specified, it will be inferred from the dtype of low and high, but will be at least as precise as floatX. nstreams Number of streams.
625941cb435de62698dfdd0c
def SingleImagefun(self, ax): <NEW_LINE> <INDENT> def inner_SingleImage_fun(): <NEW_LINE> <INDENT> def update_data(): <NEW_LINE> <INDENT> singledata = self.Cam.SingleImageData(self.infotextshow) <NEW_LINE> cax.set_data(singledata) <NEW_LINE> self.plotUp.canvas.draw() <NEW_LINE> self.plotUp.canvas.flush_events() <NEW_LI...
1) get each frame and plot it 2) auto-update the plot :param ax: plt.addsubplot(111) :return: auto-update the plot
625941cbb57a9660fec33943
def manage_setLocalRoles(self, userid, roles, REQUEST=None): <NEW_LINE> <INDENT> notify(NySetLocalRoleEvent(self, userid, roles)) <NEW_LINE> return super(NyRoleManager, self).manage_setLocalRoles(userid, roles, REQUEST)
Override Role.manage_setLocalRoles
625941cbcad5886f8bd27099
def Tasks(self): <NEW_LINE> <INDENT> return self._Request('tasks')
Lists a given bot's tasks within the specified date range.
625941cb56b00c62f0f14719
def refactor_labels(x, y, class_dict, model_is_binary=True, meta=None): <NEW_LINE> <INDENT> if ((x.dtype == np.float64) or (x.dtype == np.float32)): <NEW_LINE> <INDENT> raise Exception("img must be a uint for label refactoring") <NEW_LINE> <DEDENT> mask = x[:,:,0] == 0; <NEW_LINE> y[np.logical_and(np.logical_not(mask),...
Returns label array y which will be modified according to these rules: - if model_is_binary is True, any label with a value above that of 'no_road' will be converted to 'any_road' - pixels which are outside original image bounds are converted to 'no_img' Also returns mask, alogical array indicatng no_img pixels
625941cb56ac1b37e6264290
def registration_statuses(self): <NEW_LINE> <INDENT> values = [] <NEW_LINE> reg_meta = self.connection.Registration__c.describe() <NEW_LINE> for f in reg_meta['fields']: <NEW_LINE> <INDENT> if f['name'] == 'Status__c': <NEW_LINE> <INDENT> for v in f['picklistValues']: <NEW_LINE> <INDENT> if v['active']: <NEW_LINE> <IND...
Get the statuses of the registration.
625941cb9b70327d1c4e0e95
def setPrintFunction(self, *args): <NEW_LINE> <INDENT> return _yarp.IControlDebug_setPrintFunction(self, *args)
setPrintFunction(IControlDebug self, int (*)(char const *,...) f) -> bool
625941cb0fa83653e465707c
def search_data(file_path): <NEW_LINE> <INDENT> file_path = os.path.normpath(file_path) <NEW_LINE> if not os.path.exists(file_path): <NEW_LINE> <INDENT> raise IOError('The file path "{}" is not existed!'.format(file_path)) <NEW_LINE> <DEDENT> faces = {} <NEW_LINE> for dirpath, subdirs, filenames in os.walk(file_path): ...
get path for all images params file_path: directory of images returns faces: dict of image path, labels for keys, file path for values
625941cb498bea3a759b9b6f
def parse_resource(resource): <NEW_LINE> <INDENT> if resource: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if HAS_PRECIS_I18N: <NEW_LINE> <INDENT> return resource.encode('Nickname').decode('utf-8') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> from nbxmpp.stringprepare import resourceprep <NEW_LINE> return resourcepre...
Perform stringprep on resource and return it
625941cbc432627299f04d06
def __init__(self, port=502, address='', timeout_in_sec=1, databank=None): <NEW_LINE> <INDENT> super(TcpServer, self).__init__(databank if databank else Databank()) <NEW_LINE> self._sock = None <NEW_LINE> self._sa = (address, port) <NEW_LINE> self._timeout_in_sec = timeout_in_sec <NEW_LINE> self._sockets = []
Constructor: initializes the server settings
625941cb6fb2d068a760f15d
def snap_config(volname=None, mnode=None): <NEW_LINE> <INDENT> if mnode is None: <NEW_LINE> <INDENT> mnode = tc.servers[0] <NEW_LINE> <DEDENT> if volname is None: <NEW_LINE> <INDENT> volname = "" <NEW_LINE> <DEDENT> cmd = "gluster snapshot config %s" % volname <NEW_LINE> return tc.run(mnode, cmd)
Runs 'gluster snapshot config' on specific node Example: snap_config() Kwargs: volname (str): volume name mnode (str): Node on which cmd has to be executed. If None, defaults to nodes[0]. Returns: tuple: Tuple containing three elements (ret, out, err). The first element 'ret' is of ty...
625941cbfff4ab517eb2f4fc
def _xmrange_iter(iter_list, typ=list): <NEW_LINE> <INDENT> if len(iter_list) == 0: <NEW_LINE> <INDENT> yield typ() <NEW_LINE> return <NEW_LINE> <DEDENT> if any(not _is_finite(L) for L in iter_list): <NEW_LINE> <INDENT> for L in iter_list: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> n = _len(L) <NEW_LINE> <DEDENT> exc...
This implements the logic for :func:`mrange_iter` and :class:`xmrange_iter`. Note that with typ==list, we will be returning a new copy each iteration. This makes it OK to modified the returned list. This functionality is relied on in the polynomial iterators. Here's a doc-test to prove this:: sage: iter = sage.mi...
625941cb1f5feb6acb0c4c12
def general_preprocess_data(self, df, cfg): <NEW_LINE> <INDENT> df.sort_values(by=[cfg['ID_COL'],cfg['EVENT_DATE'], cfg['EVENT_ID']], ascending=[True, True, True], inplace=True) <NEW_LINE> df = self.clean_data(df,cfg) <NEW_LINE> df = self.flb_imputation(df, cfg) <NEW_LINE> df = self.remove_negative_tenure(df, cfg) <NEW...
Contains functions to preprocess data in Té Parameters: df (dataframe): raw dataframe cfg (dict): configuration dictionary Returns: df: preprocessed dataframe
625941cbdc8b845886cb55f5
def on_closing(event=None): <NEW_LINE> <INDENT> my_msg.set("quit") <NEW_LINE> send()
This function is to be called when the window is closed.
625941cb7cff6e4e81117a46
def metal(path): <NEW_LINE> <INDENT> import pandas as pd <NEW_LINE> path = os.path.expanduser(path) <NEW_LINE> filename = 'metal.csv' <NEW_LINE> if not os.path.exists(os.path.join(path, filename)): <NEW_LINE> <INDENT> url = 'http://dustintran.com/data/r/Ecdat/Metal.csv' <NEW_LINE> maybe_download_and_extract(path, url, ...
Production for SIC 33 a cross-section *number of observations* : 27 *observation* : regional *country* : United States A dataframe containing : va output labor labor input capital capital input Aigner, D., K. Lovell and P. Schmidt (1977) “Formulation and estimation of stochastic frontier production...
625941cb23e79379d52ee625
def run(self): <NEW_LINE> <INDENT> options = { 'endDate': ' '.join(self.arguments), 'filename': self.options.get('filename', ''), 'cd': self.options.get('countdown', ''), 'tr': self.options.get('tr', ''), 'output_folder': self.site.config['OUTPUT_FOLDER'], } <NEW_LINE> directory = os.path.join(options['output_folder'],...
Required by the Directive interface. Create docutils nodes
625941cb283ffb24f3c559c2
def plot_data(self,xparm,yparm, figname="auto", savefig=False, formatfn=None, **kwargs): <NEW_LINE> <INDENT> if "label" in kwargs.keys(): <NEW_LINE> <INDENT> label = kwargs["label"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> label = self.file <NEW_LINE> <DEDENT> signx, signy = 1,1 <NEW_LINE> if xparm in ["Load","Str...
Plots small punch data and optionally saves the figure formatfn allows passing a function with a collection of arguments to format the function before saving it args ==== xparm,yparm (str) parameter names if these are "Load","Stroke", or "Extens." the sign is reversed for clarity of plotting fignam...
625941cbfff4ab517eb2f4fd
def reverse(x): <NEW_LINE> <INDENT> sign = -1 if x < 0 else 1 <NEW_LINE> val_str = str(abs(x)) <NEW_LINE> rev_str = int(val_str[::-1])*sign <NEW_LINE> return rev_str
:type x: int :rtype: int
625941cb2c8b7c6e89b35881
def get_vector_gcd(v): <NEW_LINE> <INDENT> a = v[0] <NEW_LINE> for x in v[1:]: <NEW_LINE> <INDENT> a = gcd(a, x) <NEW_LINE> <DEDENT> return a
This function returns the single greatest common divisor of a linear vector. Input numbers must be integers.
625941cbf9cc0f698b1406bc
def set_3d(self): <NEW_LINE> <INDENT> width, height = self.get_size() <NEW_LINE> glEnable(GL_DEPTH_TEST) <NEW_LINE> viewport = self.get_viewport_size() <NEW_LINE> glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1])) <NEW_LINE> glMatrixMode(GL_PROJECTION) <NEW_LINE> glLoadIdentity() <NEW_LINE> gluPerspective(PLAYE...
Configure OpenGL to draw in 3d.
625941cb7b180e01f3dc48be
def test_refresh_job_result(self): <NEW_LINE> <INDENT> result = self.sim_job.result() <NEW_LINE> cached_result = copy.deepcopy(result.to_dict()) <NEW_LINE> self.assertTrue(cached_result) <NEW_LINE> result.results[0].header.name = 'modified_result' <NEW_LINE> self.assertNotEqual(cached_result, result.to_dict()) <NEW_LIN...
Test re-retrieving job result via refresh.
625941cb63d6d428bbe445b0
def test_add_user_duplicate_email(self): <NEW_LINE> <INDENT> add_user('test', 'test@test.com', 'test') <NEW_LINE> user = User.query.filter_by(email='test@test.com').first() <NEW_LINE> user.admin = True <NEW_LINE> db.session.commit() <NEW_LINE> with self.client: <NEW_LINE> <INDENT> resp_login = self.client.post( '/auth/...
Ensure error is thrown if the email already exists.
625941cb55399d3f05588774
def clear_current(self, record_type): <NEW_LINE> <INDENT> current_f = self._get_file(record_type, permanent=False) <NEW_LINE> with suppress(FileNotFoundError): <NEW_LINE> <INDENT> os.remove(current_f)
Clears the current record of the given type. Args: record_type (str): The record type, e.g. 'weather', 'environment', etc.
625941cbc4546d3d9de72af4
def get_backend(): <NEW_LINE> <INDENT> return sys.modules[__name__]
The backend is this module itself.
625941cb21bff66bcd684a14
def print_json(data, jpath, pretty=False, tab_size=4, f=sys.stdout): <NEW_LINE> <INDENT> check_color_caps(f) <NEW_LINE> def _apply_style(text, *args, **kwargs): <NEW_LINE> <INDENT> if pretty: <NEW_LINE> <INDENT> return colorize(text, *args, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return text <NEW_LINE> ...
Prints JSON in a fancy colorized maner.
625941cbb830903b967e99cc
def turn(self) -> None: <NEW_LINE> <INDENT> player = self.player1_name if self.game_round % 2 == 0 else self.player2_name <NEW_LINE> print(f"Your turn, {player}\n") <NEW_LINE> while not self.stop_rolling: <NEW_LINE> <INDENT> player_input = input(5 * " " + "ROLL or PASS? ") <NEW_LINE> if player_input.lower() ...
Start a turn for the player. Player would either roll or pass. If oinker, lose point and stop rolling. If piggyback, lose game. If pass, bank the points. If roll, call self.roll(). :return: None
625941cb8a43f66fc4b54126
def add_command_to_menu(self, menu): <NEW_LINE> <INDENT> parent_menu = menu <NEW_LINE> parts = self.name.split("/") <NEW_LINE> for item_label in parts[:-1]: <NEW_LINE> <INDENT> sub_menu = self._find_sub_menu_item(parent_menu, item_label) <NEW_LINE> if sub_menu: <NEW_LINE> <INDENT> parent_menu = sub_menu <NEW_LINE> <DED...
Adds an app command to the menu
625941cbd10714528d5ffda3
def binom_approx_norm_dist(n, p): <NEW_LINE> <INDENT> mean = n * p <NEW_LINE> var = n*p*(1-p) <NEW_LINE> return stats.norm(mean, np.sqrt(var))
Inputs: n - country's total number cases (minus last two weeks) p - country's frequency of deaths per cases Creates a normal distribution approximation from a binomial distribution Output: normal distribution
625941cba05bb46b383ec8e2
def number_of_forking_points(neurites, neurite_type=NeuriteType.all): <NEW_LINE> <INDENT> return map_neurons(n_forking_points, neurites, neurite_type)
number of forking points in a collection of neurites
625941cba79ad161976cc206
def isglobalelement (domains): <NEW_LINE> <INDENT> for domain in domains.split(","): <NEW_LINE> <INDENT> if domain and not domain.startswith("~"): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Check whether all domains are negations.
625941cb4f6381625f114afc
def vsim_get(self, country, period): <NEW_LINE> <INDENT> params = { 'country': country, 'period': period, **self.params } <NEW_LINE> response = self._get_api('vsimGet', params) <NEW_LINE> return response
Method for requesting VirtualSIM number Documentation: https://sms-reg.com/docs/APImethods.html?vsimGet :param country: str: country name (ru, ua, gb, bg, pl, hk) :param period: str: period of rent (3hours, day, week) :return: dict: json from API-response
625941cb15fb5d323cde0bd0
def set_model_cout_net(graph,p, start, n_clientsuppr, n_depsuppr, Entity): <NEW_LINE> <INDENT> p = int(p) <NEW_LINE> n_clientsuppr = int(n_clientsuppr) <NEW_LINE> n_depsuppr = int(n_depsuppr) <NEW_LINE> DEPOT_OBJ, CLIENTS_OBJ= SeparetEntityObjet(Entity) <NEW_LINE> DEPOT = ObtenirEntity(DEPOT_OBJ) <NEW_LINE> CLIENT = Ob...
Set the coût net problem's model.
625941cbf7d966606f6aa0c4
def set_address(self): <NEW_LINE> <INDENT> if self.has_non_empty_attribute("address"): <NEW_LINE> <INDENT> address = utils.remove_markup(self.address) <NEW_LINE> if utils.contains_digit(address): <NEW_LINE> <INDENT> placename = utils.remove_markup(self.municipality) <NEW_LINE> street_address = "{}, {}".format(address, ...
Set the street address. Only if the 'address' field contains a digit. Form the address as "$address, $municipality".
625941cbeab8aa0e5d26dc18
def show_about_dialog(self): <NEW_LINE> <INDENT> dialog = AboutDialog( iface=self.iface ) <NEW_LINE> dialog.show() <NEW_LINE> dialog.exec_()
Show the help dialog.
625941cb97e22403b379d05a
def get_reviewer_comments_count(self, reviewer): <NEW_LINE> <INDENT> return ProposalComment.objects.filter( proposal=self, deleted=False, private=True, commenter=reviewer, vote=False).count()
Number of private comments by a reviewer
625941cb66656f66f7cbc26b
def ha_reboot_test(self, nodes): <NEW_LINE> <INDENT> self.ha_start() <NEW_LINE> for node in nodes: <NEW_LINE> <INDENT> if not self.reboot(node): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> sleep(360); <NEW_LINE> if not self.ha_basic_test(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return s...
Test reboot of controller nodes instance crashes/restarted. Pass crietria: as defined by ha_basic_test
625941cbeab8aa0e5d26dc19
def __init__(self, house_wall, read_line, cross_rate, mutation_rate, distanch_apart, dna_size, pop_size): <NEW_LINE> <INDENT> self.house_wall = house_wall <NEW_LINE> self.read_line = read_line <NEW_LINE> self.minx = float(self.read_line.bounds.minx) <NEW_LINE> self.maxx = float(self.read_line.bounds.maxx) <NEW_LINE> se...
house_wall: 房屋线 read_line: 红线 cross_rate: 交叉率 mutation_rate:变异率 distanch_apart:每个房屋之间的间距 dna_size: 一个方案中房屋的栋数 pop_size:一个种群中包含多少个个体
625941cba4f1c619b28b00fb
def emo(str): <NEW_LINE> <INDENT> text_object = NRCLex(str) <NEW_LINE> return text_object.affect_frequencies
affect_frequencies returns a value between 0 and 1 for all emotions per word.
625941cb30c21e258bdfa55e
def pretty(string: str, colour: bool = True) -> str: <NEW_LINE> <INDENT> head, tail = string.rsplit(maxsplit=1) <NEW_LINE> space = ' ' * (9 - len(head)) <NEW_LINE> if colour: <NEW_LINE> <INDENT> return ''.join( [ typer.style(head, fg='green'), space, typer.style(tail, bold=True), ] ) <NEW_LINE> <DEDENT> else: <NEW_LINE...
Generate pretty output for :command:`ninja`’s non-verbose mode. Args: string: Text to prettify colour: Colourise output
625941cb656771135c3eb92f
def run(self, options): <NEW_LINE> <INDENT> print(Gstr_title) <NEW_LINE> print('Version: %s' % self.get_version()) <NEW_LINE> os.chdir('/neuro/users/lizeth.machado/Public') <NEW_LINE> ima=self.verification_image() <NEW_LINE> ima_mask=self.verification_image_mask() <NEW_LINE> self.verification_image_mask_traspond() <NEW...
Define the code to be run by this plugin app.
625941cb5166f23b2e1a521a
def first_triangle_by_factors(n): <NEW_LINE> <INDENT> triangle = 0 <NEW_LINE> for i in count(1): <NEW_LINE> <INDENT> triangle += i <NEW_LINE> if get_divisor_count(triangle) > n: <NEW_LINE> <INDENT> return triangle
>>> first_triangle_by_factors(5) 28
625941cb0383005118ecf6a4
def color_of_season(datein): <NEW_LINE> <INDENT> season = get_season(datein) <NEW_LINE> if season == 'winter': <NEW_LINE> <INDENT> outcolor = 'b' <NEW_LINE> <DEDENT> elif season == 'summer': <NEW_LINE> <INDENT> outcolor = 'r' <NEW_LINE> <DEDENT> elif season == 'spring': <NEW_LINE> <INDENT> outcolor = 'g' <NEW_LINE> <DE...
give a color for a given season
625941cb7d847024c06be37c
def is_comment_or_whitespace(self): <NEW_LINE> <INDENT> entry_text = self.get_raw_entry_text() <NEW_LINE> if not entry_text.strip() or entry_text.lstrip().startswith("#"): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Returns True if the crontab entry is a comment
625941cbad47b63b2c50a040
def test_positive_create_user_7(self): <NEW_LINE> <INDENT> self.fail(NOT_IMPLEMENTED)
@Feature: User - Positive Create @Test: Create User for all variations of Password @Steps: 1. Create User for all valid Password variation in [1] using valid Username, First Name, Surname, Email Address, Language, authorized by @Assert: User is created @Status: Manual
625941cb377c676e9127226a
def list(request, template="media/list.html"): <NEW_LINE> <INDENT> albums = Album.objects.all() <NEW_LINE> if not request.user.is_authenticated(): <NEW_LINE> <INDENT> albums = albums.filter(public=True) <NEW_LINE> <DEDENT> paginator = Paginator(albums, 10) <NEW_LINE> try: <NEW_LINE> <INDENT> page = int(request.GET.get(...
Main listing.
625941cb3317a56b86939d1a
def __init__(self): <NEW_LINE> <INDENT> self.Age = None <NEW_LINE> self.Bag = None <NEW_LINE> self.Gender = None <NEW_LINE> self.Orientation = None <NEW_LINE> self.UpperBodyCloth = None <NEW_LINE> self.LowerBodyCloth = None
:param Age: 返回年龄信息 :type Age: bool :param Bag: 返回随身挎包信息 :type Bag: bool :param Gender: 返回性别信息 :type Gender: bool :param Orientation: 返回朝向信息 :type Orientation: bool :param UpperBodyCloth: 返回上装信息 :type UpperBodyCloth: bool :param LowerBodyCloth: 返回下装信息 :type LowerBodyCloth: bool
625941cb8da39b475bd65034
def sort_best_primers(primer3_output, **kwargs): <NEW_LINE> <INDENT> size_filter = kwargs.get('size_filter', True) <NEW_LINE> deltag_filter = kwargs.get('deltag_filter', False) <NEW_LINE> excluded_sequences = kwargs.get('excluded_sequences', ('GAGTC', 'GACTC')) <NEW_LINE> target_primers = parse_primers(primer3_output) ...
filtering primers based on different parameters that we choose :param primer3_output: primers dict for targets :param size_filter: primers dict for targets :param deltag_filter: primers dict for targets :param best_size: primers dict for targets :param margin_size: primers dict for targets :param delta_min: primers dic...
625941cb4527f215b584c518
def set_rev_date(self, when): <NEW_LINE> <INDENT> dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked) <NEW_LINE> return _set_asn1_time(dt, when)
Set the revocation timestamp. :param bytes when: The timestamp of the revocation, as ASN.1 GENERALIZEDTIME. :return: ``None``
625941cbd4950a0f3b08c410
def apply_beam(self, beamtype, fwhm): <NEW_LINE> <INDENT> fwhm = np.deg2rad(fwhm) <NEW_LINE> sigmab = fwhm/sqrt(8.e0*log(2.e0)) <NEW_LINE> self.Bl = exp(-self.l*(self.l+1.e0)*sigmab*sigmab/2.e0) <NEW_LINE> self.beam = np.interp(self.modk, self.k, self.Bl) <NEW_LINE> self.beam[~np.isfinite(self.beam)] = 0.e0 <NEW_LINE> ...
Apply a beam function to map. Currently 'beamtype' is redundant and a Gaussian beam is always used. ****fwhm is in degrees****
625941cbcdde0d52a9e530f4
def test_peek(test_deque): <NEW_LINE> <INDENT> peek = test_deque[2].peek() <NEW_LINE> assert peek == test_deque[2]._container.head.data
Test peek method.
625941cbde87d2750b85fe54
def test_min_zero(): <NEW_LINE> <INDENT> mlp = MLP(input_space=VectorSpace(1), layers= [Maxout(layer_name="test_layer", num_units=1, num_pieces = 2, irange=.05, min_zero=True)]) <NEW_LINE> X = T.matrix() <NEW_LINE> output = mlp.fprop(X) <NEW_LINE> f = function([X], output, mode="DEBUG_MODE") <NEW_LINE> f(np.zeros((1, 1...
This test guards against a bug where the size of the zero buffer used with the min_zero flag was specified to have the wrong size. The bug only manifested when compiled with optimizations off, because the optimizations discard information about the size of the zero buffer.
625941cb711fe17d8254242e
def make_pwm(sites): <NEW_LINE> <INDENT> cell_fn = lambda x, y, z: math.log((float(x) + 1) / (float(y) + 1), 2) <NEW_LINE> return make_matrix(sites, cell_fn, PWM, normalize=True)
Make a position-weight matrix from sites, with scores that represent the log of the frequency of each base, normalized so that the minimum possible score is zero. >>> operator = make_pwm(['AA', 'TA', 'CA', 'GA']) >>> operator.calc_score('AA') 2.3219280948873622 >>> operator.calc_score('GT') 0.0
625941cb4f88993c3716c129
def freq(self, year, *queries:str): <NEW_LINE> <INDENT> denominator=10000 <NEW_LINE> df = pd.DataFrame(columns=list(queries)*2 + ['tokens']) <NEW_LINE> for month in range(1, 13): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> filename = f"{self.path}/tokenized/{year}-{month}.tsv" <NEW_LINE> token, count = 0, [0] * len(qu...
:*args: query words calculate word frequency from random tweet file print word frequency of each month and total count of the year
625941cbd4950a0f3b08c411
def assembler(self, assembler: osbuild.Assembler): <NEW_LINE> <INDENT> pass
Called when an assembler is being built
625941cbbaa26c4b54cb11e1
def get_default(self, vp=None): <NEW_LINE> <INDENT> if vp is None: <NEW_LINE> <INDENT> raise ValueError('Visual Property ID is required.') <NEW_LINE> <DEDENT> url = self.__url + 'defaults/' + vp <NEW_LINE> key_value_pair = requests.get(url).content <NEW_LINE> print(key_value_pair) <NEW_LINE> key2 = requests.get(url).js...
:param vp: :return :
625941cbd99f1b3c44c67650
def d2(S, K, t, r, sigma, q): <NEW_LINE> <INDENT> return d1(S, K, t, r, sigma, q) - sigma * numpy.sqrt(t)
Calculate the d2 component of the Black-Scholes-Merton PDE. :param S: underlying asset price :type S: float :param K: strike price :type K: float :param sigma: annualized standard deviation, or volatility :type sigma: float :param t: time to expiration in years :type t: float :param r: risk-free interest rate :type r:...
625941cb63f4b57ef00011dc
def test_valid_access(self): <NEW_LINE> <INDENT> self.login() <NEW_LINE> response = self.client.get(reverse(self.url_name, kwargs=self.get_kwargs()), follow=True) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> data = {"value": "yes"} <NEW_LINE> response = self.client.post( reverse(self.url_name, kwar...
Account1 should be able to delete Account1:Char1
625941cb507cdc57c6306d9b
def test_post(self, client): <NEW_LINE> <INDENT> valid = _get_category_json() <NEW_LINE> resp = client.post(self.RESOURCE_URL, json=valid) <NEW_LINE> assert resp.status_code == 201 <NEW_LINE> assert resp.headers["Location"].endswith(self.RESOURCE_URL + valid["name"] + "/") <NEW_LINE> resp = client.get(resp.headers["Loc...
Tests for AllCategories POST method
625941cbbe8e80087fb20d05
def IsRightSet(self): <NEW_LINE> <INDENT> return _itkGeometricalQuadEdgePython.itkGeometricalQuadEdgeULULBBT_IsRightSet(self)
IsRightSet(self) -> bool
625941cbb7558d58953c4fd6
def properties_of_interest(self, part_properties: Dict[str, Any]) -> Dict[str, Any]: <NEW_LINE> <INDENT> relevant_properties = [ "plugin", "source", "source-commit", "source-depth", "source-tag", "source-type", "source-branch", "source-subdir", "source-submodules", "override-pull", "stage-packages", "overlay-packages",...
Return relevant properties concerning this step. :param part_properties: A dictionary containing all part properties. :return: A dictionary containing properties of interest.
625941cb167d2b6e31218c57
def extract(self, sample_offset, nsamps, cut_missing=False): <NEW_LINE> <INDENT> delta = sample_offset - self.sample_offset <NEW_LINE> pad_left = pad_right = np.zeros((0,2),int) <NEW_LINE> if delta < 0 or sample_offset+nsamps > self.sample_offset+self.nsamps: <NEW_LINE> <INDENT> if not cut_missing: <NEW_LINE> <INDENT> ...
Extract a TODCuts from this one to match a particular range of indices. For example, if you loaded a TOD using tod = moby2.TOD.from_dirfile(filename, start=START, end=START+1000) Then to resize and re-index your cuts object you should call: tod_cuts = tod_cuts0.extract(tod.info.sample_index, tod.nsamps) N...
625941cb097d151d1a222f1b
def get_weight(self): <NEW_LINE> <INDENT> return self.root.get_weight()
获取这棵huffman树根节点的权重
625941cbd486a94d0b98e207
def upload_file(self, local_path, remote_path='A/', skip_checks=False): <NEW_LINE> <INDENT> local_path = os.path.abspath(local_path) <NEW_LINE> remote_path = util.to_camerapath(remote_path) <NEW_LINE> if os.path.isdir(local_path): <NEW_LINE> <INDENT> raise ValueError("`local_path` must be a file, not a directory.") <NE...
Upload a file to the device. :param local_paths: Path to a local file :type local_paths: str/unicode :param remote_path: Target path on the device :type remote_path: str/unicode :param skip_checks: Skip sanity checks on the device, required if a script is running on the de...
625941cb4c3428357757c3e9
def sample_gumbel(shape, eps=1e-20): <NEW_LINE> <INDENT> U = np.random.uniform(size=shape, low=0, high=1) <NEW_LINE> return -np.log(-np.log(U + eps) + eps)
Sample from Gumbel(0, 1)
625941cbec188e330fd5a861
def le(a, b): <NEW_LINE> <INDENT> return T.le(a, b)
a <= b
625941cb29b78933be1e576e
def _encryptThenSeal(self, buf, contentType): <NEW_LINE> <INDENT> seqNumBytes = self._writeState.getSeqNumBytes() <NEW_LINE> authData = seqNumBytes + bytearray([contentType, self.version[0], self.version[1], len(buf)//256, len(buf)%256]) <NEW_LINE> nonce = self._getNonce(self._writeState, seqNumBytes) <NEW_LINE> assert...
Encrypt with AEAD cipher
625941cb5f7d997b87174b59
def _check_redefined_slots( self, node: nodes.ClassDef, slots_node: nodes.NodeNG, slots_list: List[nodes.NodeNG], ) -> None: <NEW_LINE> <INDENT> slots_names: List[str] = [] <NEW_LINE> for slot in slots_list: <NEW_LINE> <INDENT> if isinstance(slot, nodes.Const): <NEW_LINE> <INDENT> slots_names.append(slot.value) <NEW_LI...
Check if `node` redefines a slot which is defined in an ancestor class.
625941cbb830903b967e99cd
def test_eq(self): <NEW_LINE> <INDENT> pr1 = PairedRegion(3,10,2) <NEW_LINE> pr2 = PairedRegion(3,10,2) <NEW_LINE> pr3 = PairedRegion(3,10,2, Id='A') <NEW_LINE> pr4 = PairedRegion(3,10,2, Id='A') <NEW_LINE> pr5 = PairedRegion(3,20,4, Id='A') <NEW_LINE> self.assertEqual(pr1==pr2, True) <NEW_LINE> self.assertEqual(pr3==p...
PairedRegion __eq__: should use pairs and IDs
625941cb3617ad0b5ed67fb9
def count_percentile(self): <NEW_LINE> <INDENT> num_pos_list = [] <NEW_LINE> for qid, relevance in self.relevance_dict.items(): <NEW_LINE> <INDENT> judged_docid_list = relevance.get_judged_docid_list() <NEW_LINE> rel_docid_list = [] <NEW_LINE> for i in range(len(judged_docid_list) - 1, 0, -1): <NEW_LINE> <INDENT> rel_d...
cut number of into percetiles, sample size of query that has more positive documents will be cut Returns:
625941cb7b25080760e3951b
def pushNotification(self, message): <NEW_LINE> <INDENT> url = "/service/push/notifications" <NEW_LINE> content = {'message': message} <NEW_LINE> return self.doHTTPRequest(url, json.dumps(content), 'POST')
Send a notification to the account of the user. :param message: the message that should be sent :type message: basestring :return: the result of the request
625941cb167d2b6e31218c58
def CRF_Map_opt(Img, popt): <NEW_LINE> <INDENT> w, h, c = Img.shape <NEW_LINE> output_Img = Img.copy() <NEW_LINE> output_Img = func(output_Img, *popt) <NEW_LINE> return output_Img
Optimized Version of CRF mapping function Transfer image x to irradiance L accroding to CRF function [Input] Img: Input np array [0,1] double I, B: CRF response lookup table [output] Irradiance L
625941cbdd821e528d63b26b
def get_storage_class(self): <NEW_LINE> <INDENT> response = self.connection.make_request('GET', self.name, query_args=STORAGE_CLASS_ARG) <NEW_LINE> body = response.read() <NEW_LINE> if response.status == 200: <NEW_LINE> <INDENT> rs = ResultSet(self) <NEW_LINE> h = handler.XmlHandler(rs, self) <NEW_LINE> xml.sax.parseSt...
Returns the StorageClass for the bucket. :rtype: str :return: The StorageClass for the bucket.
625941cbaad79263cf390b02
def __setup(self, mx): <NEW_LINE> <INDENT> self.required_lines = [(i // mx) + 1 for i in self.lens]
sets the required lines on screen to display the actual line in file for each line
625941cbb5575c28eb68e0c2
@click.command() <NEW_LINE> @click.argument('account-id') <NEW_LINE> @click.argument('queue-name') <NEW_LINE> @click.option('--datacenter', help="Datacenter, E.G.: dal05") <NEW_LINE> @click.option('--network', type=click.Choice(['public', 'private']), help="Network type") <NEW_LINE> @click.option('--visibility-interval...
Modify a queue.
625941cbac7a0e7691ed418f
def write(self): <NEW_LINE> <INDENT> pdf_writer = pyPdf.PdfFileWriter() <NEW_LINE> if self.front_matter is not None: <NEW_LINE> <INDENT> front_matter = pyPdf.PdfFileReader(file(self.front_matter, "rb")) <NEW_LINE> for page in range(front_matter.getNumPages()): <NEW_LINE> <INDENT> pdf_writer.addPage(front_matter.getPage...
Assembles the final PDF and writes to disk.
625941cba8370b7717052962
def apply_metadata(df: DataFrame, metadata: Union[Metadata, dict, pyreadstat.metadata_container], as_category: bool = True): <NEW_LINE> <INDENT> if not checkers.is_type(df, 'DataFrame'): <NEW_LINE> <INDENT> raise ValueError(f'df must be a pandas.DataFrame. Was: {df.__class__.__name__}') <NEW_LINE> <DEDENT> if not check...
Updates the :class:`DataFrame <pandas:DataFrame>` ``df`` based on the ``metadata``. :param df: The :class:`DataFrame <pandas:pandas.DataFrame>` to update. :type df: :class:`pandas.DataFrame <pandas:pandas.DataFrame>` :param metadata: The :class:`Metadata` to apply to ``df``. :type metadata: :class:`Metadata`, :class:...
625941cb45492302aab5e384
def test_end_only(self): <NEW_LINE> <INDENT> repo_path = get_local_project_git_path("brotli") <NEW_LINE> churn = calc_code_churn_range( repo_path, ChurnConfig.create_c_style_languages_config(), None, FullCommitHash("645552217219c2877780ba4d7030044ec62d8255") ) <NEW_LINE> self.assertEqual( churn[FullCommitHash("64555221...
Check if churn is correct if only end range is set.
625941cb5fcc89381b1e1780
def parse_params(exp_name: str) -> Tuple[dict, List[str]]: <NEW_LINE> <INDENT> args, unknown_args = parse_runner_params(exp_name) <NEW_LINE> if "ddp" in args["engine"]: <NEW_LINE> <INDENT> ddp_args, unknown_args = parse_ddp_params(unknown_args) <NEW_LINE> args = {**args, **ddp_args} <NEW_LINE> <DEDENT> return args, unk...
Constructs the command-line arguments for ``train_*.py``.
625941cb63b5f9789fde71a7
def publish_registered_device(host, username, password, slack_token): <NEW_LINE> <INDENT> response = get_registered_devices(host, username, password) <NEW_LINE> with open('wifi_log.txt', 'a') as f: <NEW_LINE> <INDENT> response.append(["timestamp", datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S...
:param host: :param username: :param password: :param slack_token: :return:
625941cb009cb60464c63474
def extend_codomain(self, new_codomain, check=True): <NEW_LINE> <INDENT> new_dict = {} <NEW_LINE> for g in self._manin.gens(): <NEW_LINE> <INDENT> new_dict[g] = new_codomain(self._dict[g]) <NEW_LINE> <DEDENT> return ManinMap(new_codomain, self._manin, new_dict, check)
Extend the codomain of self to new_codomain. There must be a valid conversion operation from the old to the new codomain. This is most often used for extension of scalars from `\QQ` to `\QQ_p`. EXAMPLES:: sage: from sage.modular.pollack_stevens.manin_map import ManinMap, M2Z sage: from sage.modular.pollack_st...
625941cb82261d6c526ab561
def register_json_adapters(config): <NEW_LINE> <INDENT> json_renderer = JSON() <NEW_LINE> def blob_adapter(obj, request): <NEW_LINE> <INDENT> return obj.open('r').read() <NEW_LINE> <DEDENT> def theblob_adapter(obj, request): <NEW_LINE> <INDENT> return obj.get().decode('utf-8') <NEW_LINE> <DEDENT> def date_adapter(obj, ...
register custom JSON serializers
625941cb8e71fb1e9831d86b
def keyIsPressed(key): <NEW_LINE> <INDENT> if backend == "pygame" or backend == "pygame-basic": return KeyIsPressed_Pygame(key) <NEW_LINE> elif backend == "pyglet": return KeyIsPressed_Pyglet(key)
Return True if the string key is currently pressed
625941cb23e79379d52ee626
def standard_atari_env_spec(env=None, simulated=False): <NEW_LINE> <INDENT> standard_wrappers = [ (tf_atari_wrappers.StackWrapper, {"history": 4}) ] <NEW_LINE> env_spec = tf.contrib.training.HParams( wrappers=standard_wrappers, simulated_env=simulated, reward_range=env.reward_range, observation_space=env.observation_sp...
Parameters of environment specification.
625941cb15fb5d323cde0bd1
def _generate_implicit_api_resource(self): <NEW_LINE> <INDENT> return ImplicitApiResource().to_dict()
Uses the implicit API in this file to generate an Implicit API resource
625941cbb57a9660fec33946
def LocateSpecification(self,group,name): <NEW_LINE> <INDENT> pass
LocateSpecification(self: FabricationConfiguration,group: str,name: str) -> int Gets the specification identifier by group and name. group: The specification group. name: The specification name. Returns: The specification identifier. Returns -1 if not found.
625941cb236d856c2ad4489c