code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def prompt_for_numble(): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> brick_str = input('Bricks: ') <NEW_LINE> try: <NEW_LINE> <INDENT> bricks = [int(b) for b in brick_str.split()] <NEW_LINE> if not bricks: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <... | Prompts the user to enter bricks and a target at the keyboard.
Returns a Numble object. | 625941e271ff763f4b549a54 |
def relative_start_path(self, path=None): <NEW_LINE> <INDENT> if path is None: <NEW_LINE> <INDENT> path = Path.cwd() <NEW_LINE> <DEDENT> return relative_path(path, self.start) | return given path (or current one) relative to `start` path (in relative form, eg. '../file.csv') | 625941e291af0d3eaac9bdde |
def hierarchical_dilated_module(filters, modules, dilation): <NEW_LINE> <INDENT> def layer(x): <NEW_LINE> <INDENT> output = [] <NEW_LINE> output.append(x) <NEW_LINE> for i in range(modules): <NEW_LINE> <INDENT> x = dilated_res_block(filters, dilation[i])(output[i]) <NEW_LINE> x = dilated_res_block(filters, dilation[i])... | input -> dilated_res_block -> dilated_res_block -> dilated_res_block -> concat -> output
↘ -------> ↓ ------------------> ↓ -----------------> ↓ ------- ↗ | 625941e244b2445a33932456 |
def get_ibassettot(self): <NEW_LINE> <INDENT> return sum((ibasset for borrower, ibasset in self.ibasset)) | Return the total face value of interbank assets. | 625941e276e4537e8c351a37 |
def get_query(query_string, search_fields): <NEW_LINE> <INDENT> query = None <NEW_LINE> terms = normalize_query(query_string) <NEW_LINE> for term in terms: <NEW_LINE> <INDENT> or_query = None <NEW_LINE> for field_name in search_fields: <NEW_LINE> <INDENT> q = Q(**{"%s__icontains" % field_name: term}) <NEW_LINE> if or_q... | Retourne une requête, qui est une combinaison d'objets Q. Cette combinaison
vise à rechercher des mots-clés dans un modèle en testant les champs
de recherche donnés. | 625941e2d4950a0f3b08c70c |
def file_ref(self): <NEW_LINE> <INDENT> from metatab.util import slugify <NEW_LINE> assert self.file_name is None or isinstance(self.file_name, str) <NEW_LINE> if self.file_name is not None and self.row is not None: <NEW_LINE> <INDENT> parts = split(self.file_name); <NEW_LINE> return "{} {}:{} ".format(parts[-1], self.... | Return a string for the file, row and column of the term. | 625941e223e79379d52ee921 |
def get_translation_checks(self): <NEW_LINE> <INDENT> result = [ ( 'all', _('All strings'), self.total, 'success', ) ] <NEW_LINE> if self.translated > 0: <NEW_LINE> <INDENT> result.append(( 'translated', _('Translated strings'), self.translated, 'success', )) <NEW_LINE> <DEDENT> nottranslated = self.total - self.transl... | Returns list of failing checks on current translation. | 625941e221a7993f00bc80b9 |
def __init__( self, rules_file: str="/etc/devfs.rules", logger: typing.Optional['libioc.Logger.Logger']=None ) -> None: <NEW_LINE> <INDENT> self.logger = logger <NEW_LINE> self._ruleset_number_index = {} <NEW_LINE> self._ruleset_name_index = {} <NEW_LINE> self._system_rule_lines = [] <NEW_LINE> list.__init__(self) <NEW... | Initialize a DevfsRules manager for devfs.rules files.
Args:
rules_file (string): (default=/etc/devfs.rules)
Path of the devfs.rules file
logger (libioc.Logger): (optional)
Instance of the logger that is passed to occuring errors | 625941e2596a897236089e7f |
def dir(self): <NEW_LINE> <INDENT> osnav.dir() | An attempted to replicate the command line dir function for navigation. | 625941e28e71fb1e9831db6a |
@project_cli.command( "run", context_settings={"allow_extra_args": True, "ignore_unknown_options": True} ) <NEW_LINE> def project_run_cli( ctx: typer.Context, subcommand: str = Arg(None, help=f"Name of command defined in the {PROJECT_FILE}"), project_dir: Path = Arg(Path.cwd(), help="Location of project directory. Defa... | Run a named command or workflow defined in the project.yml. If a workflow
name is specified, all commands in the workflow are run, in order. If
commands define dependencies and/or outputs, they will only be re-run if
state has changed.
DOCS: https://spacy.io/api/cli#project-run | 625941e229b78933be1e5a6a |
def send_error(message, errors=None, status_code=400): <NEW_LINE> <INDENT> return jsonify({ 'success': False, 'message': message, 'errors': errors }), status_code | Send error response
:param message: message to be sent
:param errors: error object
:param status_code: response's status code
:return: | 625941e27c178a314d6ef828 |
def _confirm(self, question, default="yes"): <NEW_LINE> <INDENT> valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} <NEW_LINE> if default is None: <NEW_LINE> <INDENT> prompt = " [y/n] " <NEW_LINE> <DEDENT> elif default == "yes": <NEW_LINE> <INDENT> prompt = " [Y/n] " <NEW_LINE> <DEDENT> elif default ... | Confirmation dialog that requires *manual* input.
:param str question: Question to ask the user
:param str default: default answer
:return: Choice of the user
:rtype: bool | 625941e2fbf16365ca6f658e |
def print_status(self): <NEW_LINE> <INDENT> logfile = "%s_stat.txt" % self.basename <NEW_LINE> ofile = open(logfile,"w") <NEW_LINE> log = "Replica State Lambda Lambda1 Lambda2 Alpha U0 W0coeff Temperature Status Cycle \n" <NEW_LINE> for k in range(self.nreplicas): <NEW_LINE> <INDENT> stateid = self.status[k]['statei... | Writes to BASENAME_stat.txt a text version of the status of the RE job
It's fun to follow the progress in real time by doing:
watch cat BASENAME_stat.txt | 625941e21d351010ab855ede |
def prim(g: Graph) -> Graph: <NEW_LINE> <INDENT> cost: Dict[Vertex, float] = {v: inf for v in g.vertices} <NEW_LINE> edge: Dict[Vertex, Vertex] = {v: None for v in g.vertices} <NEW_LINE> tree = Graph() <NEW_LINE> vertices_left = g.vertices <NEW_LINE> while vertices_left: <NEW_LINE> <INDENT> (current_vertex, current_cos... | Constructs a minimum spanning tree using Prim's algorithm | 625941e294891a1f4081be6d |
def __init__(self,target,size=64,impro=False): <NEW_LINE> <INDENT> self.target = pd.read_csv(target, header=None, sep='\t').sample(frac=1) <NEW_LINE> self.fea_size=len(self.target) <NEW_LINE> self.impro=impro <NEW_LINE> self.size=size | :param target:
:param impro: 是否数据增强 | 625941e25fc7496912cc3d41 |
def update(self): <NEW_LINE> <INDENT> return self._send_request(self._id) | Update trigger
:return: trigger id | 625941e2283ffb24f3c55cc0 |
def kernel(self, X, A, ktup): <NEW_LINE> <INDENT> m,n = np.shape(X) <NEW_LINE> K = np.mat(np.zeros((m,1))) <NEW_LINE> if ktup[0] == 'lin': <NEW_LINE> <INDENT> K = X * A.T <NEW_LINE> <DEDENT> elif ktup[0] == 'rbf': <NEW_LINE> <INDENT> for j in range(m): <NEW_LINE> <INDENT> delta = X[j,:] - A <NEW_LINE> K[j] = delta * de... | output: mat m*1 | 625941e28e71fb1e9831db6b |
def describe_restaurant(self): <NEW_LINE> <INDENT> message = self.restaurant_name.title() + " serves the best " + self.cuisine_type.title() + " food!" <NEW_LINE> print("\n" + message) | Let people know what food is on offer | 625941e23cc13d1c6d3c773b |
def create_function_typedefs_from_file(self, f): <NEW_LINE> <INDENT> raw_data = ConfigObj(f, file_error=True) <NEW_LINE> typedefs = parse_data( raw_data, ( (Key.ARGS, Key.as_args_tuple, ()), (Key.RETURN_TYPE, Key.as_return_type, Return.VOID), (Key.CONVENTION, Key.as_convention, Convention.CDECL), (Key.DOC, str, None) )... | Create function typedefs from a file. | 625941e255399d3f05588a79 |
def decode(self, input, errors='strict'): <NEW_LINE> <INDENT> if encoding: <NEW_LINE> <INDENT> input = str(input, encoding, errors) <NEW_LINE> <DEDENT> x = map(str, _unlatex(input)) <NEW_LINE> return ''.join(x), len(input) | Convert latex source string to unicode. | 625941e2236d856c2ad44ba2 |
def main(): <NEW_LINE> <INDENT> logging.basicConfig(level=logging.DEBUG) <NEW_LINE> app = QtWidgets.QApplication(sys.argv) <NEW_LINE> window = QtWidgets.QMainWindow() <NEW_LINE> ui = example_ui.Ui_MainWindow() <NEW_LINE> ui.setupUi(window) <NEW_LINE> ui.bt_delay_popup.addActions([ ui.actionAction, ui.actionAction_C ]) ... | Application entry point | 625941e24c3428357757c6e8 |
def test_if_input_is_zero(self): <NEW_LINE> <INDENT> self.assertEquals(prime_num(0), "Numbers less than or equal to zero are not allowed!") | Tests if zero is a prime number | 625941e29f2886367277ac4d |
def __init__(self, path, branch): <NEW_LINE> <INDENT> super(GitCheckout, self).__init__(path) <NEW_LINE> self.path = path <NEW_LINE> self.branch = branch <NEW_LINE> self.debug = [] <NEW_LINE> os.chdir(path) | Constructor for GitCheckout | 625941e282261d6c526ab868 |
def print(self): <NEW_LINE> <INDENT> width, height = self.width, self.height <NEW_LINE> field_walls = self.walls <NEW_LINE> def horizontal(): <NEW_LINE> <INDENT> print(' ', end='') <NEW_LINE> for i in range(width + 2): <NEW_LINE> <INDENT> print('#', end='') <NEW_LINE> <DEDENT> print('') <NEW_LINE> <DEDENT> print(' ', ... | тестовая текстовая визуализация, скопирована откуда-то выше (а там из из ratsnblobs.py), выводит только стены TODO сделать печать всего | 625941e24428ac0f6e5babb8 |
def get_loader(self): <NEW_LINE> <INDENT> files = data_utils.get_all_files(self.dataset_dir, self.datasets) <NEW_LINE> do_shuffle = False <NEW_LINE> fqueue = tf.train.string_input_producer( files, shuffle=do_shuffle, name="input") <NEW_LINE> image_1, label_1, image_2, label_2, image_3, label_3, image_4, label_4, gt3d_1... | Outputs:
image_batch: batched images as per data_format
label_batch: batched keypoint labels N x K x 3 | 625941e260cbc95b062c6906 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, OrderPaymentTransactionDetail): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941e224f1403a92600f25 |
def _valid_by_mode(self, segmented): <NEW_LINE> <INDENT> if self._nzb_mode == NZBParseMode.Simple: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> mr = None <NEW_LINE> if segmented.filename: <NEW_LINE> <INDENT> mr = self._mime.from_filename(segmented.filename) <NEW_LINE> <DEDENT> if mr is None or mr == DEFAULT_MIME... | Internally called function that takes a segmented object and matches
it against the mode defined by this class. We return True if the mode
would otherwise accept this entry, otherwise we return False. | 625941e2c4546d3d9de72dfa |
def _diddle_filters(self) : <NEW_LINE> <INDENT> def has_dot_or_dotdot(pathname) : <NEW_LINE> <INDENT> if "." == pathname : return True <NEW_LINE> if "."+os.sep in pathname : return True <NEW_LINE> if ".." == pathname : return True <NEW_LINE> if ".." + os.sep in pathname : return True <NEW_... | Alters self.filters:
python_filename:
Has a python filename with an optional path prepended.
If the pathname has a . or .. in it, we must expand
to the abspathname
dir_path:
The filters as entered have a / in them or
are . or ..
We change those filters to insure:
2. Any filter with . or .. in it is expanded to
... | 625941e297e22403b379d35e |
def paired_ttest_kfold_cv(estimator1, estimator2, X, y, cv=10, scoring=None, shuffle=False, random_seed=None): <NEW_LINE> <INDENT> if not shuffle: <NEW_LINE> <INDENT> kf = KFold(n_splits=cv, shuffle=shuffle) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> kf = KFold(n_splits=cv, random_state=random_seed, shuffle=shuffle)... | Implements the k-fold paired t test procedure
to compare the performance of two models.
Parameters
----------
estimator1 : scikit-learn classifier or regressor
estimator2 : scikit-learn classifier or regressor
X : {array-like, sparse matrix}, shape = [n_samples, n_features]
Training vectors, where n_samples is t... | 625941e2b7558d58953c52cf |
def update_next_field(self, Bx, By, Bz): <NEW_LINE> <INDENT> if np.isnan(Bx): <NEW_LINE> <INDENT> self._mw.display_next_Bx.setText(" ") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._mw.display_next_Bx.setText("{:.3f} G".format(Bx)) <NEW_LINE> <DEDENT> if np.isnan(By): <NEW_LINE> <INDENT> self._mw.display_next_Bx.... | Display the value of the next magnetic field.
| 625941e276d4e153a657eef5 |
def __iter__(self): <NEW_LINE> <INDENT> for handle in self._entityspace: <NEW_LINE> <INDENT> yield self._dxffactory.wrap_handle(handle) | Iterate over all block entities, yielding class GraphicEntity() or inherited.
| 625941e20a366e3fb873ebe0 |
def select_anno(List): <NEW_LINE> <INDENT> if 'Exon' in List: <NEW_LINE> <INDENT> return 'Exon' <NEW_LINE> <DEDENT> elif 'Intron' in List: <NEW_LINE> <INDENT> return 'Intron' <NEW_LINE> <DEDENT> elif 'Genic' in List: <NEW_LINE> <INDENT> return 'Genic' <NEW_LINE> <DEDENT> elif 'Intergenic' in List: <NEW_LINE> <INDENT> r... | Function to assign the hierarchically right choice of annotation | 625941e238b623060ff0b1b0 |
def getRecord(manager): <NEW_LINE> <INDENT> c.execute('SELECT manager, year, week, winLoss FROM {tn} WHERE manager = "{mn}" ORDER BY year ASC, week ASC'. format(tn=matchupData, mn=manager)) <NEW_LINE> games = c.fetchall() <NEW_LINE> wins = 0 <NEW_LINE> losses = 0 <NEW_LINE> ties = 0 <NEW_LINE> for game in ga... | Return League Regular Season Leader for Given Year | 625941e2d53ae8145f87a62b |
@contextmanager <NEW_LINE> def preserve_current_style(): <NEW_LINE> <INDENT> with LOCK: <NEW_LINE> <INDENT> old = ROOT.gStyle <NEW_LINE> try: <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> ROOT.gROOT.SetStyle(old.GetName()) | Context manager which ensures that the current style remains the current
style when the context is left. | 625941e26fece00bbac2db06 |
def build_enriched_mass_matrix_obj(self): <NEW_LINE> <INDENT> return self._enr_mass_matrix_class(**asdict(self, dict_factory=self.dict_factory)) | A factory that builds and returns the EnrichedMassMatrix object | 625941e2f7d966606f6aa3cc |
def pqos_cap_get_mock(cap_ref, _cpu_ref): <NEW_LINE> <INDENT> ctypes.memmove(cap_ref, ctypes.addressof(p_cap), ctypes.sizeof(p_cap)) <NEW_LINE> return 0 | Mock pqos_cap_get(). | 625941e231939e2706e4d227 |
def load_l23_neurons(nr_neurons): <NEW_LINE> <INDENT> l23_neurons = [] <NEW_LINE> nr_neurons_inh = nr_neurons['GABAa'] + nr_neurons['GABAb'] <NEW_LINE> nr_neurons_exc = nr_neurons['AMPA'] + nr_neurons['NMDA'] <NEW_LINE> for _ in range(nr_neurons_exc): <NEW_LINE> <INDENT> l23_neurons.append(sPY()) <NEW_LINE> <DEDENT> fo... | Function for creating L2/3 neuron.
output:
L23_neurons: list containing all L2/3 neurons. | 625941e21b99ca400220ae76 |
def log_wrapper(): <NEW_LINE> <INDENT> def wrapper(method): <NEW_LINE> <INDENT> def new(self, *args, **kws): <NEW_LINE> <INDENT> global _ID <NEW_LINE> try: <NEW_LINE> <INDENT> name = 'pookeeper-%s' % self.id <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> with _ID_LOCK: <NEW_LINE> <INDENT> self.id = _ID ... | A class method decorator that renames the current thread to identify the current pookeeper client
| 625941e2dc8b845886cb58fa |
def set_ers_web_proxy(self, proxy_host, proxy_port, proxy_username=None, proxy_password=None): <NEW_LINE> <INDENT> elements = [] <NEW_LINE> for key, value in locals().items(): <NEW_LINE> <INDENT> if key.startswith('proxy_'): <NEW_LINE> <INDENT> elements.append(etree.Element('ERS_WEB_' + key, attrib={'VALUE': value})) <... | Register your iLO with HP Insigt Online using Direct Connect. Note
that you must also call dc_registration_complete | 625941e2091ae3566866731a |
def review_input(self): <NEW_LINE> <INDENT> row_ = 0 <NEW_LINE> self.create_label(self.frame, "PartID", row_, 5, bg_="lightyellow", relief_="ridge") <NEW_LINE> self.create_label(self.frame, "PartName", row_, 6, width_=40, bg_="lightyellow", relief_="ridge") <NEW_LINE> self.create_label(self.frame, "ID, MaterialType", r... | :return: | 625941e28a349b6b435e8536 |
def test_getRateCoefficient(self): <NEW_LINE> <INDENT> Tlist = numpy.array([300,500,1000,1500]) <NEW_LINE> Plist = numpy.array([1e4,1e5,1e6]) <NEW_LINE> Kexp = numpy.array([ [2.83508e+08, 2.83508e+09, 2.83508e+10], [7.68759e+07, 7.68759e+08, 7.68759e+09], [4.84353e+06, 4.84353e+07, 4.84353e+08], [7.05740e+05, 7.05740e+... | Test the ThirdBody.getRateCoefficient() method. | 625941e2c432627299f0500c |
def test_slug_3_chars(self): <NEW_LINE> <INDENT> self.client.login(username='admin', password='testpass') <NEW_LINE> data = new_document_data() <NEW_LINE> data['slug'] = 'ask' <NEW_LINE> response = self.client.post(reverse('wiki.new_document'), data) <NEW_LINE> eq_(302, response.status_code) <NEW_LINE> eq_('ask', Docum... | Make sure we can create a slug with only 3 characters. | 625941e231939e2706e4d228 |
def generate_delete_view(model_entity, verbose=False): <NEW_LINE> <INDENT> generator_parameters = deduce_generator_parameters( model_entity, operation_name="delete", url_param_pattern="(?P<pk>[\d]+)", verbose=verbose) <NEW_LINE> return url( generator_parameters.url_pattern, DeleteView.as_view( model=model_entity, conte... | Generates a default delete view for a given class.
The model class' class_name will be extracted and lower cased.
The generated url pattern will be '^{class_name}s/delete/(?P<pk>[\d]+)/$'.
The generated pattern name will be 'delete_{class_name}'.
The generated html template file will be searched as '{class_name}s/dele... | 625941e201c39578d7e751ff |
def _eval_sfun(self, ngen=1): <NEW_LINE> <INDENT> popc, fitc = self._population, self._fitness <NEW_LINE> popt, fitt = self._trial_pop, self._trial_fit <NEW_LINE> for ipop in range(self.n_pop): <NEW_LINE> <INDENT> fitc[ipop] = self.m * self.minfun(popc[ipop, :]) <NEW_LINE> <DEDENT> for igen in range(ngen): <NEW_LINE> <... | Run DE for a function that takes a single pv as an input and retuns a single value. | 625941e22eb69b55b151cc77 |
def shutdown(self): <NEW_LINE> <INDENT> self.__client.disconnectConnections() <NEW_LINE> self.__setConnected(False) | Public method to shut down the cooperation system. | 625941e2287bf620b61d3e25 |
def load_data(file_list, args): <NEW_LINE> <INDENT> if args.sequence: <NEW_LINE> <INDENT> return fh.read_log(file_list, start=args.partial[0], step=args.partial[1], points=args.partial[2], labels=args.labels, units=args.units, time_unit=args.time_unit) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return fh.read_signal... | Returns SIgnalsData instance with curves loaded from files.
:param file_list: list of full paths or 1 path (str)
:param args: namespace with args
:type file_list: list of str or str
:type args: argparse.Namespace
:return: | 625941e23539df3088e2e70e |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(FaxCancel, self).__init__(*args, **kwargs) <NEW_LINE> self.endpoint = 'fax' | Initialize the endpoint | 625941e29b70327d1c4e119a |
def Getimagesize(self): <NEW_LINE> <INDENT> data=self.device.data_stream[0].get_image() <NEW_LINE> return data.get_height(),data.get_width() | 获取图像宽,高
return height,width | 625941e2a219f33f34628d28 |
def update_security_question(self, password, question, answer): <NEW_LINE> <INDENT> url = '{api}/users/{id_}/credentials/change_recovery_question'.format(api=self._okta.api, id_=self.id) <NEW_LINE> payload = {"password": {"value": password}, "recovery_question": {"question": question, "answer": answer}} <NEW_LINE> resp... | Changes the user's security question and answer.
Returns:
True on success, False otherwise | 625941e24d74a7450ccd4587 |
def testPatrol(self): <NEW_LINE> <INDENT> mysite = self.get_site() <NEW_LINE> rc = list(mysite.recentchanges(total=1))[0] <NEW_LINE> self.assertRaises(pywikibot.Error, lambda x: list(x), mysite.patrol()) <NEW_LINE> try: <NEW_LINE> <INDENT> result = list(mysite.patrol(rcid=rc['rcid'])) <NEW_LINE> <DEDENT> except api.API... | Test the site.patrol() method. | 625941e2f548e778e58cd942 |
def make_module_req_guess(self): <NEW_LINE> <INDENT> dirs = super(EB_PGI, self).make_module_req_guess() <NEW_LINE> for key in dirs: <NEW_LINE> <INDENT> dirs[key] = [os.path.join(self.install_subdir, d) for d in dirs[key]] <NEW_LINE> <DEDENT> if 'CPATH' in dirs: <NEW_LINE> <INDENT> self.log.info("Removing $CPATH entry: ... | Prefix subdirectories in PGI install directory considered for environment variables defined in module file. | 625941e2a8ecb033257d348f |
def _get_room_name(): <NEW_LINE> <INDENT> return "room_1" | 根据策略获取当前最需要加入的房间
:return: 房间名 | 625941e2fb3f5b602dac3a5b |
def find_distance(body_part_1, body_part_2, method='euclidean'): <NEW_LINE> <INDENT> if method == 'euclidean': <NEW_LINE> <INDENT> dist = np.linalg.norm(body_part_1 - body_part_2, axis = 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('No valid find_distance method specified') <NEW_LINE> <DEDENT> return dist | Computes the distances between any two body parts, given x, y coordinates
INPUT
body_part_1 | [x, y] array of the position of body_parts (can have time dimension)
method | method for calculating distance between two body parts | 625941e25fcc89381b1e1a84 |
def delete_data_file(sesh, existing_data_file): <NEW_LINE> <INDENT> logger.info("Deleting DataFile for unique_id '{}'" .format(existing_data_file.unique_id)) <NEW_LINE> existing_data_file_variables = existing_data_file.data_file_variables <NEW_LINE> existing_ensemble_data_file_variables = ( sesh.query(EnsembleDataFileV... | Delete existing ``DataFile`` object, associated ``DataFileVariable``s,
and the associations of those ``DataFileVariable``s to ``Ensemble``s
(via object ``EnsembleDataFileVariables``).
Existing ``Ensemble``s are preserved.
:param sesh: modelmeta database session
:param existing_data_file: DataFile object representing d... | 625941e230dc7b7665901d26 |
def dataclass_non_ext_info(builder: IRBuilder, cdef: ClassDef) -> Optional[NonExtClassInfo]: <NEW_LINE> <INDENT> if is_dataclass(cdef): <NEW_LINE> <INDENT> return NonExtClassInfo( builder.primitive_op(new_dict_op, [], cdef.line), builder.add(TupleSet([], cdef.line)), builder.primitive_op(new_dict_op, [], cdef.line), bu... | Set up a NonExtClassInfo to track dataclass attributes.
In addition to setting up a normal extension class for dataclasses,
we also collect its class attributes like a non-extension class so
that we can hand them to the dataclass decorator. | 625941e244b2445a33932457 |
def flip_y_perspective(row:int, current_player:int, is_vwall:bool=False)->int: <NEW_LINE> <INDENT> if current_player == 0: <NEW_LINE> <INDENT> return row <NEW_LINE> <DEDENT> elif is_vwall: <NEW_LINE> <INDENT> return 7-row <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 8-row | Flip row coordinates for player 1 so that -- no matter who the 'current player' is -- the enemy's gate is down.
Note that flip_y_perspective is its own inverse, so flip_y_perspective(flip_y_perspective(r, c, v), c, v) == r | 625941e2e76e3b2f99f3abc9 |
def print_selection(topline, selected_list = None): <NEW_LINE> <INDENT> if selected_list is None: <NEW_LINE> <INDENT> selected_list = [] <NEW_LINE> <DEDENT> print(topline) <NEW_LINE> for selected in selected_list: <NEW_LINE> <INDENT> print(f"\t{selected}") <NEW_LINE> <DEDENT> print("") | Print a topline of information and then an indented list of selected items. | 625941e23d592f4c4ed1d427 |
def _fill_defaults(context, builder, sig, args, defaults): <NEW_LINE> <INDENT> ty = sig.return_type <NEW_LINE> llty = context.get_data_type(ty) <NEW_LINE> args = args + [ir.Constant(llty, d) for d in defaults[len(args):]] <NEW_LINE> sig = signature(*(ty,) * (len(args) + 1)) <NEW_LINE> return sig, args | Assuming a homogenous signature (same type for result and all arguments),
fill in the *defaults* if missing from the arguments. | 625941e24d74a7450ccd4588 |
def __init__(self): <NEW_LINE> <INDENT> self.SiteIds = None | :param SiteIds: 站点ID列表
:type SiteIds: list of int non-negative | 625941e230c21e258bdfa864 |
def load_model(self, model_path, encoder): <NEW_LINE> <INDENT> model = object() <NEW_LINE> logger.info('Restoring Model : {0}'.format(encoder)) <NEW_LINE> try: <NEW_LINE> <INDENT> model = read_from_pkl(model_path) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.error('Error in restoring trained mo... | Parent implementation for saving model
Default function. Implementation not forced on child | 625941e2d4950a0f3b08c70d |
def map_pairs_to_paths(wikideppaths): <NEW_LINE> <INDENT> pair_to_path_counts = {} <NEW_LINE> with open(wikideppaths, 'r') as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> if not line: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> word1, word2, deppath = line.split("\t") <N... | Each line in wikideppaths contains 3 columns
col1: word1
col2: word2
col3: deppath | 625941e20fa83653e465737c |
def find_plural_tags(dtags): <NEW_LINE> <INDENT> dplurals = {} <NEW_LINE> dsingular = [] <NEW_LINE> for k in viewkeys(dtags): <NEW_LINE> <INDENT> if k not in dsingular: <NEW_LINE> <INDENT> dsingular.append(k) <NEW_LINE> plural_type_a = "%ss" % (k) <NEW_LINE> plural_type_b = "%ses" % (k) <NEW_LINE> if plural_type_a in d... | Find tags which differ only because one is a plural of
the other.
Note that only "common" plurals are looked for as dealing
with the irregular cases would generate too many false positives
Returns a dictionary keyed by a, potentially, unwanted plural the
value of which is the, presumably, wanted singular | 625941e2b7558d58953c52d0 |
def generate_report(out_dir, latex_summaries, nb_markers, nb_samples, options): <NEW_LINE> <INDENT> graphic_paths_fn = None <NEW_LINE> if os.path.isfile(os.path.join(out_dir, "graphic_paths.txt")): <NEW_LINE> <INDENT> graphic_paths_fn = os.path.join(out_dir, "graphic_paths.txt") <NEW_LINE> <DEDENT> report_name = os.pat... | Generates the report.
:param out_dir: the output directory.
:param latex_summaries: the list of LaTeX summaries.
:param nb_markers: the final number of markers.
:param nb_samples: the final number of samples.
:param options: the list of options.
:type out_dir: str
:type latex_summaries: list
:type nb_markers: str
:ty... | 625941e256b00c62f0f14a1f |
def _get_request_parser(self, operation): <NEW_LINE> <INDENT> wpsrequest = self <NEW_LINE> def parse_get_getcapabilities(http_request): <NEW_LINE> <INDENT> acceptedversions = _get_get_param(http_request, 'acceptversions') <NEW_LINE> wpsrequest.check_accepted_versions(acceptedversions) <NEW_LINE> <DEDENT> def parse_get_... | Factory function returing propper parsing function
| 625941e2d99f1b3c44c6794c |
def get_median_day(data, number, freq='MS'): <NEW_LINE> <INDENT> years = [] <NEW_LINE> for _, group in data.groupby([pd.Grouper(freq='A'), pd.Grouper(freq=freq)]): <NEW_LINE> <INDENT> grouper = group.groupby(pd.Grouper(freq='D')).mean() <NEW_LINE> if len(grouper) & 1: <NEW_LINE> <INDENT> index_median = grouper.l... | Calculate median day giving a timeseries
Args:
data (pd.DataFrame): data to filter,
number (float): number of days to return.
Note(s):
* Month start is to avoid getting more timepoints in a even division | 625941e23cc13d1c6d3c773c |
def __init__(self, validate_args=False, name="matrix_inverse_tril"): <NEW_LINE> <INDENT> self._graph_parents = [] <NEW_LINE> self._name = name <NEW_LINE> super(MatrixInverseTriL, self).__init__( forward_min_event_ndims=2, validate_args=validate_args, name=name) | Instantiates the `MatrixInverseTriL` bijector.
Args:
validate_args: Python `bool` indicating whether arguments should be
checked for correctness.
name: Python `str` name given to ops managed by this object. | 625941e2167d2b6e31218f59 |
def active_thread_priority(self): <NEW_LINE> <INDENT> return _lilacsat_swig.kiss_encode_pdu_sptr_active_thread_priority(self) | active_thread_priority(kiss_encode_pdu_sptr self) -> int | 625941e2004d5f362079a6f5 |
def get_color(color: str) -> str: <NEW_LINE> <INDENT> lut = { "Bleu": "blue", "Rouge": "red", "Vert": "green", "Blanc": "white" } <NEW_LINE> if color not in lut: <NEW_LINE> <INDENT> raise ValueError(translate("Algobox", "Unknown color: {color}").format(color=color)) <NEW_LINE> <DEDENT> return lut[color] | Converts the specified Algobox color to a standard CSS X11 color. | 625941e2aad79263cf390e0b |
def set_vf_address(module, sriov_intf, num_vfs): <NEW_LINE> <INDENT> for vf_num in xrange(num_vfs): <NEW_LINE> <INDENT> set_command = "ip link set {} vf {} mac {}".format(sriov_intf, vf_num, spawn_mac()) <NEW_LINE> module.run_command(set_command) | Set mac address for VF | 625941e215fb5d323cde0ed8 |
def getIterationLearnNum(self): <NEW_LINE> <INDENT> return _algorithms.SpatialPooler_getIterationLearnNum(self) | getIterationLearnNum(self) -> nupic::UInt | 625941e2796e427e537b098d |
def chroma_components(Lstar_P, S_RG, S_YB): <NEW_LINE> <INDENT> C_RG = ((Lstar_P / 50) ** 0.7) * S_RG <NEW_LINE> C_YB = ((Lstar_P / 50) ** 0.7) * S_YB <NEW_LINE> return C_RG, C_YB | Returns the *chroma* components :math:`C_{RG}` and :math:`C_{YB}`.
Parameters
----------
Lstar_P : numeric
*Achromatic Lightness* correlate :math:`L_p^\star`.
S_RG : numeric
*Saturation* component :math:`S_{RG}`.
S_YB : numeric
*Saturation* component :math:`S_{YB}`.
Returns
-------
numeric
*Chroma* co... | 625941e2d18da76e2353289e |
def __init__( self, file_path=Path("./findr/captions_train2014.json"), glove_path="./findr/glove.6B.50d.txt.w2v", ): <NEW_LINE> <INDENT> self.glove = KeyedVectors.load_word2vec_format(glove_path, binary=False) <NEW_LINE> if file_path.exists(): <NEW_LINE> <INDENT> self.database = json.load(open(file_path)) <NEW_LINE> se... | Imports JSON file and stores its contents in the database class variable
Parameters
----------
file_path : Path
A string containing the file path to the JSON file
Return
------
None | 625941e28c3a873295158783 |
@lru_cache(maxsize=2) <NEW_LINE> def place_keys(year=2020): <NEW_LINE> <INDENT> keys = [] <NEW_LINE> for state, state_cities in cities(year).items(): <NEW_LINE> <INDENT> keys.append(("state", state, None)) <NEW_LINE> keys.append(("city", state, "Importados/Indefinidos")) <NEW_LINE> for city_name in state_cities.keys():... | Cria chave única para cada tipo de local em que são contabilizados casos | 625941e27047854f462a17c9 |
def get_mpv_version(exename): <NEW_LINE> <INDENT> o = subprocess.check_output([exename, "--version"]).decode() <NEW_LINE> re_ver = re.compile(r"%s (\d+)\.(\d+)\.(\d+)" % exename) <NEW_LINE> for line in o.split("\n"): <NEW_LINE> <INDENT> m = re_ver.match(line) <NEW_LINE> if m: <NEW_LINE> <INDENT> v = tuple(map(int, m.gr... | Get version of mpv as 3-tuple. | 625941e255399d3f05588a7a |
def mlr_nll_and_gradient(X, Y, W, sigma2, weighted): <NEW_LINE> <INDENT> n_samples, n_features = X.shape <NEW_LINE> _n, n_classes = Y.shape <NEW_LINE> _d, _c = W.shape <NEW_LINE> assert n_samples == _n, "Shape mismatch between X and Y" <NEW_LINE> assert n_features == _d, "Shape mismatch between X and W" <NEW_LINE> asse... | Compute the MLR negative log-likelihood and its gradient
Parameters
----------
X : array-like, shape [n_samples, n_features],
Training data
Y : numpy array, shape [n_samples, n_classes],
Target values
W : numpy array, shape [n_features, n_classes],
MLR coefficient estimates
sigma2: float, optional, defa... | 625941e2a4f1c619b28b03f5 |
def pseudo_merge_dict(dto, dfrom): <NEW_LINE> <INDENT> if not (type(dto) == dict and type(dfrom) == dict): <NEW_LINE> <INDENT> raise ValueError('non-dict passed into _psuedo_merge_dict') <NEW_LINE> <DEDENT> for k, v in dfrom.items(): <NEW_LINE> <INDENT> if k not in dto.keys(): <NEW_LINE> <INDENT> dto[k] = v <NEW_LINE> ... | Recursively merge dict objects, overwriting any non-dict values | 625941e230bbd722463cc18c |
def media_dir(): <NEW_LINE> <INDENT> dir_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) <NEW_LINE> media_local = os.path.join(dir_path, 'media') <NEW_LINE> media_usr = '/usr/share/kano-feedback/media' <NEW_LINE> if os.path.exists(media_local): <NEW_LINE> <INDENT> media_dir = media_local <NEW_LINE... | Creates the directory for the media (screenshot) | 625941e210dbd63aa1bd2f66 |
def optimize_path_once(self, path_list): <NEW_LINE> <INDENT> path_list_copy = copy.deepcopy(path_list) <NEW_LINE> active_index = 0 <NEW_LINE> change_done = False <NEW_LINE> while (active_index < len(path_list_copy) - 2) : <NEW_LINE> <INDENT> if active_index == len(path_list_copy) - 2: <NEW_LINE> <INDENT> return change_... | Loop one time over the path | 625941e2d164cc6175783113 |
def test_point_in_triangle(self): <NEW_LINE> <INDENT> triangle = [[2, 1], [7, 2], [4, 6]] <NEW_LINE> point = [4, 3] <NEW_LINE> self.assertTrue(point_in_triangle(triangle, point)) | The point lies inside the triangle. | 625941e2435de62698dfe012 |
def test_signature_with_salt(self): <NEW_LINE> <INDENT> signer = signing.Signer('predictable-secret', salt='extra-salt') <NEW_LINE> self.assertEqual( signer.signature('hello'), signing.base64_hmac('extra-salt' + 'signer', 'hello', 'predictable-secret') ) <NEW_LINE> self.assertNotEqual( signing.Signer('predictable-secre... | signature(value, salt=...) should work | 625941e2596a897236089e80 |
@follows(mkdir(gene_data_dir, simulation_data_dir)) <NEW_LINE> def setup_simulation_data(): <NEW_LINE> <INDENT> for i in range(CNT_GENE_GWAS_FILES): <NEW_LINE> <INDENT> open(os.path.join(gene_data_dir, "%03d.gene" % i), "w").close() <NEW_LINE> open(os.path.join(gene_data_dir, "%03d.gwas" % i), "w").close() <NEW_LINE> <... | create simulation files | 625941e28e7ae83300e4b392 |
def json(self): <NEW_LINE> <INDENT> return { "Allow": False, "Msg": self.value } | Format the exception as dict object.
:return: the exception as dict
:rtype: dict | 625941e250485f2cf553d15f |
def p_case_select(p): <NEW_LINE> <INDENT> p[0] = None | case_select : expr_SEQ ':'
| TOK_DEFAULT ':'
| TOK_DEFAULT | 625941e2b5575c28eb68e3c8 |
def __init__(self, owner=None, created_date=None, log=None): <NEW_LINE> <INDENT> self._owner = None <NEW_LINE> self._created_date = None <NEW_LINE> self._log = None <NEW_LINE> self.discriminator = None <NEW_LINE> if owner is not None: <NEW_LINE> <INDENT> self.owner = owner <NEW_LINE> <DEDENT> if created_date is not Non... | TeamLogDetails - a model defined in Swagger | 625941e28a43f66fc4b54426 |
def test_get_states(self): <NEW_LINE> <INDENT> self.init_recorder() <NEW_LINE> states = [] <NEW_LINE> for i in range(10): <NEW_LINE> <INDENT> state = ha.State( 'test.point_in_time_{}'.format(i % 5), "State {}".format(i), {'attribute_test': i}) <NEW_LINE> mock_state_change_event(self.hass, state) <NEW_LINE> self.hass.po... | Test getting states at a specific point in time. | 625941e244b2445a33932458 |
def guessit(self, string, options=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> options = parse_options(options) <NEW_LINE> result_decode = False <NEW_LINE> result_encode = False <NEW_LINE> if six.PY2 and isinstance(string, six.text_type): <NEW_LINE> <INDENT> string = string.encode("utf-8") <NEW_LINE> result_deco... | Retrieves all matches from string as a dict
:param string: the filename or release name
:type string: str
:param options: the filename or release name
:type options: str|dict
:return:
:rtype: | 625941e2d486a94d0b98e50b |
def pathSum(self, root, sum): <NEW_LINE> <INDENT> if root is None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return self.help(root, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum) | :type root: TreeNode
:type sum: int
:rtype: int | 625941e223e79379d52ee923 |
def intToLocalDigitsStr(value, digitsToLocalDict): <NEW_LINE> <INDENT> return str(value).translate(digitsToLocalDict) | Encode an integer value into a textual form. | 625941e2adb09d7d5db6cb52 |
def points_of_change(self, percent): <NEW_LINE> <INDENT> result = [] <NEW_LINE> j = 1 <NEW_LINE> l = 1 <NEW_LINE> while j < self.k - l + 1: <NEW_LINE> <INDENT> if self.average_pvalue(l, j) < percent: <NEW_LINE> <INDENT> result.append((l + j - 1, self.average_pvalue(l, j))) <NEW_LINE> l += j <NEW_LINE> j = 1 <NEW_LINE> ... | Index of change time point above significance level
Returns a list of tuples (t, p) for each point of change where:
t is the (1-based) index of the first month of each change
p is the associated p-value
Example 1:
M1 = M2 \= M3 = M4 = M5
Returns: [(2, 0.001)]
Example 2:
M1 \= M2 = M3 = M4 \= M5
Returns: [(1, 0.0003),... | 625941e221bff66bcd684d13 |
def setDomainNameIDL(self, sessionId, domain, vrfName): <NEW_LINE> <INDENT> self._oprot.rlock.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> self.send_setDomainNameIDL(sessionId, domain, vrfName) <NEW_LINE> result = self.recv_setDomainNameIDL() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self._oprot.r... | Parameters:
- sessionId
- domain
- vrfName | 625941e22c8b7c6e89b35b82 |
def batchnorm_forward(x, gamma, beta, bn_param): <NEW_LINE> <INDENT> mode = bn_param['mode'] <NEW_LINE> eps = bn_param.get('eps', 1e-5) <NEW_LINE> momentum = bn_param.get('momentum', 0.9) <NEW_LINE> N, D = x.shape <NEW_LINE> running_mean = bn_param.get('running_mean', np.zeros(D, dtype=x.dtype)) <NEW_LINE> running_var ... | Forward pass for batch normalization.
During training the sample mean and (uncorrected) sample variance are
computed from minibatch statistics and used to normalize the incoming data.
During training we also keep an exponentially decaying running mean of the
mean and variance of each feature, and these averages are us... | 625941e26fece00bbac2db07 |
def hoverMove(self, item, event, flag=None): <NEW_LINE> <INDENT> self.show() <NEW_LINE> self.updateLocation(item, item.mapToScene(QPointF(event.pos()))) <NEW_LINE> pos_scene = item.mapToScene(QPointF(event.pos())) <NEW_LINE> pos_item = item.mapFromScene(pos_scene) <NEW_LINE> self.setTopStrand(self.helixIndex(pos_item)[... | flag is for the case where an item in the path also needs to
implement the hover method
Args:
item (TYPE): Description
event (TYPE): Description
flag (None, optional): Description | 625941e2a8ecb033257d3490 |
def set_file_extension(self, ext): <NEW_LINE> <INDENT> ext = ext.lower() <NEW_LINE> if ext and ext != self.file_extension: <NEW_LINE> <INDENT> self.file_extension = ext <NEW_LINE> self.setup_linelight() <NEW_LINE> if self.app.config["editor"]["show_highlighting"]: <NEW_LINE> <INDENT> self.setup_highlight() | Set the file extension. | 625941e216aa5153ce36283c |
def calc_connection_costs(self, connections): <NEW_LINE> <INDENT> connections_cost = 0 <NEW_LINE> batt_cost = 0 <NEW_LINE> for battery in self.district.batteries: <NEW_LINE> <INDENT> batt_cost += battery.cost <NEW_LINE> connections_cost += self.calc_battery_connections_costs(connections, battery) <NEW_LINE> <DEDENT> co... | Calculates costs of connection to one battery.
Parameters
----------
connections : dict
battery : Battery object
Returns
----------
float | 625941e28a349b6b435e8537 |
def shift_by_background(region, interval, y_data='final', add_column=True): <NEW_LINE> <INDENT> counts = region.get_data(column=y_data) <NEW_LINE> energy = region.get_data(column="energy") <NEW_LINE> first_index = 0 <NEW_LINE> last_index = len(counts) - 1 <NEW_LINE> for i in range(0, len(energy)): <NEW_LINE> <INDENT> i... | Correct counts by the average background level given by the interval [start, stop]
| 625941e294891a1f4081be6f |
def test_polynomial_design_matrix_setup(self): <NEW_LINE> <INDENT> trafo = preprocessing.PolynomialFeatures(k) <NEW_LINE> X = trafo.fit_transform(x.reshape((-1,1))) <NEW_LINE> df = pd.DataFrame(data=X) <NEW_LINE> df.columns = [str(v) for v in df.columns] <NEW_LINE> self.assertDataFrameCorrect(df,reference_data_dir+'/po... | Polynomial design matrix including interaction terms.
| 625941e2d268445f265b5233 |
def __init__(self, stat="proportion", complementary=False): <NEW_LINE> <INDENT> _check_argument("stat", ["count", "proportion"], stat) <NEW_LINE> self.stat = stat <NEW_LINE> self.complementary = complementary | Initialize the class with its parameters
Parameters
----------
stat : {{"proportion", "count"}}
Distribution statistic to compute.
complementary : bool
If True, use the complementary CDF (1 - CDF) | 625941e2009cb60464c63774 |
def read_file(filename) -> str: <NEW_LINE> <INDENT> with open(filename) as fh: <NEW_LINE> <INDENT> file_data = fh.read() <NEW_LINE> <DEDENT> return file_data | Read the contents of a file. | 625941e2ec188e330fd5ab5d |
def __init__(self, mem, addr, data, cf, progress_cb=None): <NEW_LINE> <INDENT> self.mem = mem <NEW_LINE> self.addr = addr <NEW_LINE> self._bytes_left = len(data) <NEW_LINE> self._write_len = self._bytes_left <NEW_LINE> self._data = data <NEW_LINE> self.data = bytearray() <NEW_LINE> self.cf = cf <NEW_LINE> self._progres... | Initialize the object with good defaults | 625941e215baa723493c433d |
def updateData(self, data): <NEW_LINE> <INDENT> if self.sorting: <NEW_LINE> <INDENT> self.setSortingEnabled(False) <NEW_LINE> <DEDENT> if self.dataKey: <NEW_LINE> <INDENT> key = data.__getattribute__(self.dataKey) <NEW_LINE> if key not in self.dataDict: <NEW_LINE> <INDENT> self.insertRow(0) <NEW_LINE> d = {} <NEW_LINE>... | 将数据更新到表格中 | 625941e24f6381625f114e00 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.