code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def get_avg(coin: str, currency: str = CURRENCY, exchange: str = 'CCCAGG') -> Optional[Dict]: <NEW_LINE> <INDENT> response = _query_cryptocompare(_URL_AVG.format( coin, currency, _format_parameter(exchange))) <NEW_LINE> if response: <NEW_LINE> <INDENT> return response['RAW'] <NEW_LINE> <DEDENT> return None | Get the average price
:param coin: symbolic name of the coin (e.g. BTC)
:param currency: short hand description of the currency (e.g. EUR)
:param exchange: exchange to use (default: 'CCCAGG')
:returns: dict of coin and currency price pairs | 625941bb07f4c71912b11341 |
def resetPosition(self): <NEW_LINE> <INDENT> self.setQuadraturePosition(0, 0) | This function resets the encoder position to 0 | 625941bb2ae34c7f2600cfeb |
def getQValue(self, state, action): <NEW_LINE> <INDENT> qvalue = 0 <NEW_LINE> value = 0 <NEW_LINE> features= self.featExtractor.getFeatures(state,action) <NEW_LINE> for key in self.getWeights(): <NEW_LINE> <INDENT> value = self.getWeights()[key] * features[key] <NEW_LINE> qvalue = value + qvalue <NEW_LINE> <DEDENT> ret... | Should return Q(state,action) = w * featureVector
where * is the dotProduct operator | 625941bb76d4e153a657e9ea |
def get_selected_keys(self, selection: int) -> list[str]: <NEW_LINE> <INDENT> return [k for k, b in self._lookup.items() if b & selection] | Return a list of keys for the given selection. | 625941bb57b8e32f5248335a |
def _collect_testlibs(config, server_match, client_match=[None]): <NEW_LINE> <INDENT> def expand_libs(config): <NEW_LINE> <INDENT> for lib in config: <NEW_LINE> <INDENT> sv = lib.pop('server', None) <NEW_LINE> cl = lib.pop('client', None) <NEW_LINE> yield lib, sv, cl <NEW_LINE> <DEDENT> <DEDENT> def yield_testlibs(base... | Collects server/client configurations from library configurations | 625941bb8a43f66fc4b53f23 |
def filter_gdf( gdf, rel_orbit_numbers=None, footprint_overlaps=None, start_date=None, end_date=None): <NEW_LINE> <INDENT> if len(gdf) and start_date is not None: <NEW_LINE> <INDENT> mask = gdf['sensing_end'] >= start_date <NEW_LINE> gdf = gdf[mask] <NEW_LINE> <DEDENT> if len(gdf) and end_date is not None: <NEW_LINE> <... | Filter S1 metadata GeoDataFrame
Parameters
----------
gdf : GeoDataFrame
S1 metadata
rel_orbit_numbers : list of int
relative orbit numbers
footprint_overlaps : shapely.geometry.Polygon
AOI polygon
start_date, end_date : datetime.datetime or datestr
date interval | 625941bb4d74a7450ccd407c |
def test_set_new(self): <NEW_LINE> <INDENT> c = Context() <NEW_LINE> c.set_new('foo', {}) <NEW_LINE> self.assertEqual(c['foo'], {}) <NEW_LINE> c.set_new('foo', 100) <NEW_LINE> self.assertEqual(c['foo'], {}) | Test setting values if not present | 625941bb004d5f362079a1f0 |
def __format_param(param): <NEW_LINE> <INDENT> bool_list = ['removemargin', 'flagshadow', 'flagstroke', 'opaqueavatar', 'darktriangles', 'darkheader', 'rankedscore'] <NEW_LINE> xp = ['xpbar', 'xpbarhex'] <NEW_LINE> int_list = ['avatarrounding', 'onlineindicator'] <NEW_LINE> res = '' <NEW_LINE> if xp[0] in param and xp[... | Clean up the advanced parameter from generate()
:param param: the advanced parameter from generate()
:return: string of formatted parameters | 625941bb090684286d50eb9b |
def manage_existing_get_size(self, volume, existing_ref): <NEW_LINE> <INDENT> pass | Return size of volume to be managed by manage_existing.
When calculating the size, round up to the next GB.
:param volume: Cinder volume to manage
:param existing_ref: Dictionary with keys 'source-id', 'source-name'
with driver-specific values to identify a backend
stor... | 625941bb32920d7e50b28086 |
def updateModeless(self, refreshAxes=False): <NEW_LINE> <INDENT> if refreshAxes: <NEW_LINE> <INDENT> self.dd.aPanel.drawAxisLabels() <NEW_LINE> <DEDENT> r = self.limitLineMovement(self.x1, self.y1, self.x2, self.y2) <NEW_LINE> self.x1 = r[0] <NEW_LINE> self.y1 = r[1] <NEW_LINE> self.x2 = r[2] <NEW_LINE> self.y2 = r[3] ... | Called when Pixel Display Type (actual/normalized) is changed or when
new image is loaded. | 625941bbd486a94d0b98e004 |
def push(self): <NEW_LINE> <INDENT> self._stack.append({}) <NEW_LINE> self._cur += 1 | Push a new frame onto the stack. | 625941bb63d6d428bbe443a9 |
def get(access_token, media_id, **kwargs): <NEW_LINE> <INDENT> api = 'https://api.weixin.qq.com/cgi-bin/media/get' <NEW_LINE> params = {'access_token': access_token, 'media_id': media_id} <NEW_LINE> params.update(**kwargs) <NEW_LINE> return requests_get(api, params) | 获取临时素材 | 625941bb0c0af96317bb80a3 |
def test_reload_with_changed_fields(self): <NEW_LINE> <INDENT> class User(Document): <NEW_LINE> <INDENT> name = StringField() <NEW_LINE> number = IntField() <NEW_LINE> <DEDENT> User.drop_collection() <NEW_LINE> user = User(name="Bob", number=1).save() <NEW_LINE> user.name = "John" <NEW_LINE> user.number = 2 <NEW_LINE> ... | Ensures reloading will not affect changed fields | 625941bb4e696a04525c9306 |
def exclusive() -> Callable[[Observable[Observable[_T]]], Observable[_T]]: <NEW_LINE> <INDENT> from ._exclusive import exclusive_ <NEW_LINE> return exclusive_() | Performs a exclusive waiting for the first to finish before
subscribing to another observable. Observables that come in between
subscriptions will be dropped on the floor.
.. marble::
:alt: exclusive
-+---+-----+-------|
+-7-8-9-|
+-4-5-6-|
+-1-2-3-|
[ exclusive() ]
-... | 625941bb60cbc95b062c6403 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, PageDtoDiscoveredVendorDto): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941bb796e427e537b047c |
def connect_JSON(config): <NEW_LINE> <INDENT> testnet = config.get('testnet', '0') <NEW_LINE> testnet = (int(testnet) > 0) <NEW_LINE> if not 'rpcport' in config: <NEW_LINE> <INDENT> config['rpcport'] = 51475 if testnet else 50051 <NEW_LINE> <DEDENT> connect = "http://%s:%[email protected]:%s"%(config['rpcuser'], config['rpcp... | Connect to a send JSON-RPC server | 625941bb4f6381625f1148f8 |
def P_S_arrival_T_common(epi_val, evdp): <NEW_LINE> <INDENT> P_WAVE_VELOCITY = 6.10 <NEW_LINE> S_WAVE_VELOCITY = 3.55 <NEW_LINE> hypo_dist = np.sqrt(epi_val**2 + evdp**2) <NEW_LINE> P_arrival_T = hypo_dist/P_WAVE_VELOCITY <NEW_LINE> S_arrival_T = hypo_dist/S_WAVE_VELOCITY <NEW_LINE> return P_arrival_T, S_arrival_T | p and s travel time for common model | 625941bb55399d3f0558856d |
def get_url(self, url): <NEW_LINE> <INDENT> return self.session.get(url, timeout=15).json() | Flat wrapper for fetching URL directly | 625941bb10dbd63aa1bd2a68 |
def read_dict(self, where): <NEW_LINE> <INDENT> out = {} <NEW_LINE> nd = self.get_group(where) <NEW_LINE> for prpnm, prp in nd.attrs.iteritems(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> out[prpnm] = pkl.loads(prp) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> out[prpnm] = prp <NEW_LINE> <DEDENT> <DEDEN... | Read a dictionary object at `where`. | 625941bb6fb2d068a760ef54 |
def update_options(self, *args): <NEW_LINE> <INDENT> args = args <NEW_LINE> self.update_path() | Update path | 625941bb4c3428357757c1e4 |
def test_new_user_email_normalized(self): <NEW_LINE> <INDENT> email = "[email protected]" <NEW_LINE> user = get_user_model().objects.create_user(email, 'test123') <NEW_LINE> self.assertEqual(user.email, email.lower()) | Test the email for the new uesr is normalized | 625941bb45492302aab5e17a |
def update_database(self, images): <NEW_LINE> <INDENT> conn = sqlite3.connect(self.db_path) <NEW_LINE> cur = conn.cursor() <NEW_LINE> images_to_insert = [] <NEW_LINE> for image in images: <NEW_LINE> <INDENT> count_selector = "SELECT count FROM images WHERE url = '%s'" % image['url'] <NEW_LIN... | Take a list of images and update the database to reflect them
:param db_path: Path to database to update
:param images: List of image distionaries | 625941bb1b99ca400220a96b |
def send_to_model_server(path_to_model, url): <NEW_LINE> <INDENT> shutil.make_archive("/output/model", 'zip', path_to_model) <NEW_LINE> r = requests.post(url, data=open("/output/model.zip"), headers={'content-type': 'application/zip'} ) | Send an existing model to an external server.
Parameters:
----------
path_to_model: str
Path from which the model will be loaded
url: str
Url to which the model will be send a zip file | 625941bb7cff6e4e8111783f |
def get_test_descriptors(): <NEW_LINE> <INDENT> resp = requests.get(env.test_descriptors_api, timeout=env.timeout, headers=env.header) <NEW_LINE> env.set_return_header(resp.headers) <NEW_LINE> if resp.status_code != 200: <NEW_LINE> <INDENT> LOG.debug("Request for test descriptors returned with " + (str(resp.status_code... | Returns info on all available test descriptors.
:returns: A tuple. [0] is a bool with the result. [1] is a list of
dictionaries. Each dictionary contains a test descriptor. | 625941bbbaa26c4b54cb0fdd |
def __init__(self, lifespan=None): <NEW_LINE> <INDENT> BaseWorld.__init__(self, lifespan) <NEW_LINE> self.name = 'grid_1D_chase' <NEW_LINE> print("Entering", self.name) <NEW_LINE> self.size = 7 <NEW_LINE> self.n_sensors = self.size + 2 * (self.size - 1) <NEW_LINE> self.n_actions = 2 * (self.size - 1) <NEW_LINE> self.re... | Initialize the world.
Parameters
----------
lifespan : int
The number of time steps to continue the world. | 625941bb6fece00bbac2d5f6 |
def generate_timestamp(): <NEW_LINE> <INDENT> now = datetime.datetime.utcnow() <NEW_LINE> ts = now.strftime('%Y-%m-%dT%H:%M:%SZ') <NEW_LINE> return ts | Generates timestamp of the format 2014-08-18T12:00:00Z. | 625941bb26238365f5f0ed24 |
def calc_last_modified(request, *args, **kwargs): <NEW_LINE> <INDENT> assert "cache_name" in kwargs, "Must specify cache_name as a keyword arg." <NEW_LINE> try: <NEW_LINE> <INDENT> cache = get_cache(kwargs["cache_name"]) <NEW_LINE> assert isinstance(cache, FileBasedCache) or isinstance(cache, LocMemCache), "requires fi... | Returns the file's modified time as the last-modified date | 625941bb293b9510aa2c3152 |
def build_params(self, codestring): <NEW_LINE> <INDENT> params = super(AztecCode._Renderer, self).build_params(codestring) <NEW_LINE> cbbox = self._code_bbox(codestring) <NEW_LINE> params['bbox'] = '%d %d %d %d' %(self._boundingbox(cbbox, cbbox)) <NEW_LINE> return params | >>> AztecCode._Renderer({}).build_params('abcd')
{'yscale': 1.0, 'codestring': '<61626364>', 'bbox': '0 0 30 30', 'codetype': {}, 'xscale': 1.0, 'options': '<>'} | 625941bbe8904600ed9f1de3 |
def print_sorted(self): <NEW_LINE> <INDENT> print(sorted(self)) | Prints the list in ascending order | 625941bbd10714528d5ffb9a |
def __init__(self, parent: Optional['SymbolNode'], character: int): <NEW_LINE> <INDENT> self.__children: CharReferenceMap = None <NEW_LINE> self.__token_type: TokenType = TokenType.Unknown <NEW_LINE> self.__valid: bool = None <NEW_LINE> self.__ancestry: str = None <NEW_LINE> self.__parent: SymbolNode = parent <NEW_LINE... | Constructs a SymbolNode with the given parent, representing the given character.
:param parent: This node's parent
:param character: This node's associated character. | 625941bb07d97122c4178745 |
def get_damage(unit): <NEW_LINE> <INDENT> return unit[1] | a = make_unit( 'zerg', 12 )
get_catchphrase(a)
'zerg'
get_damage(a)
12 | 625941bbbde94217f3682cb5 |
def get_update_list(fp_update): <NEW_LINE> <INDENT> update_list = [] <NEW_LINE> for item in fp_update: <NEW_LINE> <INDENT> temp = item.strip().split() <NEW_LINE> temp_item = [temp[0], temp[5], temp[-1]] <NEW_LINE> update_list.append(temp_item) <NEW_LINE> <DEDENT> return update_list | Divide the fp update based on sync-client | 625941bb187af65679ca4fd7 |
def parse_enemies(current_chunk): <NEW_LINE> <INDENT> global enemies <NEW_LINE> global frenemy <NEW_LINE> current_chunk = strip_ansi(current_chunk) <NEW_LINE> m = re_enemies.search(current_chunk) <NEW_LINE> enemies = m.groups()[0].split("\r\n") <NEW_LINE> c.echo(f"enemies: {' '.join(enemies)}") <NEW_LINE> frenemy.notif... | You have the following enemies:
Farrah
Mezghar
You have currently used 2 enemy slots of your 20 maximum. | 625941bb15fb5d323cde09c4 |
def test_get_node_health_with_invalid_id(self): <NEW_LINE> <INDENT> request_id = "xxxxxxxxxxx" <NEW_LINE> self.assertRaises( DiscoveryError, Discovery.get_node_health, request_id) | Check for node health backend url with invalid id. | 625941bb26068e7796caeb93 |
def join(): <NEW_LINE> <INDENT> t = threading.Thread(name = 'process', target= worker2, args=(3,)) <NEW_LINE> t.start() <NEW_LINE> t.join() <NEW_LINE> t2 = threading.Thread(name = 'process2', target= worker2, args=(3,)) <NEW_LINE> t2.start() | 阻塞线程 | 625941bb30c21e258bdfa355 |
def brand_info_counts(self): <NEW_LINE> <INDENT> return { 'no_brand': self.active_issues().filter(no_brand=True).count(), 'unknown': self.active_issues().filter(no_brand=False, brand__isnull=True).count(), } | Simple method for the UI to use, as the UI can't pass parameters. | 625941bb91af0d3eaac9b8cf |
def classFactory(iface): <NEW_LINE> <INDENT> from .ImportPhotos import ImportPhotos <NEW_LINE> return ImportPhotos(iface) | Load ImportPhotos class from file ImportPhotos.
:param iface: A QGIS interface instance.
:type iface: QgsInterface | 625941bb63b5f9789fde6fa0 |
def eta_func(r_list, param_dict, func_type='well-behaved', scaled=False): <NEW_LINE> <INDENT> if func_type == 'power law': <NEW_LINE> <INDENT> rScale, rc, etaScale, betaDelta = get_eta_powerlaw_params(param_dict) <NEW_LINE> r = np.array(r_list) <NEW_LINE> w = (r-rc)/rScale <NEW_LINE> return etaScale*w**(betaDelta) <NEW... | Nonlinear scaling variable function determined from
the flow equations of the disorder, w, and field, h
Input:
r_list - list of r values
param_dict - dictionary of parameters on which eta(r) is dependent
func_type - which form of eta(r) to use. Options:
'power law' - eta(r) derived with dw/dl = (1/n... | 625941bb7cff6e4e81117840 |
def main(): <NEW_LINE> <INDENT> T = int(input()) <NEW_LINE> for case in range(T): <NEW_LINE> <INDENT> num = int(input()) <NEW_LINE> solve(num, 1, int(math.sqrt(num * 2))) | 이게 최대 n 값 찾기
x = n * (2 * a1 + n - 1) / 2
x = n * (2 * a1 + -(n - 1)) / 2 | 625941bb2ae34c7f2600cfec |
def test_edit_full(self) -> None: <NEW_LINE> <INDENT> self.submit_form('edit_address', 'input_id_submit', send_form_keys={ 'id_address_line_1': '2986 Heron Way', 'id_address_line_2': 'Attn. Anna Freytag', 'id_city': 'Portland', 'id_zip': '97205', 'id_state': 'Oregon' }, select_dropdowns={ 'id_country': ('US',) }) <NEW_... | Tests that adding a full address works | 625941bb85dfad0860c3ad13 |
def receive_weather(self, weather_id): <NEW_LINE> <INDENT> path = self._compose_path("integrations/weather/{0}".format(weather_id)) <NEW_LINE> return self._get(path) | Get data from the Adafruit IO Weather Forecast Service
NOTE: This service is avaliable to Adafruit IO Plus subscribers only.
:param int weather_id: ID for retrieving a specified weather record. | 625941bb4c3428357757c1e5 |
def resize(self, size): <NEW_LINE> <INDENT> return type(self)(self._data.name, size=size, index=self._index) | Returns a new copy of this font in a different size | 625941bb2c8b7c6e89b3567d |
def _stepwise_interp(xi, yi, x): <NEW_LINE> <INDENT> end = np.atleast_1d(xi.searchsorted(x)) <NEW_LINE> end[end == 0] += 1 <NEW_LINE> start = end - 1 <NEW_LINE> end[end == len(xi)] -= 1 <NEW_LINE> try: <NEW_LINE> <INDENT> xi_smallest_diff = 20 * np.finfo(xi.dtype).resolution <NEW_LINE> <DEDENT> except ValueError: <NEW_... | Step-wise interpolate (or extrapolate) (xi, yi) values to x positions.
Given a set of N ``(x, y)`` points, provided in the *xi* and *yi* arrays,
this will calculate ``y``-coordinate values for a set of M
``x``-coordinates provided in the *x* array, using step-wise (zeroth-order)
interpolation and extrapolation.
The i... | 625941bb45492302aab5e17b |
def stop_vm(self, vmname): <NEW_LINE> <INDENT> sms = ServiceManagementService(self.__subscription, self.__certSelection) <NEW_LINE> result = sms.shutdown_role(self.getVmService(vmname), self.getVmService(vmname), vmname) <NEW_LINE> if result: <NEW_LINE> <INDENT> return self.wait_operation(result.request_id) <NEW_LINE> ... | starts vm role | 625941bb9f2886367277a74b |
def ssr(self, x, y): <NEW_LINE> <INDENT> J = np.ones((y.shape[0], y.shape[0])) <NEW_LINE> G = np.linalg.inv(np.dot(x.T, x)) <NEW_LINE> H = np.dot(x, np.dot(G, x.T)) <NEW_LINE> Qr = H - (1/y.shape[0])*J <NEW_LINE> SSR = np.dot(y.T, np.dot(Qr, y)) <NEW_LINE> return SSR | Compute the regression sum of squares.
Parameters:
- - - - -
x: feature matrix
y: response matrix | 625941bbde87d2750b85fc49 |
def trainer(self, classes=None): <NEW_LINE> <INDENT> self.logger.info('Running trainer method') <NEW_LINE> if classes is None: <NEW_LINE> <INDENT> classes = ['ok'] <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.cleaned = self.data.copy() <NEW_LINE> self.cleaned = self.data[self.selection + self.codes] <NEW_LINE> sel... | Prepare the data for training | 625941bb94891a1f4081b963 |
def optimize(self, network, data_X, data_Y): <NEW_LINE> <INDENT> optimize_start_time = time.time() <NEW_LINE> indexes = np.arange(len(data_X)) <NEW_LINE> if self.verbosity > 0: <NEW_LINE> <INDENT> c = network.cost(data_X, data_Y) <NEW_LINE> print("Cost before epochs: {}".format(c)) <NEW_LINE> <DEDENT> for epoch in rang... | :return: optimized network | 625941bbd164cc6175782c08 |
def talk_m10_02_x21(): <NEW_LINE> <INDENT> ClearNpcMenuResults() <NEW_LINE> if GetEventFlag(102181) != 0: <NEW_LINE> <INDENT> assert talk_m10_02_x23() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert talk_m10_02_x22() <NEW_LINE> <DEDENT> """State 4: End state""" <NEW_LINE> return 0 | Retired fire prevention woman 1: Conversation | 625941bb8c3a873295158279 |
def isLoading(self): <NEW_LINE> <INDENT> return self.__isLoading | Public method to get the loading state.
@return flag indicating the loading state (boolean) | 625941bbcb5e8a47e48b7969 |
def put_inst(self, byte): <NEW_LINE> <INDENT> self._inst(byte) | Write an instruction byte. | 625941bb26068e7796caeb94 |
def order_limit_sell(self, disable_validation=False, timeInForce=TIME_IN_FORCE_GTC, **params): <NEW_LINE> <INDENT> params.update({ 'side': SIDE_SELL }) <NEW_LINE> return self.order_limit(disable_validation=disable_validation, timeInForce=timeInForce, **params) | Send in a new limit sell order
:param symbol: required
:type symbol: str
:param quantity: required
:type quantity: decimal
:param price: required
:type price: decimal
:param timeInForce: default Good till cancelled
:type timeInForce: enum
:param newClientOrderId: A unique id for the order. Automatically generated if n... | 625941bb0a366e3fb873e6d2 |
def find_or_create(community, teamJSON): <NEW_LINE> <INDENT> if 'name' in teamJSON: <NEW_LINE> <INDENT> return TeamService.find_by_name(community, teamJSON['name']) <NEW_LINE> <DEDENT> elif 'goalkeeper' in teamJSON and 'forward' in teamJSON: <NEW_LINE> <INDENT> gk_id = teamJSON['goalkeeper'] <NEW_LINE> fw_id = teamJSON... | Find team using provided team json: by name or by players. | 625941bbfbf16365ca6f6078 |
def testProcess(self): <NEW_LINE> <INDENT> use_context = True <NEW_LINE> conn0, child_conn0 = mp.Pipe() <NEW_LINE> conn1, child_conn1 = mp.Pipe() <NEW_LINE> if use_context: <NEW_LINE> <INDENT> context = mp.get_context("fork") <NEW_LINE> proc0 = context.Process(target=worker, args=(child_conn0,)) <NEW_LINE> proc1 = cont... | env_dummy = rodentia.Environment(width=84, height=84,
bg_color=[0.0, 0.0, 0.0])
env_dummy.close()
env_dummy = None | 625941bba934411ee3751555 |
def _expr(self): <NEW_LINE> <INDENT> expr_value = self._or() <NEW_LINE> while self._accept('XOR'): <NEW_LINE> <INDENT> return self.graph.addOperator('XOR', leftNode=expr_value, rightNode=self._expr(), side=self.side) <NEW_LINE> <DEDENT> return expr_value | <expr> ::= <or> {'^' <expr>} | 625941bbab23a570cc25003a |
def t350190_x14(): <NEW_LINE> <INDENT> Quit() <NEW_LINE> return 0 | State 0 | 625941bbb57a9660fec3373b |
def _createProtoQuery(self): <NEW_LINE> <INDENT> protoObj = LeveldbServerMessages.ActualData() <NEW_LINE> protoObj.timestamp = arrow.now().timestamp <NEW_LINE> protoObj.type = LeveldbServerMessages.ActualData.QUERY <NEW_LINE> return protoObj | helper method that creates the LeveldbServerMessages.ActualData object for us, sets the timestamp
and the type, and then returns it for us
this is for a ServerQuery
@return a ActualData protobuf object | 625941bb92d797404e304044 |
def test_check_failure(self): <NEW_LINE> <INDENT> results = Run(["grep", "--asdfghjk"])() <NEW_LINE> results = Check(AssertExitFailure())(results) <NEW_LINE> self.assertEqual(results.returncode, 0) | Check should set results to successful by asserting exit failure. | 625941bb4f88993c3716bf28 |
def astimezone(self, tz=LOCAL): <NEW_LINE> <INDENT> if tz is None: <NEW_LINE> <INDENT> tz = LOCAL <NEW_LINE> <DEDENT> tz = parser.get_timezone(tz) <NEW_LINE> return self.datetime.astimezone(tz) | Return datetime shifted to timezone `tz`.
Note:
This returns a native datetime object.
Args:
tz (None|str|tzinfo, optional): Timezone to shift to. Defaults to `"local"` which uses
the local timezone.
Returns:
:class:`datetime` | 625941bb63f4b57ef0000fdb |
def generate_template(tmpl, dest, config): <NEW_LINE> <INDENT> with open(tmpl) as tmpl: <NEW_LINE> <INDENT> with open(dest, 'w') as dest: <NEW_LINE> <INDENT> dest.write(render_template(tmpl.read(), config)) | generate file
| 625941bb9c8ee82313fbb630 |
def seg_ctc_ent_cost(out, targets, sizes, target_sizes, uni_rate=1.5): <NEW_LINE> <INDENT> Time = out.size(0) <NEW_LINE> loss_func = seg_ctc_ent_loss_log <NEW_LINE> offset = 0 <NEW_LINE> batch = target_sizes.size(0) <NEW_LINE> uniform_mask = Variable(T.zeros(Time, batch).type(byteX)) <NEW_LINE> for index, (target_size,... | out = out.cpu()
targets = targets.cpu()
sizes = sizes.cpu()
target_sizes = target_sizes.cpu() | 625941bbcdde0d52a9e52eea |
def _find_existing_inputs(in_bam): <NEW_LINE> <INDENT> sr_file = "%s-sr.bam" % os.path.splitext(in_bam)[0] <NEW_LINE> disc_file = "%s-disc.bam" % os.path.splitext(in_bam)[0] <NEW_LINE> if utils.file_exists(sr_file) and utils.file_exists(disc_file): <NEW_LINE> <INDENT> return in_bam, sr_file, disc_file <NEW_LINE> <DEDEN... | Check for pre-calculated split reads and discordants done as part of alignment streaming.
| 625941bbff9c53063f47c0b0 |
def repeat_last_operation(calc): <NEW_LINE> <INDENT> if calc['history']: <NEW_LINE> <INDENT> return calc['history'][-1][-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Return passed calculator's last operation result. | 625941bb30bbd722463cbc7e |
def filter_by_regex(self, kind=None, value=None, exclude=False): <NEW_LINE> <INDENT> self.loggit.debug('Filtering indices by regex') <NEW_LINE> if kind not in [ 'regex', 'prefix', 'suffix', 'timestring' ]: <NEW_LINE> <INDENT> raise ValueError('{0}: Invalid value for kind'.format(kind)) <NEW_LINE> <DEDENT> if value == 0... | Match indices by regular expression (pattern).
:arg kind: Can be one of: ``suffix``, ``prefix``, ``regex``, or
``timestring``. This option defines what kind of filter you will be
building.
:arg value: Depends on `kind`. It is the strftime string if `kind` is
``timestring``. It's used to build the regular e... | 625941bb50812a4eaa59c1df |
def ll_copyfile(self, src, dst, *, follow_symlinks=True): <NEW_LINE> <INDENT> if shutil._samefile(src, dst): <NEW_LINE> <INDENT> raise shutil.SameFileError("{!r} and {!r} are the same file".format(src, dst)) <NEW_LINE> <DEDENT> for fn in [src, dst]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> st = os.stat(fn) <NEW_LIN... | Copy data from src to dst.
If follow_symlinks is not set and src is a symbolic link, a new
symlink will be created instead of copying the file it points to. | 625941bb3346ee7daa2b2c25 |
def generateRandomKey(): <NEW_LINE> <INDENT> key = list(LETTERS) <NEW_LINE> random.shuffle(key) <NEW_LINE> return ''.join(key) | Generate and return a random encryption key. | 625941bbd18da76e2353238d |
def test_approx_freq_pattern_finder(self): <NEW_LINE> <INDENT> for DNA, pat_len, dist, freq in self.known_approx_freq: <NEW_LINE> <INDENT> result = freq_finder.find_most_approx_freq(DNA, pat_len, dist) <NEW_LINE> self.assertCountEqual(freq, result) | Most-frequent approximate patterns should be found correctly | 625941bbe1aae11d1e749b6f |
def predict(image_path, model, topk=5): <NEW_LINE> <INDENT> model.eval() <NEW_LINE> img = process_image(image_path) <NEW_LINE> img = torch.from_numpy(np.array(img)).float() <NEW_LINE> img = img.to(device) <NEW_LINE> img.unsqueeze_(0) <NEW_LINE> output = model.forward(img) <NEW_LINE> probs, classes = torch.exp(output).t... | Predict the class (or classes) of an image using a trained deep learning model.
| 625941bb6fb2d068a760ef55 |
def _create_hash(self): <NEW_LINE> <INDENT> sha = hashlib.sha256() <NEW_LINE> for index in self.collect_package_indices(): <NEW_LINE> <INDENT> sha.update(index.encode()) <NEW_LINE> <DEDENT> return sha.hexdigest()[:32] | Creates a hash based on the configuration of this Source.
The hash should uniquely identify a source configuration,
without having to store a massive string. | 625941bb090684286d50eb9c |
def PlotResult(model,x_test,y_test): <NEW_LINE> <INDENT> x = [i+1 for i in range(len(y_test))][:100] <NEW_LINE> y_pred = model.predict(x_test) <NEW_LINE> plt.rcParams['font.family'] = ['sans-serif'] <NEW_LINE> plt.rcParams['font.sans-serif'] = ['SimHei'] <NEW_LINE> fig = plt.figure(figsize=(12,6)) <NEW_LINE> plt.plot(x... | 预测值\真实值可视化. | 625941bb925a0f43d2549d2f |
def upload_test_results(self): <NEW_LINE> <INDENT> project_id = self.config_dict.get_config('project_id') <NEW_LINE> self.qtest_project_id = project_id <NEW_LINE> auto_api = swagger_client.TestlogApi() <NEW_LINE> auto_req = self._generate_auto_request() <NEW_LINE> try: <NEW_LINE> <INDENT> response = auto_api.submit_aut... | Construct a 'AutomationRequest' qTest resource and upload the test results to the desired project in
qTest Manager.
Returns:
int: The queue processing ID for the job.
Raises:
RuntimeError: Failed to upload test results to qTest Manager. | 625941bb5fc7496912cc3841 |
def index_search(self, wait=True): <NEW_LINE> <INDENT> if not self.driver: <NEW_LINE> <INDENT> self.logger.error("Not connected.") <NEW_LINE> return False <NEW_LINE> <DEDENT> if self._index_searched: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for i, axis in enumerate(self.axes): <NEW_LINE> <INDENT> self.logge... | Finding index, requires full rotation on motor | 625941bbff9c53063f47c0b1 |
def off(self): <NEW_LINE> <INDENT> if self.state == OFF: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.process.terminate() <NEW_LINE> self.state = OFF | выключает видео | 625941bb6e29344779a624d0 |
def _get_sal_config(self, channel): <NEW_LINE> <INDENT> if 'channels' not in self.config['sal']: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> if channel not in self.config['sal']['channels']: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> return self.config['sal']['channels'][channel] | Get SAL configuration for given channel. | 625941bb2c8b7c6e89b3567e |
def image_gradient_T(x): <NEW_LINE> <INDENT> if isinstance(x, np.ndarray): <NEW_LINE> <INDENT> x_h = x[0] <NEW_LINE> x_v = x[1] <NEW_LINE> x_h_ext = np.hstack((x_h, x_h[:, :1])) <NEW_LINE> x_v_ext = np.vstack((x_v, x_v[:1])) <NEW_LINE> d_x = x_h_ext[:, :-1] - x_h_ext[:, 1:] <NEW_LINE> d_y = x_v_ext[:-1] - x_v_ext[1:] <... | Transpose of the operator that function image_gradient implements.
Computes the transpose of the matrix given by function image_gradient.
Parameters
----------
x : numpy.ndarray or ctorch.ComplexTensor
stack of two identically shaped arrays
Returns
-------
numpy.ndarray or ctorch.ComplexTensor
result of appl... | 625941bb76d4e153a657e9eb |
def _IsTestMethod(attrname, test_case_class): <NEW_LINE> <INDENT> attr = getattr(test_case_class, attrname) <NEW_LINE> return callable(attr) and attrname.startswith('test') | Checks whether this is a valid test method.
Args:
attrname: the method name.
test_case_class: the test case class.
Returns:
True if test_case_class.'attrname' is callable and it starts with 'test';
False otherwise. | 625941bbb57a9660fec3373c |
def get_lpm_len_from_node(self, node, dst_addr): <NEW_LINE> <INDENT> cur_lpm_len = 0 <NEW_LINE> dst_addr = ipaddress.ip_address(dst_addr) <NEW_LINE> is_ipv4 = isinstance(dst_addr, ipaddress.IPv4Address) <NEW_LINE> for cur_prefix in self.get_node_prefixes(node, is_ipv4): <NEW_LINE> <INDENT> if dst_addr in ipaddress.ip_n... | return the longest prefix match of dst_addr in node's
advertising prefix pool | 625941bb0fa83653e4656e78 |
def norm1(self, x): <NEW_LINE> <INDENT> return self._get_module_by_name(self.norm1_name)(x) | Apply norm1. | 625941bb2eb69b55b151c767 |
def pc_output_buffers_full(self, *args): <NEW_LINE> <INDENT> return _Interfaces_swig.ax25_sink_b_sptr_pc_output_buffers_full(self, *args) | pc_output_buffers_full(ax25_sink_b_sptr self, int which) -> float
pc_output_buffers_full(ax25_sink_b_sptr self) -> pmt_vector_float | 625941bb7b180e01f3dc46c0 |
def test_clean_name_string(self): <NEW_LINE> <INDENT> self.assertEqual('this is a full name', baidu.clean_name_string('this is a full name')) <NEW_LINE> self.assertEqual('this is a full ,. pz', baidu.clean_name_string('this is a full ;,.$&[{{}}(=*)+]pz')) <NEW_LINE> self.assertEqual('', baidu.clean_name_string('')) | bibauthorid - test cleaning of name strings | 625941bb167d2b6e31218a52 |
def last_record(): <NEW_LINE> <INDENT> out_record = dict() <NEW_LINE> out_record['date'] = "2014-12-08" <NEW_LINE> out_record['time'] = "21:38" <NEW_LINE> out_record['celsius'] = -4 <NEW_LINE> out_record['fahrenheit'] = int(round(out_record['celsius']*9/5.0 + 32)) <NEW_LINE> out_record['humidity'] = 50 <NEW_LINE> retur... | Returns the last temperature and humidity record data.
The returned object is a dict with keys ts, fahrenheit, celsius and
humidity.
In the mockup, there is no real temperature sensor to query, so
an arbitrary result is returned. | 625941bb56ac1b37e6264091 |
def variant(bg): <NEW_LINE> <INDENT> fullname = epp.literal(misc.normalize(bg.name)) <NEW_LINE> shortname = epp.literal(misc.normalize(bg.shortname)) <NEW_LINE> eff = epp.effect(lambda val, st: val.update({Capture.BACKGROUND: bg})) <NEW_LINE> return epp.chain( [epp.branch([fullname, shortname], save_iterator=False), ef... | Make a parser for the background. | 625941bb379a373c97cfaa06 |
def get(self, request, format=None): <NEW_LINE> <INDENT> an_apiview = [ 'Uses HTTP methods as function (get, post, put, patch, delete).', 'It is similar to a traditional django view', 'Gives you the most control over your logic', 'Is mapped manually to URLs', ] <NEW_LINE> return Response({'message': 'Hello world', 'an_... | Returns a list of APIView feature. | 625941bbac7a0e7691ed3f94 |
def output_multiple(self): <NEW_LINE> <INDENT> return _trellis.trellis_viterbi_combined_fi_sptr_output_multiple(self) | output_multiple(self) -> int | 625941bb21a7993f00bc7ba6 |
def delete_extra_channel(self, id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.delete_extra_channel_with_http_info(id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.delete_extra_channel_with_http_in... | DeleteExtraChannel deletes the extra channel matching the given id. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_extra_channel(id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param s... | 625941bb66673b3332b91f4c |
def to_basic_block(self): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_multiply_ff_sptr_to_basic_block(self) | to_basic_block(self) -> gr_basic_block_sptr | 625941bba219f33f34628830 |
def generate_access_config(access, psecurity = False): <NEW_LINE> <INDENT> result_cmd_list = [] <NEW_LINE> access_template = [ 'switchport mode access', 'switchport access vlan', 'switchport nonegotiate', 'spanning-tree portfast', 'spanning-tree bpduguard enable' ] <NEW_LINE> port_security = [ 'switchport port-security... | из задания 9.1а
access - словарь access-портов,
для которых необходимо сгенерировать конфигурацию, вида:
{ 'FastEthernet0/12':10,
'FastEthernet0/14':11,
'FastEthernet0/16':17 }
psecurity - контролирует нужна ли настройка Port Security. По умолчанию значение False
- если значение True, то настройка... | 625941bb627d3e7fe0d68d0a |
def randomNetwork(sites, cmin=1, cmax=10): <NEW_LINE> <INDENT> sites = list(sites) <NEW_LINE> c = {} <NEW_LINE> for i in xrange(len(sites)): <NEW_LINE> <INDENT> a = sites[i] <NEW_LINE> c[a, a] = 0 <NEW_LINE> for j in xrange(i + 1, len(sites)): <NEW_LINE> <INDENT> b = sites[j] <NEW_LINE> c[b, a] = c[a, b] = randint(cmin... | sites: names of the sites | 625941bb8a43f66fc4b53f25 |
@csrf_exempt <NEW_LINE> def logUser(request): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> objJson = json.loads(request.body.decode('utf-8')) <NEW_LINE> login = objJson['login'] <NEW_LINE> password = objJson['password'] <NEW_LINE> user = authenticate(username=login, password=password) <NEW_LINE>... | Connecte un utilisateur | 625941bb2ae34c7f2600cfed |
def get_list_example(): <NEW_LINE> <INDENT> return [ [1, '2017-11-01'], [2, '2017-11-08'], [3, '2017-11-15'] ] | 获取某一类监控数据的列表,分页显示
:return:
[
[1, '2017-11-01'],
[2, '2017-11-08'],
[3, '2017-11-15']
] | 625941bb1d351010ab8559d9 |
def test_assembly_fails_for_incompatible_dimensions(self): <NEW_LINE> <INDENT> from bempp.api import BlockedOperator <NEW_LINE> op = BlockedOperator(2, 1) <NEW_LINE> op[0, 0] = self._slp <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> op[1, 0] = self._hyp | Assembly fails for incompatible dimensions. | 625941bb6aa9bd52df036c5e |
def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ReportCampaignsGroup): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | Returns true if both objects are not equal | 625941bbcc40096d6159580e |
def __str__(self): <NEW_LINE> <INDENT> return self.outfit_name | String for representing the Outfit object. | 625941bba17c0f6771cbdf0f |
def _load_location(location, element): <NEW_LINE> <INDENT> location.file = element.get('file') <NEW_LINE> line = element.get('line') <NEW_LINE> if line is None: <NEW_LINE> <INDENT> line = element.get('linenr') <NEW_LINE> <DEDENT> if line is None: <NEW_LINE> <INDENT> line = '0' <NEW_LINE> <DEDENT> location.linenr = int(... | Load location from element/dict | 625941bb60cbc95b062c6405 |
def __init__(self, title=None, description=None, visible=None, type=None, order=None, width=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configu... | TopicGraphCreateRequest - a model defined in OpenAPI | 625941bb796e427e537b047e |
def test_baidu_search(self): <NEW_LINE> <INDENT> home_page = HomePage(self.driver) <NEW_LINE> home_page.search("selenium") | # 1
self.driver.find_element_by_id("kw").send_keys("selenium"+Keys.RETURN)
time.sleep(2)
assert "selenium" in self.driver.title | 625941bb4527f215b584c316 |
def get_keywords(self, keyword_part='', current_dict=None): <NEW_LINE> <INDENT> keywords = dict() <NEW_LINE> if current_dict is None: <NEW_LINE> <INDENT> current_dict = self.keyword_trie_dict <NEW_LINE> <DEDENT> for char in current_dict: <NEW_LINE> <INDENT> if char == self._keyword_flag: <NEW_LINE> <INDENT> keywords[ke... | 获取所有的keywords
Returns:
keywords: list | 625941bb10dbd63aa1bd2a6a |
def __init__(self, id=None, label=None, data_type=None, input=None, values=None, operators=None): <NEW_LINE> <INDENT> self.swagger_types = { 'id': 'str', 'label': 'str', 'data_type': 'str', 'input': 'str', 'values': 'list[SchemeValueType]', 'operators': 'list[str]' } <NEW_LINE> self.attribute_map = { 'id': 'id', 'label... | SchemeField - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition. | 625941bb73bcbd0ca4b2bf39 |
def __setitem__ (self, name, newValue): <NEW_LINE> <INDENT> comp = self.fun <NEW_LINE> if isinstance( newValue, FunctionWrapper): <NEW_LINE> <INDENT> comp[name] = newValue.fun <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> comp[name] = newValue | Called from array-like access on LHS
**It should not be called directly.**
:param name: name or index in the []
:param newValue: new value for item | 625941bbd8ef3951e32433f9 |
def __init__(self, client_id=None, event=None): <NEW_LINE> <INDENT> self._client_id = None <NEW_LINE> self._event = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.client_id = client_id <NEW_LINE> self.event = event | Log - a model defined in Swagger | 625941bb30bbd722463cbc7f |
def validate_date(self, date): <NEW_LINE> <INDENT> if isinstance(date, datetime.datetime) and date.date() < timezone.now().date(): <NEW_LINE> <INDENT> raise ValidationError("Please verify the end dates are not in the past.") | Validate that end dates are not in the past. | 625941bb5166f23b2e1a5015 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.