code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def nodedev_create(xml_file, options=None, **dargs): <NEW_LINE> <INDENT> cmd = "nodedev-create %s" % xml_file <NEW_LINE> if options is not None: <NEW_LINE> <INDENT> cmd += " %s" % options <NEW_LINE> <DEDENT> logging.debug("Create the device from %s", xml_file) <NEW_LINE> return command(cmd, **dargs)
Return cmd result of the device to be created by an XML file :param xml_file: device XML file :param dargs: standardized virsh function API keywords :return: CmdResult object
625941db1b99ca400220ad90
def test_delete_ips(task_app): <NEW_LINE> <INDENT> last_login_at1 = datetime.utcnow() - task_app.config['ACCOUNTS_RETENTION_PERIOD'] - timedelta(days=1) <NEW_LINE> last_login_at2 = datetime.utcnow() <NEW_LINE> with task_app.app_context(): <NEW_LINE> <INDENT> user1 = create_test_user(email='user1@invenio-software...
Test if ips are deleted after 30 days.
625941db67a9b606de4a8195
def t(fn): <NEW_LINE> <INDENT> @wraps(fn) <NEW_LINE> def tuplized(args): <NEW_LINE> <INDENT> return fn(*args) <NEW_LINE> <DEDENT> return tuplized
Convert a function of N arguments to a function of one N-degree tuple Useful with higher order functions that expect single argument functions as inputs. This is given as an alternative to implementing a star_map, star_for_each, star_flat_map, etc functions for all collections. Example: def add(a, b): ret...
625941dba8370b7717052b7b
def __init__(self, f, t_0, t_f, tex, r=.1, cylinders = True, min_depth=4, max_depth=8, e_rel = .01, e_abs = .01): <NEW_LINE> <INDENT> self._e_rel = e_rel <NEW_LINE> self._e_abs = e_abs <NEW_LINE> self._r = r <NEW_LINE> self._f = f <NEW_LINE> self._tex = tex <NEW_LINE> self._cylinders = cylinders <NEW_LINE> self._max_de...
Creates the parametric plotting class. EXAMPLES:: sage: from sage.plot.plot3d.tachyon import ParametricPlot sage: t = var('t') sage: f = lambda t: (t,t^2,t^3) sage: q = ParametricPlot(f,0,1,'s') sage: q._e_rel 0.01
625941db8e7ae83300e4b2ab
def simulate_linear_data(N,beta_0,beta_1,eps_sigma_sq): <NEW_LINE> <INDENT> df = pd.DataFrame( { 'x': np.random.RandomState(42).choice( map( lambda x: float(x)/100.0, np.arange(100) ), N, replace=False ) } ) <NEW_LINE> eps_mean = 0.0 <NEW_LINE> df["y"] = beta_0 + beta_1*df["x"] + np.random.RandomState(42).normal(eps_me...
Simulate a random dataset using a noisy linbear procvess N: number of points to generate beta_0: The intercept beta_1: The slope of univariante predictor,X eps_sigma_sq: The square of the standard deviation ie the variance
625941db56b00c62f0f14938
def formfield(self, **kwargs): <NEW_LINE> <INDENT> from mezzanine.generic.forms import KeywordsWidget <NEW_LINE> kwargs["widget"] = KeywordsWidget <NEW_LINE> return super().formfield(**kwargs)
Provide the custom form widget for the admin, since there isn't a form field mapped to ``GenericRelation`` model fields.
625941db5fc7496912cc3c5b
def test_delete(self): <NEW_LINE> <INDENT> resg = self._create_dummy_stack() <NEW_LINE> self.assertIsNotNone(resg.nested()) <NEW_LINE> scheduler.TaskRunner(resg.delete)() <NEW_LINE> self.assertEqual((resg.DELETE, resg.COMPLETE), resg.nested().state) <NEW_LINE> self.assertEqual((resg.DELETE, resg.COMPLETE), resg.state)
Test basic delete.
625941dbcc0a2c11143dd16e
def finalize_expired_submission(sub): <NEW_LINE> <INDENT> grader_dict = { 'score': 0, 'feedback': error_template.format(errors="Error scoring submission."), 'status': GraderStatus.failure, 'grader_id': "0", 'grader_type': sub.next_grader_type, 'confidence': 1, 'submission_id' : sub.id, } <NEW_LINE> sub.state = Submissi...
Expire submissions by posting back to LMS with error message. Input: timed_out_list from check_if_expired method Output: Success code.
625941db4c3428357757c604
def create_test_world(radius, span, n_actin, n_actinin, n_motors): <NEW_LINE> <INDENT> tractspace = space.Space("hex", radius, span) <NEW_LINE> for tract in tractspace.all_tracts: <NEW_LINE> <INDENT> for _ in range(n_actin): <NEW_LINE> <INDENT> length = np.random.uniform(0.1 * span, 0.9 * span) <NEW_LINE> x = np.random...
Create a world of given radius with n_actin and n_actinin per tract
625941db4f6381625f114d19
def is_valid(self, text): <NEW_LINE> <INDENT> return (self.gettext('HACKER').upper() in text.upper())
Returns True if the input is related to the news. Arguments: text -- user-input, typically transcribed speech
625941db5e10d32532c5f204
def check_config(config, params, aliases=None, logger=None): <NEW_LINE> <INDENT> for key in config: <NEW_LINE> <INDENT> if aliases and key in aliases: <NEW_LINE> <INDENT> if logger: <NEW_LINE> <INDENT> logger.warn("The parameter %s is deprecated. You should use %s instead.", key, aliases[key]) <NEW_LINE> <DEDENT> new_...
Check (and update) a config dict to conform to the given parameter rules. The params dict has an entry for each valid config parameter whose value is a tuple with the following items: - type - can be a list? - default value - valid values - description (Multiple entries here are allowed for longer strings) The file c...
625941dbac7a0e7691ed43a5
def __init__(self, batch_dims): <NEW_LINE> <INDENT> if batch_dims < 0: <NEW_LINE> <INDENT> raise ValueError('Batch dims must be non-negative.') <NEW_LINE> <DEDENT> self._batch_dims = batch_dims <NEW_LINE> self._original_tensor_shape = None
Create two tied ops to flatten and unflatten the front dimensions. Args: batch_dims: Number of batch dimensions the flatten/unflatten ops should handle. Raises: ValueError: if batch dims is negative.
625941db30dc7b7665901c41
def raise_issue(url: str, issue: json) -> int: <NEW_LINE> <INDENT> r = requests.post(url, json.dumps(issue)) <NEW_LINE> return r.status_code
raise the issue in github.
625941db0c0af96317bb84c5
def get_datetime_from_request(prefix='', default=None, source=None): <NEW_LINE> <INDENT> if source is None: <NEW_LINE> <INDENT> source = request.values <NEW_LINE> <DEDENT> if default is None: <NEW_LINE> <INDENT> default = datetime.now() <NEW_LINE> <DEDENT> date_str = source.get('{}date'.format(prefix), '') <NEW_LINE> t...
Retrieves date and time from request data.
625941db187af65679ca53fd
def _SliceHelperVar(var, slice_spec): <NEW_LINE> <INDENT> return _slice_helper(var._AsTensor(), slice_spec, var)
Creates a slice helper object given a variable. This allows creating a sub-tensor from part of the current contents of a variable. See ${tf.Tensor$`Tensor.__getitem__`} for detailed examples of slicing. This function in addition also allows assignment to a sliced range. This is similar to `__setitem__` functionality...
625941db26068e7796caefc0
def fmts_from_shape(shape, texture_dim): <NEW_LINE> <INDENT> ndim = len(shape) <NEW_LINE> if ndim == texture_dim: <NEW_LINE> <INDENT> t_len = shape[-1] <NEW_LINE> if t_len > 4: <NEW_LINE> <INDENT> raise TextureError( '%s dimension of texture array must be <=4' % t_len) <NEW_LINE> <DEDENT> <DEDENT> elif ndim == texture_...
Return source and destination GL formats from array shape Parameters ---------- shape : tuple texture_dim : int shape index that should contain texture. For 1D textures this will == 2, for 2D arrays `texture_dim` == 3 Returns ------- src_format : int GL code for source array format dst_format : int GL ...
625941db7b25080760e39736
def get_concordance(lines: list, dictionary: set, output: str = None) -> None: <NEW_LINE> <INDENT> if output: <NEW_LINE> <INDENT> output = open(output, 'w') <NEW_LINE> <DEDENT> print('\n'.join(line for line,_ in lines), end='\n\n', file=output) <NEW_LINE> for word in sorted(dictionary): <NEW_LINE> <INDENT> print(''.joi...
Creates the concordance and outputs it to a file or the terminal. :param lines: A list of sentences along with each word in that line. :param dictionary: A set of words to generate a concordance from the lines. :param output: Outputs the results to a file if given or the terminal if not.
625941dbd486a94d0b98e425
def is_selected(self, locator, timeout=None, log=True): <NEW_LINE> <INDENT> if timeout is None: <NEW_LINE> <INDENT> timeout = self.default_timeout <NEW_LINE> <DEDENT> self.logger.info("Checking if element: {} is selected".format(locator.describe())) <NEW_LINE> element = locator.find_element_matching(self.wd_instance, t...
Check to see if an element is selected. You can control how long to wait, and if the method should do any logging. If you specify 0 for the timeout, the framework will only look for the element once. :param locator: the locator to look for (usually defined on a Page class) :type locator: :class:`.WebElementLocator` ...
625941db30bbd722463cc0a6
def exists(name, region=None, key=None, keyid=None, profile=None): <NEW_LINE> <INDENT> conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) <NEW_LINE> try: <NEW_LINE> <INDENT> elb = conn.get_all_load_balancers(load_balancer_names=[name]) <NEW_LINE> if elb: <NEW_LINE> <INDENT> return True <NEW_LINE> <D...
Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1
625941db91af0d3eaac9bcf9
def test_timeseries_payload(): <NEW_LINE> <INDENT> token = "asdashdsauh_8aeraerf" <NEW_LINE> client = __get_apptuit_client() <NEW_LINE> series_list = [] <NEW_LINE> tags1 = {"tagk1": "tagv1", "tagk2": "tagv2"} <NEW_LINE> tags2 = {"tagk3": "tagv3"} <NEW_LINE> metric1_name = 'metric1' <NEW_LINE> metrics2_name = "metric2" ...
Test payload from timeseries list
625941dbd8ef3951e324381b
def make_cdf(self, **kwargs): <NEW_LINE> <INDENT> normalize = kwargs.pop('normalize', False) <NEW_LINE> total = getattr(self, 'total', 1.0) <NEW_LINE> cdf = Cdf(total - self, **kwargs) <NEW_LINE> if normalize: <NEW_LINE> <INDENT> cdf.normalize() <NEW_LINE> <DEDENT> return cdf
Make a Cdf from the Surv. :return: Cdf
625941db0a50d4780f667172
def load(self, source): <NEW_LINE> <INDENT> if type(source) == file: <NEW_LINE> <INDENT> self.schema_parser = SchemaLDIFParser(source) <NEW_LINE> self.schema_source = SourceExternalFile <NEW_LINE> <DEDENT> elif type(source) == type(''): <NEW_LINE> <INDENT> self.schema_parser = SchemaLDIFParser(open(source)) <NEW_LINE> ...
Loads the source from this schema
625941dbbf627c535bc134ad
def hudFontColorHomed(raw=False): <NEW_LINE> <INDENT> return _color(PreferenceHudFontColorHomed, 0xff007400, raw)
Return the configured HUD font color to be used when the tool IS homed.
625941db63b5f9789fde73c4
def __init__(self, name, compare_gan_cls, **compare_gan_kwargs): <NEW_LINE> <INDENT> super(_CompareGANLayer, self).__init__(name=name) <NEW_LINE> compare_gan_kwargs["name"] = name <NEW_LINE> self._name = name <NEW_LINE> self._model = compare_gan_cls(**compare_gan_kwargs)
Constructor. Args: name: Name of the layer. IMPORTANT: Setting this to the same string for two different layers will cause unexpected behavior since variables are found using this name. compare_gan_cls: A class from compare_gan, which should inherit from either AbstractGenerator or AbstractDiscriminato...
625941db5fc7496912cc3c5c
def to_jsonable(self) -> MutableMapping[str, Any]: <NEW_LINE> <INDENT> return token_post401_application_json_response_to_jsonable(self)
Dispatches the conversion to token_post401_application_json_response_to_jsonable. :return: JSON-able representation
625941dbe8904600ed9f220e
def cast(*args): <NEW_LINE> <INDENT> return _itkAbsImageFilterPython.itkAbsImageFilterID3ID3_Superclass_cast(*args)
cast(itkLightObject obj) -> itkAbsImageFilterID3ID3_Superclass
625941db627d3e7fe0d6912f
def output(self, invar): <NEW_LINE> <INDENT> dir=['down','','up'] <NEW_LINE> try: <NEW_LINE> <INDENT> error=self.setPoint - invar <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> error=0 <NEW_LINE> msg='invalid actual '+repr(invar)+' for pid error calculation, error zero used!' <NEW_LINE> <DEDENT> self.currtm = time.tim...
Performs a PID computation and returns a control value based on the elapsed time (dt) and the difference between actual value and setpoint.
625941dbcc0a2c11143dd16f
def test_main(self, tmpdir, mocker): <NEW_LINE> <INDENT> mocker.patch('latexdiffcite.latexdiffcite.subprocess.Popen', new=mock_popen) <NEW_LINE> fname = os.path.join('tests', 'utf-8_LF', 'test.tex') <NEW_LINE> latexdiffcite.main(['file', fname, fname, '-v', '-l', str(tmpdir.join('log.log')), '-o', str(tmpdir.join('diff...
Tests the whole shebang, except actually calling latexdiff
625941db9b70327d1c4e10b4
def get_gps_network_simulator(self, bench_name): <NEW_LINE> <INDENT> self.get_logger().debug("Get GPS network simulator %s", bench_name) <NEW_LINE> bench_dic = self.get_global_config().benchConfig.get_parameters(bench_name) <NEW_LINE> eqt_model = bench_dic.get_param_value("Model") <NEW_LINE> if not eqt_model...
Gets the instance of a GPS network simulator :type bench_name: str :param bench_name: the bench name of the equipment :rtype: IGPSNetSim :return: the instance of the requested bench WLAN network simulator
625941db8e05c05ec3eea654
def hide_tick_marks(ax=None, show_x_tick_mrks=False, show_y_tick_mrks=False): <NEW_LINE> <INDENT> ax = axes(ax) <NEW_LINE> if not show_x_tick_mrks: <NEW_LINE> <INDENT> ax.tick_params(axis='x', which='both', length=0) <NEW_LINE> <DEDENT> if not show_y_tick_mrks: <NEW_LINE> <INDENT> ax.tick_params(axis='y', which='both',...
Hide ticks marks (but not tick labels) on either or both axes.
625941dbb830903b967e9be7
def get_rating_query(self): <NEW_LINE> <INDENT> raise errors.Unimplemented()
Gets the query for a rating query. Multiple retrievals produce a nested ``OR`` term. return: (osid.grading.GradeQuery) - the rating query raise: Unimplemented - ``supports_rating_query()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_rating_query()`` is ``true``.*
625941db3cc13d1c6d3c7657
def split_words(text): <NEW_LINE> <INDENT> return
Split an utterance on spaces Parameters: text (str): Running text with space-delimited words Returns: (list): A list of words Example: >>> split_words("This is an example.") ["This","is","an","example."]
625941db91f36d47f21ac7d3
def get_map(working_threads): <NEW_LINE> <INDENT> if working_threads <= 1: <NEW_LINE> <INDENT> return map <NEW_LINE> <DEDENT> return multiprocessing.Pool(processes=working_threads).imap_unordered
Returns the map method for jobs.
625941db15baa723493c4255
def sort_with_connect(fname): <NEW_LINE> <INDENT> mdffile = "%s.mdf"%fname <NEW_LINE> carfile = "%s.car"%fname <NEW_LINE> mdf = Mdf(mdffile) <NEW_LINE> car = Car(carfile) <NEW_LINE> a = car.parser() <NEW_LINE> Li = [] <NEW_LINE> Ge = [] <NEW_LINE> P = [] <NEW_LINE> atom_names = mdf.atom_names <NEW_LINE> for i in range(...
Sort the atoms: gather the same atoms, and atoms in same molecules according to connectivity (.mdf). This is very good for generating gromacs input files, and organize the atoms into a well defined order.
625941dbf9cc0f698b1408d7
def testCaseSend(self): <NEW_LINE> <INDENT> Send(self.driver,username).send_action("appiumpythonios")
发送邮件
625941db956e5f7376d7114a
def camera_add(name, origin=(0, 0, 0), clip_start=0.1, clip_end=1000.0): <NEW_LINE> <INDENT> cam = bpy.data.cameras.new(name+"_cam") <NEW_LINE> obj = bpy.data.objects.new(name, cam) <NEW_LINE> obj.location = origin <NEW_LINE> obj.show_name = True <NEW_LINE> cam.clip_start = clip_start <NEW_LINE> cam.clip_end = clip_end...
Create camera
625941db7d43ff24873a2f80
def OneClickAddToCurrentScene(self): <NEW_LINE> <INDENT> pass
Send the scene and add it to the current scene in the specified application. return : True if transfer successful.
625941db07d97122c4178b6f
def contextMenuEvent(self, event): <NEW_LINE> <INDENT> indexes = self.tree.selectedIndexes() <NEW_LINE> try: <NEW_LINE> <INDENT> index = indexes[0] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> pBLogger.debug(cwstr.clickMissingIndex) <NEW_LINE> return <NEW_LINE> <DEDENT> if index.isValid(): <NEW_LINE> <IND...
Create a right click menu with few actions on the selected category Parameter: event: a `QEvent`
625941db21a7993f00bc7fd2
def annotations(self): <NEW_LINE> <INDENT> name = '{annotations}' <NEW_LINE> obj_type = "{OL}" <NEW_LINE> parent_keys = ["annotations"] <NEW_LINE> docstring = ( "{A_OLlike} of annotation {pl_ULlike} to be shown on one plotly figure." ) <NEW_LINE> links = [] <NEW_LINE> examples = MakeExamples.annotations(MakeExamples())...
@annotations@ (accepts no keys)
625941dbd99f1b3c44c67869
def make_key_getter(key): <NEW_LINE> <INDENT> if hasattr(key, "__moyacall__"): <NEW_LINE> <INDENT> return key.__moyacall__ <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return obj_index_getter(key)
Get a callable that extracts a key or sub-expression.
625941dbdc8b845886cb5814
def matched(string): <NEW_LINE> <INDENT> match = { '{': '}', '[': ']', '(': ')' } <NEW_LINE> state = [] <NEW_LINE> for char in string: <NEW_LINE> <INDENT> if char in match.keys(): <NEW_LINE> <INDENT> state.append(char) <NEW_LINE> <DEDENT> elif char in match.values(): <NEW_LINE> <INDENT> if not len(state): <NEW_LINE> <I...
>>> matched('()') True >>> matched('(]') False >>> matched('[{()}]') True >>> matched('[{()]}') False >>> matched('[{()}]]') False
625941dba219f33f34628c44
def _install(self): <NEW_LINE> <INDENT> self.node.run_cmd(self.script_download, attempts=5) <NEW_LINE> command = "; ".join(self.install_commands) <NEW_LINE> self.node.run_cmd(command)
Installs chef server on the given node
625941db07f4c71912b11762
def test_basic_discovery(self): <NEW_LINE> <INDENT> with os_helper.temp_cwd(): <NEW_LINE> <INDENT> os.mkdir('foo') <NEW_LINE> file1 = os.path.join('foo', 'file1.txt') <NEW_LINE> os_helper.create_empty_file(file1) <NEW_LINE> os.mkdir('bar') <NEW_LINE> file2 = os.path.join('bar', 'file2.txt') <NEW_LINE> os_helper.create_...
When findall is called with no parameters or with '.' as the parameter, the dot should be omitted from the results.
625941db85dfad0860c3b13a
def __init__(self, directory_movehistory): <NEW_LINE> <INDENT> now = datetime.datetime.now() <NEW_LINE> directory_movehistory = directory_movehistory if directory_movehistory[-1] == "/" else directory_movehistory + "/" <NEW_LINE> self.filename_movehistory = directory_movehistory + str(now.strftime("%Y-%m-%d_%H:%M:%S"))...
:param directory_movehistory: directory, where to save the sequence of moves
625941db4f6381625f114d1a
def get_group(group_name): <NEW_LINE> <INDENT> return Group.objects.get(name=group_name)
Return group from a group_name identifier
625941dbbe8e80087fb20f1d
def build_lift_calendar(lift_times, is_break=False): <NEW_LINE> <INDENT> days = set() <NEW_LINE> lift_dict = dict() <NEW_LINE> for lift in lift_times: <NEW_LINE> <INDENT> days.add(lift.date) <NEW_LINE> lift_dict[(lift.date,lift.start_time)] = lift <NEW_LINE> <DEDENT> return LiftCalendar(days=sorted(list(days)), lift_ho...
Method that takes a list of lif times and turns them into a LiftCalendar object
625941db0383005118ecf8c0
def execute(self, context): <NEW_LINE> <INDENT> pi = 0 if context.selected_objects[0] == context.active_object else 1 <NEW_LINE> ci = int(not pi) <NEW_LINE> parentinterface = context.selected_objects[pi] <NEW_LINE> childinterface = context.selected_objects[ci] <NEW_LINE> eUtils.connectInterfaces(parentinterface, childi...
Args: context: Returns:
625941db596a897236089d9c
def _rotateBy(self, points, theta): <NEW_LINE> <INDENT> c = self._centroid(points) <NEW_LINE> cos = math.cos(theta) <NEW_LINE> sin = math.sin(theta) <NEW_LINE> newpoints = [] <NEW_LINE> for point in points: <NEW_LINE> <INDENT> qx = (point[0] - c[0]) * cos - (point[1] - c[1]) * sin + c[0] <NEW_LINE> qy = (point[0] - c[0...
Rotate a set of points by a given angle.
625941db004d5f362079a610
def test_update(self): <NEW_LINE> <INDENT> self.client.force_authenticate(user=self.admin) <NEW_LINE> fname = self.picture_file.name.replace('\\', '/').split("/")[-1] <NEW_LINE> data = { 'name': "new_picture", 'workplace': reverse('workplace-detail', args=[self.workplace.id]), 'picture': self.picture_file, } <NEW_LINE>...
Ensure we can update a picture.
625941db24f1403a92600e42
def anagramMappings(self, A, B): <NEW_LINE> <INDENT> my_map = defaultdict(list) <NEW_LINE> for i in range(len(B)): <NEW_LINE> <INDENT> my_map[B[i]].append(i) <NEW_LINE> <DEDENT> res = [] <NEW_LINE> for n in A: <NEW_LINE> <INDENT> index = my_map[n].pop(0) <NEW_LINE> res.append(index) <NEW_LINE> <DEDENT> return res
:type A: List[int] :type B: List[int] :rtype: List[int]
625941db435de62698dfdf2b
def call(self, func, sopel, trigger): <NEW_LINE> <INDENT> nick = trigger.nick <NEW_LINE> current_time = time.time() <NEW_LINE> if nick not in self._times: <NEW_LINE> <INDENT> self._times[nick] = dict() <NEW_LINE> <DEDENT> if self.nick not in self._times: <NEW_LINE> <INDENT> self._times[self.nick] = dict() <NEW_LINE> <D...
Call a function, applying any rate-limiting or restrictions. :param func: the function to call :type func: :term:`function` :param sopel: a SopelWrapper instance :type sopel: :class:`SopelWrapper` :param Trigger trigger: the Trigger object for the line from the server that triggered this call
625941dbb7558d58953c51ee
def create_user(request, ulogin_response): <NEW_LINE> <INDENT> if s.CREATE_USER_CALLBACK is not None: <NEW_LINE> <INDENT> callback = import_by_path(s.CREATE_USER_CALLBACK) <NEW_LINE> if callable(callback): <NEW_LINE> <INDENT> return callback(request=request, ulogin_response=ulogin_response) <NEW_LINE> <DEDENT> raise Im...
Creates user
625941db76e4537e8c351953
def checksum(rows: List[List[int]]) -> int: <NEW_LINE> <INDENT> check = 0 <NEW_LINE> for row in rows: <NEW_LINE> <INDENT> assert len(row) == len(set(row)) <NEW_LINE> for i in row: <NEW_LINE> <INDENT> for j in row: <NEW_LINE> <INDENT> if i != j and i % j == 0: <NEW_LINE> <INDENT> check += i / j <NEW_LINE> <DEDENT> <DEDE...
Solves the AOC second puzzle, part two.
625941db16aa5153ce362756
def test_main_version(self): <NEW_LINE> <INDENT> with mock.patch("sys.argv", ("square.py", "version")): <NEW_LINE> <INDENT> assert main.main() == 0
Simulate "version" command.
625941dbeab8aa0e5d26de37
def get_longest_matches(self): <NEW_LINE> <INDENT> def get_overlapping_spans(spans): <NEW_LINE> <INDENT> offsets = spans.keys() <NEW_LINE> overlaps = {} <NEW_LINE> for offset in offsets: <NEW_LINE> <INDENT> o = [(i[0], i[1]) for i in offsets if i[0] >= offset[0] and i[0] <= offset[1] or i[1] >= offset[0] and i[1] <= of...
Remove all shortest matching overlapping spans.
625941dbad47b63b2c50a25d
def get_compute_capability(gpu_id): <NEW_LINE> <INDENT> gpu_list = get_available_gpus() <NEW_LINE> device_query_path = prefs.devices.cuda_standalone.cuda_backend.device_query_path <NEW_LINE> if device_query_path is None: <NEW_LINE> <INDENT> cuda_path = get_cuda_path() <NEW_LINE> device_query_path = os.path.join( cuda_p...
Get compute capability of GPU with ID `gpu_id`. Returns a float (e.g. `6.1`).
625941db67a9b606de4a8196
def test_delete_user(self): <NEW_LINE> <INDENT> self.new_user.save_user() <NEW_LINE> test_user = User("mimi","niyigena","mimi@gmail.com","mymy","mimik") <NEW_LINE> test_user.save_user() <NEW_LINE> self.new_user.delete_user() <NEW_LINE> self.assertEqual(len(User.user_list),1)
test_delete_user to test if we can remove a user from our users list
625941dbf9cc0f698b1408d8
def _tipo(row): <NEW_LINE> <INDENT> per = db.persona(row.id) <NEW_LINE> tipo = "OTHER" <NEW_LINE> if per.estudiante.select(): <NEW_LINE> <INDENT> tipo = T("ESTUDIANTE") <NEW_LINE> <DEDENT> elif per.profesor.select(): <NEW_LINE> <INDENT> tipo = T("PROFESOR") <NEW_LINE> <DEDENT> return CAT(tipo)
Para mostrar el tipo de persona que es
625941db1d351010ab855dfa
def nameToIndex(self, name): <NEW_LINE> <INDENT> for index, pos in enumerate(self.positionList): <NEW_LINE> <INDENT> if pos.name == name: <NEW_LINE> <INDENT> return index <NEW_LINE> <DEDENT> <DEDENT> return None
return the index of the first instance of named position or None if not found
625941db460517430c39445e
def test_create_reviewer_with_no_user(self): <NEW_LINE> <INDENT> module = self.module <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> self.manager.create_reviewer([module], None)
Check that a model will not be created without a user
625941db23e79379d52ee83f
def make_pddtable(self, D = 1, kmin = 1e-3, kmax = 2, nk = 200, jlfunc=None): <NEW_LINE> <INDENT> if jlfunc is None: <NEW_LINE> <INDENT> jlfunc = lambda k: self.jn <NEW_LINE> <DEDENT> self.setup_yq(species='dd',D=D) <NEW_LINE> self.pktable_dd = np.zeros([nk, self.num_power_components+1]) <NEW_LINE> kv = np.logspace(np....
Make a table of different terms of P(k) between a given 'kmin', 'kmax' and for 'nk' equally spaced values in log10 of k This is the most time consuming part of the code.
625941db24f1403a92600e43
def calculate_delta_dipole_angle(azimuth1: List[float], elevation1: List[float], azimuth2: List[float], elevation2: List[float], convert_to_degrees: bool = False) -> List[float]: <NEW_LINE> <INDENT> dt = list() <NEW_LINE> for az1, ele1, az2, ele2 in zip(azimuth1, elevation1, azimuth2, elevation2): <NEW_LINE> <INDENT> d...
Calculates the angular difference between two VCGs based on difference in azimuthal and elevation angles. Useful for calculating difference between weighted averages. Parameters ---------- azimuth1 : list of float Azimuth angles for the first dipole elevation1 : list of float Elevation angles for the first di...
625941db046cf37aa974d024
def edit(self, point_id, name, geometry): <NEW_LINE> <INDENT> url = f"{self.url}/{self.version}/points/{point_id}" <NEW_LINE> headers = { "Accept": "application/geo+json", "Content-Type": "application/geo+json", } <NEW_LINE> changed_point = { "type": "Feature", "properties": {"name": name}, "geometry": json.loads(geome...
Edit a Point with a specific ID.
625941db8a43f66fc4b54341
def _setup_property_sets(self): <NEW_LINE> <INDENT> def add_set(set_enum): <NEW_LINE> <INDENT> self._property_set_map[set_enum] = PropertySet(set_enum) <NEW_LINE> <DEDENT> add_set(PropertySet.BROWN) <NEW_LINE> add_set(PropertySet.LIGHT_BLUE) <NEW_LINE> add_set(PropertySet.PURPLE) <NEW_LINE> add_set(PropertySet.ORANGE) ...
Creates a property set for each set, and maps them to the set ID.
625941db3eb6a72ae02ec7c3
def Start(self): <NEW_LINE> <INDENT> system = self.client_os <NEW_LINE> if system == "Darwin" or system == "Windows": <NEW_LINE> <INDENT> self.CallClient( server_stubs.Uninstall, next_state=compatibility.GetName(self.Kill)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.Log("Unsupported platform for Uninstall")
Start the flow and determine OS support.
625941db3617ad0b5ed681d5
def test_create_user(self): <NEW_LINE> <INDENT> msg_s1 = 'Tenant can not be created. ' <NEW_LINE> tenant = self.verify(20, self._create_tenant, 1, msg_s1, 'tenant creation', self.identity_client) <NEW_LINE> self.verify_response_true( tenant.name.startswith('ost1_test'), "Step 2 failed: {msg}".format(msg=msg_s1)) <NEW_L...
Create user and authenticate with it. Target components: Nova, Keystone Scenario: 1. Create a new tenant. 2. Check that tenant was created successfully. 3. Create a new user. 4. Check that user was created successfully. 5. Create a new user role. 6. Check that user role was created successfully...
625941db379a373c97cfae25
def _reset_filters(self): <NEW_LINE> <INDENT> self.filter_coords.value = True <NEW_LINE> self.filter_restarts.value = True
Reset filters to default values
625941db07d97122c4178b70
def _on_combo_changed(self, combobox): <NEW_LINE> <INDENT> active = combobox.get_active() <NEW_LINE> self.__timespan_value = TimeSpanValues[str(active)] <NEW_LINE> self.__filter.refilter()
Update model @param combobox as Gtk.ComboBox
625941db57b8e32f5248377c
def test_delete_article_successful(self): <NEW_LINE> <INDENT> user = User.objects.get(username='olivia') <NEW_LINE> list_view = ArticleList.as_view() <NEW_LINE> detail_view = ArticleDetail.as_view() <NEW_LINE> create_request = self.request_factory.post(self.articles_url, self.data) <NEW_LINE> force_authenticate(create_...
Test user can successfully delete an article
625941db6e29344779a628ef
def spatialite_connect(*args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from pyspatialite import dbapi2 <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> import sqlite3 <NEW_LINE> con = sqlite3.dbapi2.connect(*args, **kwargs) <NEW_LINE> con.enable_load_extension(True) <NEW_LINE> cur = con.cursor...
returns a dbapi2.Connection to a SpatiaLite db either using pyspatialite if it is present or using the "mod_spatialite" extension (python3)
625941dbeab8aa0e5d26de38
def testCanGetLayersByType(self): <NEW_LINE> <INDENT> self.m.addLayer(serge.blocks.tiled.Layer(self.m, 'one', 'visual', tiles=self.t1)) <NEW_LINE> self.m.addLayer(serge.blocks.tiled.Layer(self.m, 'two', 'movement', 4, 4)) <NEW_LINE> l = self.m.getLayerByType('visual') <NEW_LINE> self.assertEqual((3,4), l.getSize()) <NE...
testCanGetLayersByType: should be able to get layers by type
625941dbfbf16365ca6f64a7
def decorator( fct ): <NEW_LINE> <INDENT> @functools.wraps( fct ) <NEW_LINE> def wrapper( self, *args, **kwargs ): <NEW_LINE> <INDENT> if not self._connection: <NEW_LINE> <INDENT> utils.UserMessage( 'Vimspector not connected, start a debug session first', persist=False, error=True ) <NEW_LINE> return otherwise <NEW_LIN...
Decorator, call fct if self._connected else echo warning
625941dba934411ee3751973
def wybierz_xo(): <NEW_LINE> <INDENT> global PLANSZA_ROZMIAR, WYGRYWAJACYCH <NEW_LINE> PLANSZA_ROZMIAR = (3, 3) <NEW_LINE> WYGRYWAJACYCH = 3
klasyczna gra w kółko i krzyżyk na planszy 3x3
625941db091ae35668667239
def generate_telemetry(fileName, callID="000", header=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> h5File = h5py.File(fileName, 'r') <NEW_LINE> h5File.close() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> with h5py.File(fileName, 'r') as h5File: <NEW_LINE> <INDENT> rowData = ge...
Create telemetry matrix from read files; any per-read summary statistics that would be useful to know
625941db4428ac0f6e5baad3
def parse(self, stream, verbose=False): <NEW_LINE> <INDENT> myroot = Root("root") <NEW_LINE> context = [myroot] <NEW_LINE> warnings = "" <NEW_LINE> for num, line in enumerate(stream): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> rank, myelement = self.__parseLine__(line) <NEW_LINE> while len(context) > rank : <NEW_LINE...
parse a stream, usually a opened file
625941db046cf37aa974d025
def clear(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> super(DrawableGroup, self).clear() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self[:] = []
Remove all the items from the group Compatibility method for python2, where lists don't have a clear method
625941db66656f66f7cbc48b
def xmlrpc_get_tasks(self, info={}): <NEW_LINE> <INDENT> tname = info.get('name', '') <NEW_LINE> tasks = self.get_tasks(tname) <NEW_LINE> s = '' <NEW_LINE> for task in tasks: <NEW_LINE> <INDENT> s += "[%06d] - [%30s] - [%s]\n" % (task[0], task[1], task[2]) <NEW_LINE> <DEDENT> return (True, s,)
Get task list and its informations
625941db2c8b7c6e89b35a9e
def asset_filename(self, path): <NEW_LINE> <INDENT> return os.path.normpath(os.path.join(self.ASSETS_DIR, path))
Given a path relative to the assets directory, returns the absolute path to the filename.
625941dba4f1c619b28b0312
def show_entry(self, recnum=1): <NEW_LINE> <INDENT> self.prevButton.setEnabled(True) <NEW_LINE> self.nextButton.setEnabled(True) <NEW_LINE> if recnum < 1: <NEW_LINE> <INDENT> self.current_entry_number = self.max_entry_number + recnum <NEW_LINE> <DEDENT> elif recnum > self.max_entry_number: <NEW_LINE> <INDENT> self.curr...
show_entry(recnum) where 1 <= recnum <= max_entry_number. recnum is the index into the entry list. The buttons will wrap around the index values.
625941db0383005118ecf8c1
def get_timestamp(ordinal): <NEW_LINE> <INDENT> if ordinal is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> timestamp = str(ordinal_to_timestamp(ordinal)) <NEW_LINE> return timestamp
Turn an ordinal timestamp into a datetime string.
625941dbab23a570cc250464
def mkdir(self, path): <NEW_LINE> <INDENT> p=path.split('/') <NEW_LINE> cur=self.root <NEW_LINE> for v in p: <NEW_LINE> <INDENT> if not v: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if not v in cur.children: <NEW_LINE> <INDENT> cur.children[v]=Node() <NEW_LINE> cur.children[v].name=v <NEW_LINE> <DEDENT> cur=cur.c...
:type path: str :rtype: void
625941db498bea3a759b9d8e
def __init__(self, apex_pt3d, vector_1, vector_2): <NEW_LINE> <INDENT> self._apex = apex_pt3d <NEW_LINE> self._versor_1 = vector_1.versor() <NEW_LINE> self._versor_2 = vector_2.versor()
assert almost_zero(versor_1.length() - 1.0) assert almost_zero(versor_2.length() - 1.0)
625941db167d2b6e31218e74
def test_api_can_get_all_businesses(self): <NEW_LINE> <INDENT> res = self.client().post('/statuses/', data=self.status) <NEW_LINE> self.assertEqual(res.status_code, 201) <NEW_LINE> res = self.client().get('/statuses/') <NEW_LINE> self.assertEqual(res.status_code, 200) <NEW_LINE> self.assertIn('active', str(res.data))
Test API can get all statuses (GET request).
625941db2c8b7c6e89b35a9f
def get_commit(self, oid_or_commit): <NEW_LINE> <INDENT> if not self.__repo or not oid_or_commit: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> commit = oid_or_commit <NEW_LINE> if not isinstance(oid_or_commit, Commit): <NEW_LINE> <INDENT> commit = self.__repo.get(oid_or_commit) <NEW_LINE...
return a commit w/ json
625941db9f2886367277ab6b
def null_to_zero(): <NEW_LINE> <INDENT> cur.execute("SELECT * FROM teams") <NEW_LINE> rows = cur.fetchall() <NEW_LINE> for row in rows: <NEW_LINE> <INDENT> team = row[0] <NEW_LINE> wins = row[1] <NEW_LINE> losses = row[2] <NEW_LINE> if wins == None: <NEW_LINE> <INDENT> new_wins = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> ...
This is a function to replace all null variables in the wins and losses columns with 0s. Should have done this at the beginning.... Would have been easier. Will keep for next season.
625941db56ac1b37e62644aa
def line_search(f, th_star, vd, eps, K=10, eta=1., rep_lim=300): <NEW_LINE> <INDENT> th = th_star.copy() <NEW_LINE> offset = 0 <NEW_LINE> for i in range(K): <NEW_LINE> <INDENT> rep = 0 <NEW_LINE> while f(th) < eps and rep <= rep_lim: <NEW_LINE> <INDENT> th += eta * vd <NEW_LINE> offset += eta <NEW_LINE> rep += 1 <NEW_L...
Line search algorithm. Parameters ---------- f: Callable(np.ndarray) -> float, the distance function th_star: np.array (D,), starting point vd: np.array (D,) search direction eps: threshold K: int (default = 10), nof refinements eta: float (default = 1.), step along the search direction rep_lim: int (default = 300), n...
625941db5166f23b2e1a5438
def register_business(self, access_token): <NEW_LINE> <INDENT> business_data = json.dumps({ 'name': 'Palmer Tech', 'category': 'Technology', 'location': 'Nairobi', 'summary': 'AI is transforming human life'}) <NEW_LINE> return self.run_app.post( '/api/v2/businesses', data=business_data, headers=dict(Authorization='Bear...
Register a business.
625941db711fe17d82542645
@app.route('/myrecipes/<username>/') <NEW_LINE> def myrecipes(username): <NEW_LINE> <INDENT> user_recipes = mongo.db.recipes.find({"author": username}) <NEW_LINE> pic = randint(1,10) <NEW_LINE> return render_template('myrecipes.html', user_recipes=user_recipes, username=username, picture_number=pic, all_categories=all_...
Shows all recipes of the user, or all recipes from one specific author
625941dbb7558d58953c51ef
def _update_all_dependencies(self, t, do_2d_coupling=False, do_vert_diffusion=False, do_ale_update=False, do_stab_params=False, do_turbulence=False): <NEW_LINE> <INDENT> self._update_3d_elevation() <NEW_LINE> if do_ale_update: <NEW_LINE> <INDENT> self._update_moving_mesh() <NEW_LINE> <DEDENT> if do_2d_coupling: <NEW_LI...
Default routine for updating all dependent fields after a time step
625941dbbe7bc26dc91cd8da
def DefinePRBinCatConstraint(self, placement, officeData, persoData ) : <NEW_LINE> <INDENT> self.wish = persoData.loc[:, self.label].values <NEW_LINE> officeFilter = pd.pivot_table(officeData.loc[:,[self.label]], columns=self.label, index=officeData.index, aggfunc=len).fillna(0) <NEW_LINE> self.dispo = np.dot( placemen...
Fills the wish and dispo for prBinCat constraints wish ( user x 1) contains the weight a user i attributes to having a ressource with the labelled property. dispo ( user x cat) contains the category which have been attributed to a user i.
625941db5510c4643540f6bd
def set_name(self): <NEW_LINE> <INDENT> res = self.master_scan() <NEW_LINE> if res is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.name = res['data']['name'] <NEW_LINE> return True
Set the name appropriately. The Name is given from master :return: bool if master was found
625941db4c3428357757c606
def test(self): <NEW_LINE> <INDENT> self.restore_model(self.test_iters) <NEW_LINE> with torch.no_grad(): <NEW_LINE> <INDENT> start_flag = 0 <NEW_LINE> for i, (x_real, c_org) in enumerate(self.dataloader['val']): <NEW_LINE> <INDENT> x_real = x_real.float().to(self.device) <NEW_LINE> rand_idx = torch.randperm(c_org.size(...
Translate images using StarGAN trained on a single dataset.
625941dbff9c53063f47c4d2
def set_file_vars(file_vars=None): <NEW_LINE> <INDENT> files.update_vars({"path_where": str(WHERE_DIR)}) <NEW_LINE> files.update_vars({"path_{}".format(k): str(v.path) for k, v in where.path.data.items()}) <NEW_LINE> if file_vars is not None: <NEW_LINE> <INDENT> files.update_vars(file_vars)
Add variables to Files-configuration Args: file_vars (Dict): Variables that will be made available in files-configuration
625941db0c0af96317bb84c7
def update_task(request, task_uri): <NEW_LINE> <INDENT> if request.method == 'PUT': <NEW_LINE> <INDENT> _task = ToDo.objects.filter(uri__exact=task_uri) <NEW_LINE> if _task: <NEW_LINE> <INDENT> req_body_dict = json.loads(request.body) <NEW_LINE> _task.update(**req_body_dict) <NEW_LINE> _task_json = json.loads( serializ...
update name or status of a task
625941db3617ad0b5ed681d6
def get_data(self, soup: BeautifulSoup) -> list: <NEW_LINE> <INDENT> data = soup.find("table", {"class": self._table_class}).find_all('td', {'data-label': HEADERS}) <NEW_LINE> data = [item.text for item in data] <NEW_LINE> data = [data[i:i + 5] for i in range(0, len(data), 5)] <NEW_LINE> return data
Get the proper data and divide it to list of days
625941dbf7d966606f6aa2e7
def cmd_add(options): <NEW_LINE> <INDENT> def per_file(fname): <NEW_LINE> <INDENT> op.add_tags(fname, **options) <NEW_LINE> op.print_file_tags(fname, **options) <NEW_LINE> <DEDENT> _maybe_check_new_tags(options) <NEW_LINE> apply_to_files(per_file, options) <NEW_LINE> op.update_recoll_index(**options)
Perform the actions corresponding to --add.
625941db187af65679ca53ff
def _get_checkpoint(): <NEW_LINE> <INDENT> ckpt = tf.train.get_checkpoint_state(FLAGS.model) <NEW_LINE> if ckpt and ckpt.model_checkpoint_path: <NEW_LINE> <INDENT> ckpt_path=ckpt.model_checkpoint_path <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeError('No checkpoint file found') <NEW_LINE> <DEDENT> return...
Get the checkpoint path from the given model output directory
625941db82261d6c526ab782
def eqri(self, a, b, c): <NEW_LINE> <INDENT> self.registers[c] = 1 if self.registers[a] == b else 0
eqri (equal register/immediate) sets register C to 1 if register A is equal to value B. Otherwise, register C is set to 0.
625941db566aa707497f4845
@login_required(login_url='/denied/') <NEW_LINE> def latest(request, page, cat): <NEW_LINE> <INDENT> if int(cat) == 0: <NEW_LINE> <INDENT> occurrences = Occurrences.objects.filter( bullshit=0, validated=1).order_by('-created_at') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> category = Categories.objects.get(id=int(cat...
latest(request, page, cat) ------------------- Description: Return latest occurrences by creation date Url: /hope/occurrences/latest/{page}/{cat} Return: HttpResponse Object Author: Miguel Loureiro <mlimaloureiro@outlook.com>, Andre Goncalves <andre@gon...
625941dbbaa26c4b54cb13fd
def class_if_y0(self, index, dataset, labels, k): <NEW_LINE> <INDENT> dataset_size = dataset.shape[0] <NEW_LINE> diff_mat = tile(index, (dataset_size, 1)) - dataset <NEW_LINE> sq_diff_mat = diff_mat ** 2 <NEW_LINE> sq_distances = sq_diff_mat.sum(axis=1) <NEW_LINE> distances = sq_distances ** 0.5 <NEW_LINE> sorted_disti...
选择距离最少的 k 个点 :param index: 分类的输入向量 :param dataset:训练样本集 :param labels:标签向量 :param k:选择最近邻居的数目 :return:
625941dbcc40096d61595c2f