code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def getMultiAdapter(objects, interface, name=_u('')): <NEW_LINE> <INDENT> pass | Look for a multi-adapter to an interface for multiple objects
If a matching adapter cannot be found, a ComponentLookupError
is raised. | 625941ec1b99ca400220afb7 |
def _print_csv(result): <NEW_LINE> <INDENT> if type(result) is not list: <NEW_LINE> <INDENT> raise TypeError("output not able to be displayed as CSV.") <NEW_LINE> <DEDENT> first_line = result[0] <NEW_LINE> w = csv.DictWriter(sys.stdout, fieldnames=sorted(first_line.keys())) <NEW_LINE> w.writeheader() <NEW_LINE> for lin... | Print a JSON list of JSON objects in CSV format. | 625941ec1d351010ab85601f |
def run_command( commands, args, cwd=None, verbose=False, hide_stderr=False, env=None, ): <NEW_LINE> <INDENT> assert isinstance(commands, list) <NEW_LINE> process = None <NEW_LINE> for command in commands: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> dispcmd = str([command] + args) <NEW_LINE> process = subprocess.Popen... | Call the given command(s). | 625941ec5fdd1c0f98dc0739 |
def appoint_owner_to_store(self, store_id, owner, to_appoint): <NEW_LINE> <INDENT> return jsons.dumps( self.get_store(store_id).appoint_owner(owner, to_appoint, self.users_manager, self.publisher)) | Args:
store_id:
owner:
to_appoint: | 625941ecd53ae8145f87a76a |
def test_infinity(self): <NEW_LINE> <INDENT> inf = 1e1000 <NEW_LINE> values = [ [inf, inf, inf], [1e6, 1e300, 1e500], [2**1000, 2**1000, inf], [self.max_half * 10 , self.max_float * 10 , self.max_double * 10], [(1 + 2 - 2**-10) * 2**15, (1 + 2 - 2**-23) * 2**127, (1 + 1 + (1 - 2**-52)) * 2**1023], ] <NEW_LINE> result =... | Checks to see if overflow values are detected correctly. | 625941ec0fa83653e46574bc |
def singlePossibilityRules(self, fbRules=None): <NEW_LINE> <INDENT> if fbRules is None: <NEW_LINE> <INDENT> fbRules = rules.Rules() <NEW_LINE> <DEDENT> singlePossibRules = [ (fbRules.forbidIncompletePossibilities, possibility.isIncomplete, False, [self.pitchNamesInChord]), (True, possibility.upperPartsWithinLimit, True... | A framework for storing single possibility rules and methods to be applied
in :meth:`~music21.figuredBass.segment.Segment.allCorrectSinglePossibilities`.
Takes in a :class:`~music21.figuredBass.rules.Rules` object, fbRules.
If None then a new rules object is created.
Items are added within this method in the following... | 625941ec21a7993f00bc81fd |
def obsoletes(self): <NEW_LINE> <INDENT> self._gatherDepInfo() <NEW_LINE> return self._obsoletes | Get package Obsoletes as list of
(name, flags, (epoch, version, release)) tuples. | 625941ecff9c53063f47c6f5 |
def __resolve_parenting(self, blender_object: bpy.types.Object) -> Node: <NEW_LINE> <INDENT> parent_candidates = self.root.find_from_blender_object(blender_object.parent) <NEW_LINE> return parent_candidates[0] if parent_candidates else self.root | Attempts to find a parent for the argument in the graph. Uses the root node if no candidate node is found at first | 625941ec796e427e537b0ace |
def end(self,name): <NEW_LINE> <INDENT> self.callback('end_',name) | Helper methods | 625941ec442bda511e8be915 |
def sankey_format_deal(self): <NEW_LINE> <INDENT> columns_name = self.frame.columns.tolist() <NEW_LINE> layout_name = " - ".join(columns_name) <NEW_LINE> self.frame[columns_name[0]] = self.frame[columns_name[0]].fillna(f'{columns_name[0]}_空白') <NEW_LINE> self.frame[columns_name[1]] = self.frame[columns_name[1]].fillna(... | sankey配置文件的预处理,返回sankey图标题名,标签中文名列表,颜色列表,source值和target值,以及权重value
:return:layout_name,lable,color,source,target,value | 625941ec7d847024c06be7c4 |
def doBlob_DeleteBlob(self,blobUri): <NEW_LINE> <INDENT> params = {} <NEW_LINE> params['context'] = self.context <NEW_LINE> params['blobUri'] = self.fixTypes(blobUri) <NEW_LINE> ret= self.runMultipart("/blob", "DELETEBLOB", params) <NEW_LINE> return ret['response'] | Removes a blob from the backing store. There is no undo. | 625941ece5267d203edce19a |
def wrapped(): <NEW_LINE> <INDENT> return func(*args, **kwargs) | Function for timeit. | 625941ec3eb6a72ae02ec9ef |
def copy(self): <NEW_LINE> <INDENT> return Position(self.fen) | Gets a copy of the position. The copy will not change when the
original instance is changed.
:return:
An exact copy of the positon. | 625941ecb57a9660fec33d8f |
def load_served(gens, t_lines, load): <NEW_LINE> <INDENT> gen_import = 0 <NEW_LINE> for g in gens[0:2]: <NEW_LINE> <INDENT> if g.state: <NEW_LINE> <INDENT> gen_import += 75 <NEW_LINE> <DEDENT> <DEDENT> trans_capacity = 0 <NEW_LINE> for t in t_lines: <NEW_LINE> <INDENT> if t.state: <NEW_LINE> <INDENT> trans_capacity += ... | Determine whether or not load can be served depending on the
state of the generators, transmission lines, and system loading.
:param gens: List of the three generators. Each generator is
represented by a TwoStateComponent object. gens[0] is G1,
gens[1] is G2, and gens[2] is G3.
:param t_lines: List of th... | 625941ec3539df3088e2e850 |
def main(): <NEW_LINE> <INDENT> optmgr = WMArchiveOptionParser() <NEW_LINE> opts, _ = optmgr.get_opt() <NEW_LINE> data = get_data(opts.host, opts.spec, opts.ckey, opts.cert, opts.verbose) <NEW_LINE> print(json.dumps(data)) | Main function | 625941ec0383005118ecfae5 |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ApTravels.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you su... | Run administrative tasks. | 625941ec925a0f43d254a380 |
def removeColumns(self, p_int, p_int_1, QModelIndex_parent=None, *args, **kwargs): <NEW_LINE> <INDENT> pass | QStandardItemModel.removeColumns(int, int, QModelIndex parent=QModelIndex()) -> bool | 625941ecab23a570cc25068b |
def action(self, s, x): <NEW_LINE> <INDENT> return self.retract(self.ambient().action(s, self.lift(x))) | EXAMPLES::
sage: M = Semigroups().SetsWithAction().example(); M
Representation of the monoid generated by <2,3> acting on Z/10 Z by multiplication
sage: M.classes()
[{1, 3, 9, 7}, {5}, {0}, {8, 2, 4, 6}]
sage: N = M.submodule(Set([2, 4, 6, 8]))
sage: list(N)
[0, 1, 3, 5, 7, 9] | 625941ecfff4ab517eb2f944 |
def get_ipts_dir(self): <NEW_LINE> <INDENT> return self._iptsDir | Get directory for IPTS
:return: | 625941ecd8ef3951e3243a42 |
def get_labels_str(self, metric, inst=None, curr=True, combine=True): <NEW_LINE> <INDENT> if curr: <NEW_LINE> <INDENT> ref = self.res_labels[metric] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ref = self.labels[list(self.util.metrics.keys()).index(metric)] <NEW_LINE> <DEDENT> if inst in (None, pmapi.c_api.PM_IN_NULL)... | Return labels as string | 625941ec7d847024c06be7c5 |
def Kappa0(hl, vs, qs, z=[]): <NEW_LINE> <INDENT> lnum = len(hl) <NEW_LINE> hl = _np.array(hl) <NEW_LINE> vs = _np.array(vs) <NEW_LINE> qs = _np.array(qs) <NEW_LINE> if not z: <NEW_LINE> <INDENT> z = _np.sum(hl) <NEW_LINE> <DEDENT> par = z/(vs*qs) <NEW_LINE> kappa0 = DepthAverage(lnum, hl, par, z) <NEW_LINE> return kap... | This function calucalted the attenuation parameter
Kappa(0) from a soil profile down to an arbitrary
depth z. | 625941ec44b2445a33932596 |
def test_beer(self): <NEW_LINE> <INDENT> results = RateBeer().beer("/beer/new-belgium-tour-de-fall/279122/") <NEW_LINE> self.assertIsNotNone(results) <NEW_LINE> self.assertDictContainsSubset({ 'name': u'New Belgium Tour de Fall', 'brewery': u'New Belgium Brewing Company', 'brewery_url': u'/brewers/new-belgium-brewing-c... | Make sure the results for a beer contain the expected data | 625941ec3346ee7daa2b3275 |
def value(self, halo): <NEW_LINE> <INDENT> return self.values([halo])[:,0] | Return the value of this calculation applied to the given halo | 625941ec046cf37aa974d247 |
def md5ns_in(res): <NEW_LINE> <INDENT> f = open("5ns.in", 'w') <NEW_LINE> f.write('5ns md simulation\n&cntrl\n' 'imin=0, irest=1, ntx=7, \n' 'ntb=2, pres0=1.0, ntp=1, \n' 'ntt=1, temp0=300.0, tautp=5.0, \n' 'ntc=2, ntf=2,cut=9.0, \n' 'nstlim=2500000, dt=0.002, ' 'ntpr=20000, ntwx=10000, ntwr=500000\n/') | write the 5ns md simulation input file | 625941ecb830903b967e9e0a |
def degree(self): <NEW_LINE> <INDENT> return self._element.degree() | Return the degree of the (embedding) polynomial space. | 625941ec6e29344779a62b15 |
def getState(self, *args, **kwargs): <NEW_LINE> <INDENT> return _VISHNU.Queue_getState(self, *args, **kwargs) | getState(self) -> QueueStatus | 625941ec26238365f5f0f37a |
def Get_5GNR_BWP_Ch_Mapping(self): <NEW_LINE> <INDENT> rdStr = self.queryFloatArry(f'CONF:NRMM:MEAS:CC{self.cc}:ALL{self.alloc}:PUSC?') <NEW_LINE> return rdStr[0] | PUSCH Mapping | 625941ec4d74a7450ccd46ca |
def splitArray(self, nums, m): <NEW_LINE> <INDENT> sumDict = {} <NEW_LINE> index = 0 <NEW_LINE> currSum = 0 <NEW_LINE> for num in nums: <NEW_LINE> <INDENT> currSum += num <NEW_LINE> sumDict[index] = currSum <NEW_LINE> index += 1 <NEW_LINE> <DEDENT> if m == 1: <NEW_LINE> <INDENT> return sumDict[len(sumDict)-1] <NEW_LINE... | :type nums: List[int]
:type m: int
:rtype: int | 625941ec45492302aab5e7cd |
def put(self, request, project, key_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> key = ProjectKey.objects.get( project=project, public_key=key_id, roles=F("roles").bitor(ProjectKey.roles.store) ) <NEW_LINE> <DEDENT> except ProjectKey.DoesNotExist: <NEW_LINE> <INDENT> raise ResourceDoesNotExist <NEW_LINE> <DEDENT> ... | Update a Client Key
```````````````````
Update a client key. This can be used to rename a key.
:pparam string organization_slug: the slug of the organization the
client keys belong to.
:pparam string project_slug: the slug of the project the client keys
... | 625941ec10dbd63aa1bd30a7 |
def orphanet_genealacart(taxon_id=9606, add_absenece=True): <NEW_LINE> <INDENT> if taxon_id != 9606: <NEW_LINE> <INDENT> raise EnvironmentError('Only supports taxon 9606, Homo sapiens') <NEW_LINE> <DEDENT> p = inout.get_path( 'geisen', 'genealacart/genealacart_orphanet_kind.gz') <NEW_LINE> df = pd.read_csv(p) <NEW_LINE... | Orphan diseases
Source: Orphanet through Genealacart
Input:
taxon_id int
add_absence bool; default is True; add genes for which there
is no disease entry
Output:
dataframe | 625941ec8a349b6b435e8677 |
def createExperiment(self, expId, expName): <NEW_LINE> <INDENT> if len(expId) > 41: <NEW_LINE> <INDENT> expId = expId[0:41] <NEW_LINE> <DEDENT> expId = expId + "_" + self.getCustomTimeStamp() <NEW_LINE> self._logger.info("Register experiment %s" % expId) <NEW_LINE> exp = self._transaction.createNewExperiment(expId, "FA... | Create an experiment with given Experiment ID extended with the addition
of a string composed from current date and time.
@param expID, the experiment ID
@param expName, the experiment name | 625941ec99fddb7c1c9de893 |
def test_requeue(rejester_queue): <NEW_LINE> <INDENT> rejester_queue.add_item('a', 3) <NEW_LINE> rejester_queue.add_item('b', 2) <NEW_LINE> item = rejester_queue.check_out_item(300) <NEW_LINE> assert item == 'a' <NEW_LINE> rejester_queue.return_item(item, 3) <NEW_LINE> item = rejester_queue.check_out_item(300) <NEW_LIN... | Pull items out and put them back | 625941ec94891a1f4081bfb0 |
@click.command() <NEW_LINE> @click.argument("city", type=str) <NEW_LINE> @click.option("--random_seed", default=None, type=int) <NEW_LINE> @click.option("--max-num-days", default=1, type=int) <NEW_LINE> @click.option("--infection-rate", default=0.5, type=float) <NEW_LINE> @click.option("--days-contagious", default=2, t... | Process the command-line arguments and do the work. | 625941ec498bea3a759b9fb2 |
def plot_solution(cities, sol): <NEW_LINE> <INDENT> plt.figure('Traveling Salesman Problem') <NEW_LINE> plt.plot(cities[:, 0], cities[:, 1], 'b*') <NEW_LINE> plt.plot(sol[:, 0], sol[:, 1], '-rx') <NEW_LINE> plt.title('Traveling Salesman Problem') <NEW_LINE> plt.grid() <NEW_LINE> plt.show() | Plots the solution to the Traveling Salesman problem optimized through a Kohonen neural network | 625941ec82261d6c526ab9ac |
def example_handler(sock, arg): <NEW_LINE> <INDENT> if arg.upper() == 'Q': <NEW_LINE> <INDENT> sock.pop_ih() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sock.send("You typed " + arg + ". Q to quit.") | used as an example of how to interact with the input handler stack | 625941ec4428ac0f6e5bacfb |
def getAcceleration(self): <NEW_LINE> <INDENT> timeGap = self.speed * self.timeHeadAway / Traffic.SECOND_PER_HOUR <NEW_LINE> freeRoadCoeff = self.calcFreeRoadCoeff() <NEW_LINE> busyRoadCoeff = self.calcBusyRoadCoeff(timeGap) <NEW_LINE> intersectionCoeff = self.calcIntersectionCoeff(timeGap) <NEW_LINE> coeff = 1 - freeR... | Get the acceleration factor of this car.
For the detail of this model, refer to https://en.wikipedia.org/wiki/Intelligent_driver_model
It will take the following factors into consideration:
1. the distance to the intersection line
2. the distance to the front car (if there is a car in front of this car)
3. the speed di... | 625941eca79ad161976cc64a |
def testControllerApp(self): <NEW_LINE> <INDENT> import tw2.core <NEW_LINE> from tw2.core.middleware import register_controller, TwMiddleware <NEW_LINE> controller_response = Response("CONTROLLER") <NEW_LINE> class WidgetMock(tw2.core.Widget): <NEW_LINE> <INDENT> def request(self, request): <NEW_LINE> <INDENT> return c... | controllerapp should dispatch to an object having id, and a
request method taking a webob request based on path_info of
request. | 625941ec2eb69b55b151cdbb |
def _connection(self, region=None): <NEW_LINE> <INDENT> r = region or 'us-east-1' <NEW_LINE> if r not in self._conns: <NEW_LINE> <INDENT> self._conns[r] = vpc.connect_to_region( r, aws_access_key_id=self.aws_access_key_id, aws_secret_access_key=self.aws_secret_access_key, ) <NEW_LINE> <DEDENT> return self._conns[r] | Returns a connection "pool" (just a dict with an object per region
used) to the calling code | 625941ecb7558d58953c540e |
def save_config(self, event=None): <NEW_LINE> <INDENT> folder, config_filename = self.get_storage_location() <NEW_LINE> mkdir_p(folder) <NEW_LINE> profile_data = [p.get_data() for p in self.profile_panels] <NEW_LINE> config_data = dict(show_console=self.is_console_visible(), show_summary=self.is_summary_visible(), prof... | Save the current miner profiles to our config file in JSON format. | 625941eca8ecb033257d35d0 |
def calc_gradient_avg(_data, _row, _column_name, _ratio = 4): <NEW_LINE> <INDENT> actual_value = _row[_column_name] <NEW_LINE> index_row = _data.index.get_loc(_row.name) <NEW_LINE> if (index_row - _ratio) >= 0: <NEW_LINE> <INDENT> value_after_ratio = 0 <NEW_LINE> for prec_row in range(index_row - _ratio, index_row): <N... | Ritorna il valore gradiente(oscillazione) di un attributo rispetto un certo intervallo di tempo
considerando la media dei valori precedenti.
Utilizzato per creare un attributo temporale artificiale per il modello neurale.
Necessita _data, intero dataset, per recupero delle row successive, no controllo temporale succes... | 625941ec8a43f66fc4b54564 |
def acceleration(v,x): <NEW_LINE> <INDENT> Ft=ms2kmh*eta*power(x)/(v+tiny) <NEW_LINE> Fmax=g*Mta*mu <NEW_LINE> F=min(Ft,Fmax) <NEW_LINE> Ra= c1*Cd*Ch*Area*v*v <NEW_LINE> Rg = g*M*(grade+friction) <NEW_LINE> R= Ra+Rg <NEW_LINE> if v >= maxVelo: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r... | calculates acceleration for a truck moving at speed V | 625941ecbaa26c4b54cb161f |
def _import_names(module_name, names=()): <NEW_LINE> <INDENT> module = __import__(module_name, {}, {}, names) <NEW_LINE> if not names: <NEW_LINE> <INDENT> for submodule_name in module_name.split('.')[1:]: <NEW_LINE> <INDENT> module = getattr(module, submodule_name) <NEW_LINE> <DEDENT> if hasattr(module, '__all__'): <NE... | Import a module and assign named attributes into namespace.
Args:
module_name: The string module name.
names: A limiting list of names to import from module_name. If
empty (the default), all names are imported from the module
similar to a "from foo.bar import *" statement.
Raises:
error.Au... | 625941ec8a43f66fc4b54565 |
def pa_value(one, two, graph): <NEW_LINE> <INDENT> values_pa = nx.preferential_attachment(graph, [(one, two)]) <NEW_LINE> value_pa = 0 <NEW_LINE> for u, v, p in values_pa: <NEW_LINE> <INDENT> value_pa = p <NEW_LINE> <DEDENT> return value_pa | Funcion que devuelve el numero de vecinos en comun de esos dos nodos | 625941ec8e05c05ec3eea87e |
def findBottomLeftValue(self, root): <NEW_LINE> <INDENT> return self.levelOrder(root)[-1][0] | :type root: TreeNode
:rtype: int | 625941ec090684286d50f1f2 |
def simulate(self, x, p0, only_forward=False): <NEW_LINE> <INDENT> p, T, lnq = self.separate(x, p0) <NEW_LINE> fwd, jac = [], [] <NEW_LINE> for model, angles in self.mod_ang: <NEW_LINE> <INDENT> if only_forward: <NEW_LINE> <INDENT> result = model.forward(angles=angles, p=p, T=T, lnq=lnq) <NEW_LINE> <DEDENT> else: <NEW_... | Calculate brightness temperatures and Jacobian. | 625941eccad5886f8bd274dd |
def backward(self, loss): <NEW_LINE> <INDENT> scaled_loss = (loss.float()) * self.cur_scale <NEW_LINE> scaled_loss.backward() | :attr:`backward` performs the following conceptual steps:
1. fp32_loss = loss.float()
2. scaled_loss = fp32_loss*loss_scale
3. scaled_loss.backward(), which accumulates scaled gradients into the ``.grad`` attributes of the model's fp16 leaves | 625941ec9f2886367277ad8e |
def test_metadata_split_to_dict(): <NEW_LINE> <INDENT> pc_axis = pyaxis.read( 'https://www.ine.es/jaxi/files/_px/es/px/t20/e301/matri/a2000/l0/' '14001.px?nocab=1', 'iso-8859-15') <NEW_LINE> metadata_elements, raw_data = pyaxis.metadata_extract(pc_axis) <NEW_LINE> metadata = pyaxis.metadata_split_to_dict(metadata_eleme... | Should split metadata into a dictionary. | 625941ec29b78933be1e5bab |
def test_drmaa_time_string(self): <NEW_LINE> <INDENT> t_new = convert_to_drmaa_time("4-10:00:00") <NEW_LINE> self.assertEqual(t_new, "106:00:00") <NEW_LINE> t_new = convert_to_drmaa_time("10:00:00") <NEW_LINE> self.assertEqual(t_new, "10:00:00") <NEW_LINE> t_new = convert_to_drmaa_time("3:00:00") <NEW_LINE> self.assert... | Test parsing of time string formatted as d-hh:mm:ss and translate days to hours | 625941ec293b9510aa2c3796 |
def test_threadNum(self): <NEW_LINE> <INDENT> task_list = MethodThreader.TaskList() <NEW_LINE> task_list.addTaskToList(jobOne, {}, name='1') <NEW_LINE> task_list.addTaskToList(jobOne, {}, name='2') <NEW_LINE> task_list.addTaskToList(jobOne, {}, name='3') <NEW_LINE> task_list.addTaskToList(jobOne, {}, name='4') <NEW_LIN... | test valid and invalid thread numbers | 625941ecff9c53063f47c6f6 |
def xyz2img(img, xyz, color, level=2): <NEW_LINE> <INDENT> for pos, size in xyz: <NEW_LINE> <INDENT> x, y, z = pos <NEW_LINE> assert 1 <= size <= 16, size <NEW_LINE> d = 2 ** (16 - size) <NEW_LINE> if z <= level < z + d: <NEW_LINE> <INDENT> if d > 100: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> px = SLICE_OCTOMAP... | Draw given list of voxels into existing image
:param img: I/O image
:param xyz: list of voxels (xyz and "size")
:param color: value 0..255 to be assigned to voxels at given level
:param level: Z-level for the cut
:return: updated image | 625941ec30dc7b7665901e66 |
def forward(self, x): <NEW_LINE> <INDENT> return self.linear(self.phi(x, X=self.X)) | Parameters
----------
x : Tensor, shape (batch_size, dim)
Returns
-------
y : Tensor, shape (batch_size, n_out) | 625941ec925a0f43d254a381 |
@tile_endpoints.route('/gee/<layer>/expire-cache', strict_slashes=False, methods=['DELETE']) <NEW_LINE> @is_microservice <NEW_LINE> def expire_cache(layer): <NEW_LINE> <INDENT> logging.info('[tile_router - expire_cache]: Expire cache tile for layer {}'.format(layer)) <NEW_LINE> logging.debug('[tile_router - expire_cach... | Expire cache tile layer Endpoint | 625941ec0a366e3fb873ed24 |
def _modified_system_iter(self, group): <NEW_LINE> <INDENT> self._add_mod_parallel_groups(group) <NEW_LINE> allpaths = set() <NEW_LINE> for path in self._modified_systems: <NEW_LINE> <INDENT> allpaths.update(all_ancestors(path)) <NEW_LINE> <DEDENT> len_prefix = len(group.pathname) + 1 if group.pathname else 0 <NEW_LINE... | Iterate over modified systems in bottom up order.
Parameters
----------
group : <Group>
Group that has just been configured.
Yields
------
<System>
Systems that have been modified. | 625941ec23e79379d52eea62 |
def turn_off(self): <NEW_LINE> <INDENT> self.cast.quit_app() | Service to exit any running app on the specimedia player ChromeCast and
shows idle screen. Will quit all ChromeCasts if nothing specified. | 625941ec56b00c62f0f14b62 |
def basic_setup(): <NEW_LINE> <INDENT> _set('lines.color', 'black') <NEW_LINE> _set('patch.facecolor', 'black') | System wide matplotlib configuration.
| 625941ecc4546d3d9de72f3e |
@pytest.mark.parametrize("quality_bitmask,answer", [('hardest', 2661), ('hard', 2706), ('default', 2917), (None, 3279), (1, 3279), (100, 3252), (2096639, 2661)]) <NEW_LINE> def test_bitmasking(quality_bitmask, answer): <NEW_LINE> <INDENT> lcf = KeplerLightCurveFile(TABBY_Q8, quality_bitmask=quality_bitmask) <NEW_LINE> ... | Test whether the bitmasking behaves like it should | 625941ec167d2b6e3121909a |
def calcGrayHist(image): <NEW_LINE> <INDENT> rows, cols = img.shape <NEW_LINE> grayHist = np.zeros([256], np.uint64) <NEW_LINE> for r in range(rows): <NEW_LINE> <INDENT> for c in range(cols): <NEW_LINE> <INDENT> grayHist[image[r][c]] += 1 <NEW_LINE> <DEDENT> <DEDENT> return grayHist | 统计像素值
:param image:
:return: | 625941eccad5886f8bd274de |
def is_admin(): <NEW_LINE> <INDENT> return is_logged_in() and login.current_user.user_db.admin | Convenient method if currently logged user is admin | 625941ec097d151d1a22335c |
def discreteGridPosToID(x: int, y: int = 0, width: int = 0, z: int = 0, height: int = 0): <NEW_LINE> <INDENT> return (z * width * height) + (y * width) + x | Returns a unique number of based on the x, y and z coordinates entered.
Uniqueness is dimension dependent | 625941ec6fece00bbac2dc4a |
def type_raw(self, s): <NEW_LINE> <INDENT> self.simplecmd("str", s) | Type in a string directly | 625941ecbf627c535bc136d5 |
def getTile(self, x, y): <NEW_LINE> <INDENT> t = self.tiles[y][x] <NEW_LINE> if t == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if t == 0x5: <NEW_LINE> <INDENT> return curses.ACS_VLINE <NEW_LINE> <DEDENT> if t == 0xa: <NEW_LINE> <INDENT> return curses.ACS_HLINE <NEW_LINE> <DEDENT> if t == 0x3: <NEW_LINE> <INDE... | Returns the curses code for the tile at position (x, y). | 625941ec8c0ade5d55d3eec5 |
def has_inlaat_structure(self, number): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> Structure.objects.get( code=self.code_inlaat_structure(number)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | Return true if area has 'inlaat' structure of the passed number. | 625941ecbe7bc26dc91cdafc |
def find_database_index(directory, database_type): <NEW_LINE> <INDENT> index="" <NEW_LINE> if database_type == "bmtagger": <NEW_LINE> <INDENT> all_extensions=config.bmtagger_db_endings <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> all_extensions=config.bowtie2_db_endings+[config.bowtie2_large_index_ext] <NEW_LINE> <DED... | Search through the directory for the name of the database index files
Or if a file name is provided check it is a database index
For bowtie2 and bmtagger databases | 625941ec63d6d428bbe449f6 |
def _clean_hash_ring(self): <NEW_LINE> <INDENT> pass | Don't clean the hash ring.
If this method was not overriden, cleanup would be performed when
calling the db sync and running neutron server would lose all the nodes
from the ring. | 625941ec0fa83653e46574bd |
def test_grade_group_1(self): <NEW_LINE> <INDENT> self.user_login(username='admin', password='admin') <NEW_LINE> msg = Call_Group(self.driver).grade_group_1() <NEW_LINE> self.assertEqual(msg, True) | 检查进入分级组管理页面 点击添加 添加一个正确的组号 验证是否添加成功 而后删除该号码 使用操作栏图标删除 | 625941ec3d592f4c4ed1d565 |
def genPoint(self, idx): <NEW_LINE> <INDENT> x = self._rand.uniform(-2*self._radius, 2*self._radius) <NEW_LINE> y = self._rand.uniform(-2*self._radius, 2*self._radius) <NEW_LINE> if x*x + y*y > self._radiusPow: <NEW_LINE> <INDENT> color = COLORS[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> color = COLORS[1] <NEW_LI... | Circle with center in [0,0] and specified 'radius'.
The generated dataset has a form of square (2*radius) x (2*radius) with center in [0,0]. | 625941ec6aa9bd52df0372ad |
def readuseragentfile(self): <NEW_LINE> <INDENT> with open(self.useragentFile) as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> self.useragent_list.append(line.strip('\n')) <NEW_LINE> <DEDENT> return len(self.useragent_list) | Read to useragent_list from file | 625941ec566aa707497f4a67 |
def get_locationAreaCode(self): <NEW_LINE> <INDENT> return self._lac | Returns the Location Area Code (LAC). The LAC is a unique identifier for each
place within a country.
@return an integer corresponding to the Location Area Code (LAC). | 625941ec5fcc89381b1e1bc9 |
def items_equal(expected): <NEW_LINE> <INDENT> def _items_equal(actual): <NEW_LINE> <INDENT> sorted_expected = sorted(expected) <NEW_LINE> sorted_actual = sorted(actual) <NEW_LINE> if sorted_expected != sorted_actual: <NEW_LINE> <INDENT> raise BeamAssertException( 'Failed assert: %r != %r' % (sorted_expected, sorted_ac... | Returns a function for checking expected and actual have the same items. | 625941ecdd821e528d63b6aa |
def play_round(agents, num_matches): <NEW_LINE> <INDENT> agent_1 = agents[-1] <NEW_LINE> wins = 0. <NEW_LINE> total = 0. <NEW_LINE> print("\nPlaying Matches:") <NEW_LINE> print("----------") <NEW_LINE> print("|{:>10} vs:|win/total |win rate\t|".format(agent_1.name)) <NEW_LINE> print("|---------------|-----------|-----... | Play one round (i.e., a single match between each pair of opponents) | 625941ec711fe17d82542865 |
@raises(TypeError) <NEW_LINE> def test_set_seed_fails_if_float(): <NEW_LINE> <INDENT> m = Concrete() <NEW_LINE> seed = 42.0 <NEW_LINE> m.seed = seed | Test that the seed property fails with a float. | 625941ecd58c6744b4258163 |
def merge(self, element, check=True, delete=True): <NEW_LINE> <INDENT> poset = self.poset <NEW_LINE> if poset._merge_ is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self_element = self.element <NEW_LINE> if check: <NEW_LINE> <INDENT> if not poset._can_merge_(self_element, element): <NEW_LINE> <INDENT> raise Ru... | Merge the given element with the element contained in this
shell.
INPUT:
- ``element`` -- an element (of the poset).
- ``check`` -- (default: ``True``) if set, then the
``can_merge``-function of :class:`MutablePoset` determines
whether the merge is possible. ``can_merge`` is ``None`` means
that this check is a... | 625941ec379a373c97cfb04d |
def __init__(self, c_in, c_out, device, ks=5): <NEW_LINE> <INDENT> super(SpatialConvLayer, self).__init__() <NEW_LINE> self.c_in = c_in <NEW_LINE> self.c_out = c_out <NEW_LINE> self.ks = ks <NEW_LINE> self.theta = nn.Parameter(torch.FloatTensor(ks * c_in, c_out)).double().to(device) <NEW_LINE> self.conv_reshape = nn.Co... | Args:
c_in (int): number of input channels per node
c_out ([type]): number of output channels per node
ks (int, optional): size of spatial kernel. Defaults to 5. | 625941ec9f2886367277ad8f |
def __init__(self, start_time, end_time): <NEW_LINE> <INDENT> start_time = datetime.strptime(start_time, TIME_FORMAT) <NEW_LINE> end_time = datetime.strptime(end_time, TIME_FORMAT) <NEW_LINE> if Meeting.validate_time_args(start_time, end_time): <NEW_LINE> <INDENT> self.start_time = start_time <NEW_LINE> self.end_time =... | A new Meeting object, will throw a ValueError on bad time values. | 625941ec851cf427c661aa10 |
def centers(self): <NEW_LINE> <INDENT> bin_centers = np.zeros(len(self) - 1, float) <NEW_LINE> if self.dataType == int: <NEW_LINE> <INDENT> for i in range(len(self) - 2): <NEW_LINE> <INDENT> bin_centers[i] = 0.5 * (ceil(self[i + 1]) - 1 + ceil(self[i])) <NEW_LINE> <DEDENT> bin_centers[-1] = 0.5 * (floor(self[-1]) + cei... | Return bin centers as array. | 625941ec31939e2706e4d368 |
def rebase_y_axis(self, height): <NEW_LINE> <INDENT> self.y = height - self.y | Rebase the y coordinate in the label. | 625941ec656771135c3ebd7b |
def delete_physical_machine(self, physical_machine_id:str): <NEW_LINE> <INDENT> response = requests.delete(f'{self.url}/rest/inventory/v1/physical-machines/{physical_machine_id}', verify=False, headers=self.access_token) <NEW_LINE> if response.status_code == 400: <NEW_LINE> <INDENT> error_message = (response.json())["... | Deletes the Physical Machine.
Available for Horizon 8 2012 and later. | 625941ec1d351010ab856020 |
def get_all_saved_models(model_dir): <NEW_LINE> <INDENT> saved_models = [os.path.join(model_dir, f) for f in os.listdir(model_dir) if os.path.isfile(os.path.join(model_dir, f)) and re.match('^.*iter[0-9]+\.*npz$', f)] <NEW_LINE> return saved_models | Get the absolute paths to all saved models in `model_dir`
models must be saved as *iter*.npz for this to work. | 625941ec711fe17d82542866 |
def set_title(self, title): <NEW_LINE> <INDENT> self.doc.find_or_create_child(self.sheet_tag, "title").text = title | Change sheet title (label displayed on sheet tab). | 625941ec236d856c2ad44ce7 |
def test_get_highlights(client): <NEW_LINE> <INDENT> rv = client.get('/highlights/2017/20391') <NEW_LINE> assert rv.status_code == 200 <NEW_LINE> assert rv.content_type == 'application/json' <NEW_LINE> data = json.loads(rv.data) <NEW_LINE> assert list(data.keys()) == ['copyright', 'link', 'editorial', 'media', 'highlig... | Test Retrieving Game Highlights | 625941ec1d351010ab856021 |
def computeActionFromQValues(self, state): <NEW_LINE> <INDENT> legalActions = self.getLegalActions(state) <NEW_LINE> if not legalActions: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return max(legalActions, key=lambda action: self.getQValue(state, action)) | Compute the best action to take in a state. Note that if there
are no legal actions, which is the case at the terminal state,
you should return None. | 625941ec8da39b475bd65480 |
def grammar(self, *target_tags): <NEW_LINE> <INDENT> tagged_strings = self.grammar_raw <NEW_LINE> target_tags = set(target_tags) <NEW_LINE> return [string for tags, string in tagged_strings if target_tags.issubset(tags)] | Return the information from grammar section
Example:
>>> word_laufen.grammar(duden.SINGULAR, duden.PRASENS, duden.INDIKATIV, duden.PERSON_3)
['er/sie/es läuft'] | 625941ec5fdd1c0f98dc073b |
def from_Y_to_label(y, i): <NEW_LINE> <INDENT> label = str(i) + '_' <NEW_LINE> for j in range(len(all_identity_columns)): <NEW_LINE> <INDENT> if y[j][i]: <NEW_LINE> <INDENT> label += all_identity_columns[j] + '_' <NEW_LINE> <DEDENT> <DEDENT> return label | Output example : '35_asian_Christian' means that review indexed with 35 mentions
both asian and christian minorities. | 625941ec4e696a04525c9953 |
def setup_s3_backend(): <NEW_LINE> <INDENT> s3_client = boto3.client('s3') <NEW_LINE> dynamodb_client = boto3.client('dynamodb') <NEW_LINE> s3_bucket = str(uuid.uuid1()) <NEW_LINE> s3_prefix = str(uuid.uuid1()) + "/" + str(uuid.uuid1()) <NEW_LINE> s3_client.create_bucket(Bucket=s3_bucket) <NEW_LINE> flags_table = str(u... | Create the AWS resources for an S3 key-value backend, and return the event body template | 625941ec57b8e32f524839a4 |
def _combine_steering_vectors(self,sv_ft,sv_st,sv_tx,sv_rx): <NEW_LINE> <INDENT> return dot(kronv(kronv(kronv(sv_st,sv_ft),sv_rx),ones(self.Nt)),sv_tx) | Phased array version, i.e. uncoded superposition of tx antennas.
sv_ft -- fast-time steering vector
sv_st -- slow-time steering vector
sv_rx -- steering vector rx-channels
sv_tx -- steering vector tx-antennas
return -- combined steering vector for fast time, slow time, rx channels, and tx a... | 625941ec23849d37ff7b3591 |
def mouseDoubleClickEvent(self, QMouseEvent): <NEW_LINE> <INDENT> self.pixmap().save('./Temps/ForExternalProgram.png') <NEW_LINE> Image.open("./Temps/ForExternalProgram.png").show() | Open the image with Imagemagick
:param QMouseEvent:
:return: | 625941ec5166f23b2e1a565f |
def is_valid_datapath_id(datapath_id): <NEW_LINE> <INDENT> m = "^[0-9a-f]{16}$" <NEW_LINE> return (isinstance(datapath_id, six.string_types) and re.match(m, datapath_id.lower())) | Verify the format of an OpenFlow datapath_id.
Check if a datapath_id is valid and contains 16 hexadecimal digits.
Datapath ID format: the lower 48-bits are for a MAC address,
while the upper 16-bits are implementer-defined.
:param datapath_id: OpenFlow datapath_id to be validated.
:returns: True if valid. False if no... | 625941ec50485f2cf553d2a2 |
def write(temp): <NEW_LINE> <INDENT> t = datetime.datetime.now() <NEW_LINE> with open('data.csv', 'a') as csvfile: <NEW_LINE> <INDENT> fieldnames = ['date', 'temp'] <NEW_LINE> writer = csv.DictWriter(csvfile, fieldnames=fieldnames) <NEW_LINE> writer.writerow({'date': t.strftime('%Y-%m-%d %H:%M:%S'), 'temp': temp}) | writes the temp to a csv file with date colomn | 625941ec3539df3088e2e852 |
def separate_footnotes(self): <NEW_LINE> <INDENT> self.__initiate_sep_values() <NEW_LINE> self.__footnote_holder = better_mktemp() <NEW_LINE> with open(self.__file) as read_obj: <NEW_LINE> <INDENT> with open(self.__write_to, 'w') as self.__write_obj: <NEW_LINE> <INDENT> with open(self.__footnote_holder, 'w') as self.__... | Separate all the footnotes in an RTF file and put them at the bottom,
where they are easier to process. Each time a footnote is found,
print all of its contents to a temporary file. Close both the main and
temporary file. Print the footnotes from the temporary file to the
bottom of the main file. | 625941ec3c8af77a43ae3cad |
def comparar_tiempo(self, trayecto_a, trayecto_b): <NEW_LINE> <INDENT> trayecto_a = self.obtener_trayecto(trayecto_a) <NEW_LINE> trayecto_b = self.obtener_trayecto(trayecto_b) <NEW_LINE> return (trayecto_a.tiempo_total > trayecto_b.tiempo_total) - (trayecto_a.tiempo_total < trayecto_b.tiempo_total) | Compara el tiempo entre dos trayectos.
Devuelve -1 si el primero es más rápido que el segundo, 1 si es más lento y 0 si son iguales.
:type trayecto_a: str
:type trayecto_b: str
:rtype: int | 625941ec55399d3f05588bbe |
def serialize_item(self, item): <NEW_LINE> <INDENT> if isinstance(item, CalciteBaseNode): <NEW_LINE> <INDENT> return self.serialize_node(item) <NEW_LINE> <DEDENT> elif isinstance(item, BaseExpr): <NEW_LINE> <INDENT> return self.serialize_expr(item) <NEW_LINE> <DEDENT> elif isinstance(item, CalciteCollation): <NEW_LINE>... | Serialize a single expression item.
Parameters
----------
item : Any
Item to serialize.
Returns
-------
str, int, dict or list of dict
Serialized item. | 625941ec1b99ca400220afba |
def test_1_1_0_in_reply_to_status_id(self): <NEW_LINE> <INDENT> status = '@{} {}'.format(USER, twitter_endpoints.generate_uuid()) <NEW_LINE> params = {'status':status, 'in_reply_to_status_id':A_STATUS_ID} <NEW_LINE> json = {'text':status, 'in_reply_to_status_id':eval(A_STATUS_ID), 'in_reply_to_status_id_str':A_STATUS_I... | 1.1.0 Post a reply | 625941eca4f1c619b28b0533 |
def ensure_export(self, context, volume): <NEW_LINE> <INDENT> pass | Synchronously recreates an export for a logical volume. | 625941ec7cff6e4e81117e8c |
def start_standalone(self): <NEW_LINE> <INDENT> self._daemon_proxy = DaemonStandaloneProxy(self.__event_handlers) <NEW_LINE> self.__started_standalone = True | Starts a daemon in the same process as the client. | 625941ece1aae11d1e74a1c3 |
def DTsClassifier(self, x_train, x_test, y_train): <NEW_LINE> <INDENT> dt_clf = tree.DecisionTreeClassifier( criterion='entropy', splitter='best', max_depth=10, ccp_alpha=0.001, random_state=0) <NEW_LINE> dt_clf.fit(x_train, y_train) <NEW_LINE> y_predict_train = dt_clf.predict(x_train) <NEW_LINE> y_predict_test = dt_cl... | DEFAULT: class sklearn.tree.DecisionTreeClassifier(*, criterion='gini', splitter='best',
max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0,
max_features=None, random_state=None, max_leaf_nodes=None, min_impurity_decrease=0.0,
min_impurity_split=None, class_weight=None, ccp_alpha=0.0) | 625941ec283ffb24f3c55e02 |
def special_update(current, key, value): <NEW_LINE> <INDENT> while '.' in key: <NEW_LINE> <INDENT> p, key = key.split('.', 1) <NEW_LINE> if p not in current: <NEW_LINE> <INDENT> current[p] = {} <NEW_LINE> <DEDENT> current = current[p] <NEW_LINE> <DEDENT> current[key] = value | >>> a = {}
>>> special_update(a, 'b.c', 1)
>>> a
{'b': {'c': 1}}
>>> | 625941ecf7d966606f6aa510 |
def setup(self): <NEW_LINE> <INDENT> sim = self.simulation <NEW_LINE> assert self.active is False, 'Trying to setup mesh morphing twice in the same simulation' <NEW_LINE> mesh = sim.data['mesh'] <NEW_LINE> Vcvol = dolfin.FunctionSpace(mesh, 'DG', 0) <NEW_LINE> sim.data['cvolp'] = dolfin.Function(Vcvol) <NEW_LINE> Vmesh... | Create mesh velocity and deformation functions | 625941ec60cbc95b062c6a4a |
def test_add_mp3_normalize_title(self): <NEW_LINE> <INDENT> self.add_mp3(artist='Artist', title='Title: øÆ & ü') <NEW_LINE> self.run_add() <NEW_LINE> self.assertEqual(Song.objects.count(), 1) <NEW_LINE> song = Song.objects.get() <NEW_LINE> self.assertEqual(song.title, 'Title: øÆ & ü') <NEW_LINE> self.assertEqual(song.n... | Test to ensure that song title normalization is working properly. | 625941ecf7d966606f6aa511 |
def autoreload(module, interval=0.5): <NEW_LINE> <INDENT> watch(lambda _: reload(module), module.__file__, interval=interval) | Reload module whenever its source file is modified.
Polls the file every interval seconds in a separate thread.
See watch. | 625941ec0c0af96317bb86ee |
def contract_choice_tuples(choices): <NEW_LINE> <INDENT> if not choices: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif not isinstance(choices[0], (list, tuple)): <NEW_LINE> <INDENT> return choices <NEW_LINE> <DEDENT> return [value for value, _ in choices] | Return only values of a choice tuple. If the choices are simple lists
without display name the same list is returned | 625941ec92d797404e304693 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.