code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def char_to_string(arr): <NEW_LINE> <INDENT> arr = np.asarray(arr) <NEW_LINE> kind = arr.dtype.kind <NEW_LINE> if kind not in ['U', 'S']: <NEW_LINE> <INDENT> raise ValueError('argument must be a string') <NEW_LINE> <DEDENT> return arr.view(kind + str(arr.shape[-1]))[..., 0] | Like netCDF4.chartostring, but faster and more flexible.
| 625941c463f4b57ef0001101 |
def error(self, eca): <NEW_LINE> <INDENT> junk = '\0'*DBR.dbr_size(self.dbr, self.dcount) <NEW_LINE> self.updateDBR(junk, self.dcount, eca) | Report failure of request to client
| 625941c4cdde0d52a9e53016 |
def run(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> tick = self.ticker() <NEW_LINE> price = float(tick['Last Trade']) <NEW_LINE> self.prices.append(price) <NEW_LINE> if len(self.prices) == int((60/self.interval)*60): <NEW_LINE> <INDENT> self.prices.pop(0) <NEW_LINE> <DEDENT> n_prices = len(prices) <NEW_L... | Runs the automatic bot.
We want to calculate both the profit (difference in value in USD) due to trading and profit if just buy and hold strategy was employed for comparison. | 625941c423849d37ff7b3074 |
def plotCONF(fignum, s, datablock, pars, new): <NEW_LINE> <INDENT> if new == 1: <NEW_LINE> <INDENT> plotNET(fignum) <NEW_LINE> <DEDENT> DIblock = [] <NEW_LINE> for plotrec in datablock: <NEW_LINE> <INDENT> DIblock.append((float(plotrec["dec"]), float(plotrec["inc"]))) <NEW_LINE> <DEDENT> if len(DIblock) > 0: <NEW_LINE>... | plots directions and confidence ellipses | 625941c48c0ade5d55d3e99e |
def read_kept_individual(file): <NEW_LINE> <INDENT> with open(file, 'r') as f: <NEW_LINE> <INDENT> inds = [i.strip() for i in f] <NEW_LINE> <DEDENT> return inds | spefify a list of individual wanting to keep
| 625941c463b5f9789fde70c9 |
def read_sequence_batch(self, sequences, mask=None): <NEW_LINE> <INDENT> if mask is None: <NEW_LINE> <INDENT> sequences, mask = pad_mask(sequences) <NEW_LINE> <DEDENT> computed_states = self.func(sequences, mask) <NEW_LINE> return dict(zip(self.state_var_names, computed_states)) | Basically read_single_sequence but for a whole batch to speed things up.
Note that, because I find it unlikely that someone wants to pass in
a batch of strings, this only works with sequences of integers atm.
That is, the way the data is stored on disk.
Mask can be computed beforehand, in which case sequences arg shou... | 625941c4435de62698dfdc31 |
def deserialize(self, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.header is None: <NEW_LINE> <INDENT> self.header = std_msgs.msg.Header() <NEW_LINE> <DEDENT> if self.points is None: <NEW_LINE> <INDENT> self.points = None <NEW_LINE> <DEDENT> end = 0 <NEW_LINE> _x = self <NEW_LINE> start = end <NEW_LINE> e... | unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str`` | 625941c4091ae35668666f45 |
def __init__(self, costfunction, dimensions, lb, ub, maxiter=500, target_cost=None, n=50, f=0.5, c=0.9): <NEW_LINE> <INDENT> s = self <NEW_LINE> s.costfunction = costfunction <NEW_LINE> s.dimensions = dimensions <NEW_LINE> s.lb = lb.copy() <NEW_LINE> s.ub = ub.copy() <NEW_LINE> s.maxiter = maxiter <NEW_LINE> s.target_c... | The cost function has to take arrays with (m,n) shape as inputs, where
m is the number of particles and n is the number of dimensions.
lb is the lower bound for each dimension
ub is the upper bound for each dimension | 625941c463b5f9789fde70ca |
def act(self, t): <NEW_LINE> <INDENT> idx = np.where(self._action_N == 0) <NEW_LINE> idx = np.array(idx).flatten() <NEW_LINE> if len(idx) == 0: <NEW_LINE> <INDENT> value_list = [] <NEW_LINE> for i in range(self._nb): <NEW_LINE> <INDENT> value = self._Q[i] + self._c * np.sqrt(np.log(t) / self._action_N[i]) <NEW_LINE> va... | Step 3: use UCB action selection. We'll pull all arms once first!
HINT: Check out p.27, equation 2.8 | 625941c4be8e80087fb20c2a |
def sendCmd(self,cmd): <NEW_LINE> <INDENT> self.write('{0}\n'.format(cmd).encode()) <NEW_LINE> rsp = self.readline() <NEW_LINE> self.clearBuffer() <NEW_LINE> if self.debug: <NEW_LINE> <INDENT> print('cmd: ', cmd) <NEW_LINE> print('rsp: ', rsp) <NEW_LINE> <DEDENT> if len(rsp) < 2: <NEW_LINE> <INDENT> raise(IOError, 'res... | Send command to colorimeter and receiver response. | 625941c445492302aab5e2a6 |
def _get_string_list(self): <NEW_LINE> <INDENT> strings = [] <NEW_LINE> lengths = [1, 10, 25, 100] <NEW_LINE> for i in lengths: <NEW_LINE> <INDENT> strings.append(create_format_string(i)) <NEW_LINE> <DEDENT> return strings | :return: This method returns a list of format strings. | 625941c4a8ecb033257d30b2 |
def sample_pairs(cases, size): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> l = len(cases) - 1 <NEW_LINE> i = 0 <NEW_LINE> while i < size: <NEW_LINE> <INDENT> index1 = random.randint(0, l) <NEW_LINE> index2 = random.randint(0, l) <NEW_LINE> if index1 == index2: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> ret.append((ca... | Returns (size) random pairs.
Key arguments:
cases -- the set of cases.
size -- the number of samples to return. | 625941c4462c4b4f79d1d6b5 |
def search_result_from_parent_map(parent_map, missing_keys): <NEW_LINE> <INDENT> if not parent_map: <NEW_LINE> <INDENT> return [], [], 0 <NEW_LINE> <DEDENT> start_set = set(parent_map) <NEW_LINE> result_parents = set(itertools.chain.from_iterable(parent_map.values())) <NEW_LINE> stop_keys = result_parents.difference(st... | Transform a parent_map into SearchResult information. | 625941c49c8ee82313fbb759 |
def check_role_requested_in_node(info: ResolveInfo) -> bool: <NEW_LINE> <INDENT> for field in info.field_asts[0].selection_set.selections: <NEW_LINE> <INDENT> if isinstance(field, InlineFragment): <NEW_LINE> <INDENT> if field.type_condition.name.value == 'ProjectType': <NEW_LINE> <INDENT> for field in field.selection_s... | Parses projectType node's field_asts and
check if current user role is requested | 625941c499cbb53fe6792bcb |
def put_items_into_redis_cache(self, items_to_cache): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for element in items_to_cache: <NEW_LINE> <INDENT> component = element.get("component", None) <NEW_LINE> version = element.get("version", None) <NEW_LINE> if component is not None and version is not None: <NEW_LINE> <INDENT> ... | Put list Items into cache
:param items_to_cache:
:return: item put count | 625941c45fc7496912cc3963 |
def as_string(self): <NEW_LINE> <INDENT> return self.as_json() | Returns a string representation.
| 625941c41d351010ab855b01 |
def Load(self): <NEW_LINE> <INDENT> internal_cfg = None <NEW_LINE> usr_cfg = None <NEW_LINE> try: <NEW_LINE> <INDENT> with open(self._internal_config_path) as config_file: <NEW_LINE> <INDENT> internal_cfg = self.LoadConfigFromProtocolBuffer( config_file, internal_config_pb2.InternalConfig) <NEW_LINE> <DEDENT> with open... | Load the configurations. | 625941c4aad79263cf390a23 |
def fun_35(subset, descr): <NEW_LINE> <INDENT> if descr == 235000: <NEW_LINE> <INDENT> subset._backref_record.restart() <NEW_LINE> <DEDENT> return None | Cancel backward data reference. | 625941c42ae34c7f2600d116 |
def __init__(self, atype): <NEW_LINE> <INDENT> self.aerotype = atype | Initialises the user-defined aerosol profile to a specific aerosol type.
Arguments:
* ``atype`` -- Aerosol type to be used for all layers. Must be one of the pre-defined types defined in this class. | 625941c48da39b475bd64f57 |
def ExistsHatenaID(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') | Missing associated documentation comment in .proto file. | 625941c4c432627299f04c29 |
def test_failed_company_update_user_does_not_have_appropriate_role(self): <NEW_LINE> <INDENT> company = CompanyFactory() <NEW_LINE> CompanyMemberFactory( user_id=self.user.id, company_id=company.id, role=CompanyMember.EMPLOYEE) <NEW_LINE> form = CompanyForm( obj=company, params=self.params, current_user=self.user ) <NE... | Test failed validation.
User does not have appropriate role in company | 625941c48e05c05ec3eea358 |
def run_command(self, name, config, cli_args): <NEW_LINE> <INDENT> logger.debug('Command "%s" chosen' % name) <NEW_LINE> options = cli_args.__dict__ <NEW_LINE> return registry.run(name, config, **options) | Load command from virtstrap.commands | 625941c4aad79263cf390a24 |
def main(gridpath, samples, file1, targV, beg, end): <NEW_LINE> <INDENT> run_rscript_fileout(path2script,[gridpath, samples, file1, targV,beg, end]) | Main entry point for the script. | 625941c4627d3e7fe0d68e34 |
def aliasByNode(requestContext, seriesList, *nodes): <NEW_LINE> <INDENT> for series in seriesList: <NEW_LINE> <INDENT> metric_pieces = re.search('(?:.*\()?(?P<name>[-\w*\.~:#]+)(?:,|\)?.*)?', series.name).groups()[0].split('.') <NEW_LINE> series.name = '.'.join(metric_pieces[n] for n in nodes) <NEW_LINE> <DEDENT> retur... | Takes a seriesList and applies an alias derived from one or more "node"
portion/s of the target name. Node indices are 0 indexed.
Example::
&target=aliasByNode(ganglia.*.cpu.load5,1) | 625941c41f5feb6acb0c4b37 |
def create_option_parser(): <NEW_LINE> <INDENT> parser = optparse.OptionParser() <NEW_LINE> parser.add_option('-i', '--input-file', dest='input_file', default='cc/licenserdf/rdf/ns.html', help='Input file containing HTML + RDFa.') <NEW_LINE> parser.add_option('-o', '--output-file', dest='output_file', default='cc/licen... | Return an optparse.OptionParser configured for the merge script. | 625941c44527f215b584c43e |
def parse_developers_info(self, tag, limit): <NEW_LINE> <INDENT> trending = {} <NEW_LINE> for content in tag: <NEW_LINE> <INDENT> repositories = content.find_all('li') <NEW_LINE> for index, list_item in enumerate(repositories, start=1): <NEW_LINE> <INDENT> repo_name, url = self.get_developer_repo(list_item) <NEW_LINE> ... | Scrape trending developer info
:return A dictionary with all trending developers filtered by arguments from user | 625941c445492302aab5e2a7 |
def __init__(self, pid, gid) : <NEW_LINE> <INDENT> self.pid = pid <NEW_LINE> self.gid = gid <NEW_LINE> self.tools = Tools() <NEW_LINE> self.local = ProjLocal(pid) <NEW_LINE> self.user = UserConfig() <NEW_LINE> ... | Do the primary initialization for this class. | 625941c4ec188e330fd5a787 |
def isRotation(s1, s2): <NEW_LINE> <INDENT> return isSubString(s1 + s1, s2) | Take O(n) time and O(n) space
:param s1: Input String s1
:param s2: Input String s2
:return: result | 625941c4f8510a7c17cf96e0 |
def ifft2(data): <NEW_LINE> <INDENT> assert data.size(-1) == 2 <NEW_LINE> data = ifftshift(data, dim=(-3, -2)) <NEW_LINE> data = ifft(data, 2, normalized=True) <NEW_LINE> data = fftshift(data, dim=(-3, -2)) <NEW_LINE> return data | Apply centered 2-dimensional Inverse Fast Fourier Transform.
Args:
data (torch.Tensor): Complex valued input data containing at least 3 dimensions: dimensions
-3 & -2 are spatial dimensions and dimension -1 has size 2. All other dimensions are
assumed to be batch dimensions.
Returns:
torch.Ten... | 625941c45f7d997b87174a7b |
def force(self, wait=True): <NEW_LINE> <INDENT> if(wait): <NEW_LINE> <INDENT> self.sync() <NEW_LINE> <DEDENT> return self.robotConnector.RobotModel.TcpForceScalar() | Returns the force exerted at the TCP
Return the current externally exerted force at the TCP. The force is the
norm of Fx, Fy, and Fz calculated using get tcp force().
Return Value
The force in Newtons (float) | 625941c44428ac0f6e5ba7d6 |
def del_profile(profile): <NEW_LINE> <INDENT> profile.delete_profile() | Method that deletes a profile | 625941c43cc13d1c6d3c7360 |
def add_version( self, current_did, form, new_did=None, size=None, file_name=None, metadata=None, urls_metadata=None, version=None, urls=None, acl=None, authz=None, hashes=None, ): <NEW_LINE> <INDENT> urls = urls or [] <NEW_LINE> acl = acl or [] <NEW_LINE> authz = authz or [] <NEW_LINE> hashes = hashes or {} <NEW_LINE>... | Add a record version given did | 625941c4099cdd3c635f0c41 |
def equals(self, value, context): <NEW_LINE> <INDENT> return self.constant_value is not None and self.constant_value == value | Check if this constant equals ``value``. | 625941c46e29344779a625f9 |
def test_create(self): <NEW_LINE> <INDENT> a = Post(title='title', body='body') <NEW_LINE> assert a.title == 'title' <NEW_LINE> assert a.body == 'body' <NEW_LINE> assert a.post_id is None, 'post is empty before commit' <NEW_LINE> assert self.session.add(a) is None <NEW_LINE> assert self.session.commit() is None <NEW_LI... | Create and store a Post
:return: None | 625941c491f36d47f21ac4d6 |
def test_flow_1(): <NEW_LINE> <INDENT> coinbase_0 = Tx( [TxIn(OutPoint("00" * 32, 0), Script.from_hex("00030000aa"))], [TxOut(10 ** 10, Script())], ) <NEW_LINE> origin_transactions = [coinbase_0] <NEW_LINE> origin_header = BlockHeader("00" * 32, generate_merkle_root(origin_transactions), 0) <NEW_LINE> origin = Block(or... | This MUST NOT fail
We simply add two blocks, each one with only the coinbase transaction | 625941c497e22403b379cf7f |
def test_memory_use(): <NEW_LINE> <INDENT> folder = os.path.split(__file__)[0] <NEW_LINE> src = os.path.join(folder, "files", "very_large.xlsx") <NEW_LINE> wb = openpyxl.load_workbook(src, use_iterators=True) <NEW_LINE> ws = wb.active <NEW_LINE> initial_use = None <NEW_LINE> for n, line in enumerate(ws.iter_rows()): <N... | Naive test that assumes memory use will never be more than 120 % of
that for first 50 rows | 625941c450812a4eaa59c309 |
def gettracker(file, host, port): <NEW_LINE> <INDENT> message = "<GET {}.track>".format(apiutils.arg_encode(file)) <NEW_LINE> response = networkutil.send(host, port, message) <NEW_LINE> match = apiutils.re_apicommand.match(response) <NEW_LINE> if match and match.group("command") == "REP": <NEW_LINE> <INDENT> payload = ... | Sends a GET request for a tracker file
| 625941c4fbf16365ca6f61a6 |
def _unsort_tensor(self, input, invert_order, num_zero): <NEW_LINE> <INDENT> if num_zero == 0: <NEW_LINE> <INDENT> input = input.index_select(0, invert_order) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dim0, dim1, dim2 = input.size() <NEW_LINE> zero = torch.zeros(num_zero, dim1, dim2) <NEW_LINE> if self.args.cuda: <... | Recover the origin order
Input:
input: batch_size-num_zero, seq_len, hidden_dim
invert_order: batch_size
num_zero
Output:
out: batch_size, seq_len, * | 625941c4f9cc0f698b1405e2 |
def __setitem__(self, key, value): <NEW_LINE> <INDENT> if key == '_id': <NEW_LINE> <INDENT> self.__internal['id'] = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__internal[key] = value | Required for use by pymongo as_class parameter to find. | 625941c4adb09d7d5db6c776 |
def shiftWavelengthArray(self, wavelength_array, shift_velocity): <NEW_LINE> <INDENT> return shift_wavelength(wavelength_array, shift_velocity) | Doppler shift a wavelength array by an amount equivalent to a given
velocity.
Parameters
----------
wavelength_array : `unyt.unyt_array`
An array containing wavelengths to be Doppler shifted. Needs units
of dimension length.
velocity : `unyt.unyt_quantity`
A Unyt quantity with dimensions length/time to shi... | 625941c43eb6a72ae02ec4be |
def extract_items( buff_response, response_item_len ): <NEW_LINE> <INDENT> result_obj = AnalysisResult() <NEW_LINE> for i in range( 0, len( buff_response ), response_item_len ): <NEW_LINE> <INDENT> item = buff_response[i:i + response_item_len] <NEW_LINE> if item[response_item_len - 1] == HASH_SEARCH_FOUND: <NEW_LINE> <... | 64 bytes of SHA256 (or 32 bytes of MD5) string plus 1 byte of result string
(0 FOUND, 1 NOT_FOUND, 2 ERROR):
00001D55121052597C78A59CADCE6F218C88A4F270A577132FBC3C834F4C6C760
00001D55121052597C78A59CADCE6F218C88A4F270A577132FBC3C834F4C6C761
00001D55121052597C78A59CADCE6F218C88A4F270A577132FBC3C834F4C6C762 | 625941c44c3428357757c30e |
def longestPalindrome(self, s: str) -> str: <NEW_LINE> <INDENT> if len(s) < 2: return s <NEW_LINE> longest_palindrome = s[0] <NEW_LINE> for i in range(len(s)): <NEW_LINE> <INDENT> p = self.expandPalindrome((i, i+ 1), s) <NEW_LINE> if p[1] - p[0] > len(longest_palindrome): longest_palindrome = s[p[0]:p[1]] <NEW_LINE> <D... | Find the longest palindrome in string s | 625941c46fece00bbac2d722 |
def inputArrowStyle(self): <NEW_LINE> <INDENT> return self._inputArrowStyle | Returns the arrow style for this connection.
:return <XNodeConnection.ArrowStyle> | 625941c444b2445a3393207c |
def update_account_info(self): <NEW_LINE> <INDENT> request = self._get_request() <NEW_LINE> resp = request.post(self.ACCOUNT_UPDATE_URL, { 'callback_url': self.account.callback_url }) <NEW_LINE> return Account(resp['account']) | Update current account information
At the moment you can only update your callback_url.
Returns:
An Account object | 625941c4a05bb46b383ec808 |
def totalSpace(self): <NEW_LINE> <INDENT> return QUrl() | static QUrl Nepomuk.Vocabulary.NFO.totalSpace() | 625941c44e4d5625662d43bf |
def logout(self): <NEW_LINE> <INDENT> self._loggined = None <NEW_LINE> rpc_params = {} <NEW_LINE> cr = self._remote.call("auth.logout", rpc_params) <NEW_LINE> return utils.extract_result(cr) | Logout to stop using the data api or switch users. | 625941c4283ffb24f3c558e8 |
def __call__(self, lang=None): <NEW_LINE> <INDENT> if lang is None: <NEW_LINE> <INDENT> return self.values[self.get_lang()] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.values[lang] | Return the value in the requested language.
While lang is None, self.lang (currently set language) is used.
Otherwise, the standard algorithm is used (see above). | 625941c4e8904600ed9f1f10 |
def remove_from_dict(dictionary: Dict, keys: List[str] = []) -> Dict: <NEW_LINE> <INDENT> r <NEW_LINE> for k in keys: <NEW_LINE> <INDENT> assert k in dictionary, f"{k} not in dict {dictionary}" <NEW_LINE> del dictionary[k] | Safely remove a list of keys from a dictionary | 625941c4a8ecb033257d30b3 |
def safe_encode(s, coding='utf-8', errors='surrogateescape'): <NEW_LINE> <INDENT> if type(s) == str: <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> elif s is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return s.encode(coding, errors) | encode str to bytes, with round-tripping "invalid" bytes | 625941c47b25080760e3943f |
def computeMoments(self): <NEW_LINE> <INDENT> self.moments = cv2.moments(self.gray) <NEW_LINE> return self.moments | Computes the moments of this eye.
Returns:
np.array: Moments | 625941c438b623060ff0add3 |
def _interpolate_in_index_html(self): <NEW_LINE> <INDENT> path = os.path.join(self.out_dir, 'index.html') <NEW_LINE> with open(path) as fp: <NEW_LINE> <INDENT> content = fp.read() <NEW_LINE> <DEDENT> today = strftime('%d %B %Y') <NEW_LINE> content = interpolate(content, last_update=today) <NEW_LINE> with open(path, 'w+... | Replace dynamic content in ``index.html``. | 625941c476d4e153a657eb16 |
@api.model <NEW_LINE> def fields_view_get( self, view_id=None, view_type='form', toolbar=False, submenu=False): <NEW_LINE> <INDENT> View = self.env['ir.ui.view'] <NEW_LINE> result = self._fields_view_get( view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu) <NEW_LINE> if view_id and result.get('base_... | fields_view_get([view_id | view_type='form'])
Get the detailed composition of the requested view
like fields, model, view architecture
:param view_id: id of the view or None
:param view_type: type of the view to return if
view_id is None ('form', 'tree', ...)
:param toolbar: true to include contextual actions
:param ... | 625941c45f7d997b87174a7c |
def dispatch(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if 'error' in request.GET or 'code' not in request.GET: <NEW_LINE> <INDENT> auth_error = request.GET.get('error', None) <NEW_LINE> if auth_error == self.adapter.login_cancelled_error: <NEW_LINE> <INDENT> error = AuthError.CANCELLED <NEW_LINE> <DEDENT> el... | This dispatch is responsible for a few things:
1. To show an authentication error, if raised
2. To use the `code` parameter received from the provider, and get
the access token.
3. To use the access token to get basic user information from the
provider
4. To create user account and social account if they don't exist
an... | 625941c4f7d966606f6a9fe8 |
def __init__(self, cfg_groups: dict, cfg_redis: dict = None, log_level: Union[str, int] = 'WARNING'): <NEW_LINE> <INDENT> self.log = logging.getLogger(self.__class__.__name__) <NEW_LINE> self.log.setLevel(log_level) <NEW_LINE> self.log_level = log_level <NEW_LINE> self.warning_printed = set() <NEW_LINE> self.log.debug(... | Initialize the class using given configuration.
:param cfg_groups: dict containing specification of event groups
:param cfg_redis: dict containing Redis connection parameters (keys are passed directly to Connection() class
from redis-py package, normally 'host', 'port' and 'db' are expected to be con... | 625941c421a7993f00bc7cd3 |
def transfer_multiple(self, destinations, priority=prio.NORMAL, payment_id=None, unlock_time=0, relay=True): <NEW_LINE> <INDENT> return self.accounts[0].transfer_multiple( destinations, priority=priority, payment_id=payment_id, unlock_time=unlock_time, relay=relay) | Sends a batch of transfers from the default account. Returns a list of resulting
transactions.
:param destinations: a list of destination and amount pairs: [(address, amount), ...]
:param priority: transaction priority, implies fee. The priority can be a number
from 1 to 4 (unimportant, normal, elevated, p... | 625941c4fb3f5b602dac3677 |
def __init__(self, param, description = ''): <NEW_LINE> <INDENT> if not isinstance(param, int): <NEW_LINE> <INDENT> raise TypeError() <NEW_LINE> <DEDENT> if param < 0: <NEW_LINE> <INDENT> raise ValueError() <NEW_LINE> <DEDENT> if not isinstance(description, str) and description is not None: <NEW_LINE> <INDENT> raise Ty... | Initializes this instance..
:param param: Must be the index of the parameter that was parsed (starting with 0 for the first argument)
:param description: An optional description of why argument parsing failed | 625941c4283ffb24f3c558e9 |
def env_discrete(nenv): <NEW_LINE> <INDENT> return make_env('CartPole-v1', nenv=nenv) | Create discrete env. | 625941c4baa26c4b54cb1107 |
def user_asdict(self) -> dict: <NEW_LINE> <INDENT> return attr.asdict(self) | Return user data as dict | 625941c47cff6e4e8111796c |
def test_order_mw_executed_when_exception_in_resp(self): <NEW_LINE> <INDENT> global context <NEW_LINE> class RaiseErrorMiddleware(object): <NEW_LINE> <INDENT> def process_response(self, req, resp, resource): <NEW_LINE> <INDENT> raise Exception('Always fail') <NEW_LINE> <DEDENT> <DEDENT> self.api = falcon.API(middleware... | Test that error in inner middleware leaves | 625941c4377c676e9127218f |
def arrangeCoins(self, n): <NEW_LINE> <INDENT> sum = 0 <NEW_LINE> i = 0 <NEW_LINE> while sum <= n: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> sum += i <NEW_LINE> <DEDENT> return i - 1 | :type n: int
:rtype: int | 625941c43cc13d1c6d3c7361 |
def t_REGEX(t): <NEW_LINE> <INDENT> return t | /([^/\s]|\/)+/ | 625941c43346ee7daa2b2d51 |
def test_smoke(self): <NEW_LINE> <INDENT> assert self.passes("""Smoke phrase with nothing flagged.""") <NEW_LINE> assert not self.passes("""Please enter your PIN number.""") | Basic smoke test for redundancy.ras_syndrome. | 625941c4be7bc26dc91cd5e8 |
def CalculatePercentiles(latencies, percentiles=(0, 50, 75, 90, 95, 99, 100)): <NEW_LINE> <INDENT> values = [d for _, d in latencies if not math.isnan(d)] <NEW_LINE> if values: <NEW_LINE> <INDENT> vals = numpy.percentile(sorted([abs(v) for v in values]), percentiles).tolist() <NEW_LINE> return zip(percentiles, vals) <N... | Calculates the latency percentiles.
Args:
latencies: (list) list of 2-tuples (<time>, <latency>).
percentiles: (tuple) tuple containing the percentiles to calculate.
Returns:
A list of the form [(<percentile>, abs(<value>)), ...] for each of
the percentiles requested. | 625941c4be7bc26dc91cd5e9 |
def notify(_context, message): <NEW_LINE> <INDENT> priority = message.get('priority', CONF.default_notification_level) <NEW_LINE> priority = priority.lower() <NEW_LINE> logger = logging.getLogger( 'designate.openstack.common.notification.%s' % message['event_type']) <NEW_LINE> getattr(logger, priority)(jsonutils.dumps(... | Notifies the recipient of the desired event given the model.
Log notifications using OpenStack's default logging system. | 625941c4236d856c2ad447be |
def withdraw(): <NEW_LINE> <INDENT> global customerList <NEW_LINE> step = 0 <NEW_LINE> trgAccount = "" <NEW_LINE> wdrMoney = 0 <NEW_LINE> print("-" * 80) <NEW_LINE> print("main menu > withdraw") <NEW_LINE> print(" * The withdraw is higher than 10,000") <NEW_LINE> while 1: <NEW_LINE> <INDENT> if(step == 0): <NEW_LINE> <... | withdraw method | 625941c473bcbd0ca4b2c05c |
def test_log_check(self): <NEW_LINE> <INDENT> self.logger.log_check(description=self.some_text) <NEW_LINE> self.mock_logger_1.log_check.assert_called_once_with(description=self.some_text) <NEW_LINE> self.mock_logger_2.log_check.assert_called_once_with(description=self.some_text) | Given: A FuzzLogger with multiple IFuzzLoggerBackends.
When: Calling log_check() with some text.
Then: log_check() is called with that same text on each
IFuzzLoggerBackend. | 625941c49c8ee82313fbb75a |
def load_addr(self, sym_a, sym_b, sym_offset=None): <NEW_LINE> <INDENT> aprint("# load_addr implemented") <NEW_LINE> reg_b = self.get_reg(sym_b) <NEW_LINE> if not sym_offset: <NEW_LINE> <INDENT> aprint(ADDI, REG_, reg_b, REG_, self.sp_reg, sym_a.offset) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> reg_offset = self.ge... | runtime load the address of sym_a to sym_b | 625941c455399d3f05588699 |
def register_pruning_hook(model, user_params): <NEW_LINE> <INDENT> pruning_layers = [ "bert.embeddings", "bert.encoder" ] <NEW_LINE> pruning = SparsePruning(model, pruning_layers, user_params['total_training_steps'], user_params['epoch_per_training_step'], t0=user_params['fine_tune_steps'], initial_sparsity=user_params... | initiate prunning object and hook it so it will activate before the forward begins | 625941c415baa723493c3f5a |
def print_score(self): <NEW_LINE> <INDENT> print("Your score is %d / %d." % (self.score, TOTAL_SCORE)) | Prints the score. | 625941c4097d151d1a222e41 |
def get_file_hash(self): <NEW_LINE> <INDENT> import hashlib <NEW_LINE> file_path = self.get_file_path() <NEW_LINE> if(not file_path): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> hash_object = hashlib.md5(file_path.encode('utf-8')) <NEW_LINE> return hash_object.hexdigest() | Hash File Path
Unique hash based in the file path
Returns:
str -- hash of the file path | 625941c463f4b57ef0001103 |
def get_sinfo_nogroup(gfile): <NEW_LINE> <INDENT> tabinfo = {} <NEW_LINE> gfh = open(gfile) <NEW_LINE> for line in gfh: <NEW_LINE> <INDENT> tinfo = line.rstrip().split('\t') <NEW_LINE> tabinfo[tinfo[0]] = tinfo[1] <NEW_LINE> <DEDENT> gfh.close() <NEW_LINE> return tabinfo | Samples are not divided into groups.
Sample info file:
table_name1 label1
table_name2 label2
Return:
o tabinfo - dict | 625941c46fece00bbac2d723 |
def _probe_all_channels(probe): <NEW_LINE> <INDENT> cgs = probe['channel_groups'].values() <NEW_LINE> cg_channels = [cg['channels'] for cg in cgs] <NEW_LINE> return sorted(set(itertools.chain(*cg_channels))) | Return the list of channels in the probe. | 625941c429b78933be1e5695 |
def create_edge(con_type, site_link, guid_to_vertex): <NEW_LINE> <INDENT> e = MultiEdge() <NEW_LINE> e.site_link = site_link <NEW_LINE> e.vertices = [] <NEW_LINE> for site_guid in site_link.site_list: <NEW_LINE> <INDENT> if str(site_guid) in guid_to_vertex: <NEW_LINE> <INDENT> e.vertices.extend(guid_to_vertex.get(str(s... | Set up a MultiEdge for the intersite graph
A MultiEdge can have multiple vertices.
From MS-ADTS 6.2.2.3.4.4
:param con_type: a transport type GUID
:param site_link: a kcc.kcc_utils.SiteLink object
:param guid_to_vertex: a mapping between GUIDs and vertices
:return: a MultiEdge | 625941c4a4f1c619b28b0023 |
def StateTransitionGraph(M): <NEW_LINE> <INDENT> G = dict([(S,{}) for S in M]) <NEW_LINE> for S in M: <NEW_LINE> <INDENT> for t in M.tokens(): <NEW_LINE> <INDENT> St = M(S,t) <NEW_LINE> if St != S: <NEW_LINE> <INDENT> if St in G[S]: <NEW_LINE> <INDENT> raise MediumError("multiple adjacency from %s to %s" % (S,St)) <NEW... | Build a graph G describing the states and transitions of medium M.
If s is a state of M, G[s] will provide a dictionary mapping
the neighbors of s to the actions that produced those neighbors. | 625941c426068e7796caecc3 |
def create_asteroids(self): <NEW_LINE> <INDENT> maxspeed = self.speed <NEW_LINE> asteroids = set() <NEW_LINE> for size, count in enumerate(self.asteroids): <NEW_LINE> <INDENT> size += 1 <NEW_LINE> for _ in xrange(count): <NEW_LINE> <INDENT> asteroids.add( entity.Asteroid(size, maxspeed) ) <NEW_LINE> <DEDENT> <DEDENT> r... | Returns a set of asteroid objects | 625941c45fc7496912cc3964 |
def rand_email_address(self): <NEW_LINE> <INDENT> return ( f'{self.tcex.utils.random_string(randint(5,15))}@' f'{self.tcex.utils.random_string(randint(5,15))}.com' ).lower() | Return a random email subject. | 625941c41b99ca400220aa98 |
def s(p,q,r,ini,times): <NEW_LINE> <INDENT> imt = it.accumulate(it.repeat(ini),lambda x , _ : (x[1] , x[1] * q + x[0] * p + r)) <NEW_LINE> lst= map(lambda x: x[0],imt) <NEW_LINE> return [next(lst) for _ in range(times)] | Use second order formula
S= S[n-1]*P+S[n-2]*Q+R to generate any second order
sequences
for instance:P=1,Q=1,R=0 is Fib seqencces
S = S[n-1]+S[n-2]
p for how many S[n-1]
s for how many S[n-2]
r for how many to add on
ini for first 2 values
times for how many value you would like to obtain | 625941c4d6c5a10208144030 |
def in_ipv4_subnet(self, ipv4network=IPv4Obj('0.0.0.0/32', strict=False)): <NEW_LINE> <INDENT> if not (str(self.ipv4_addr_object.ip)=="127.0.0.1"): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.ipv4_network_object in ipv4network <NEW_LINE> <DEDENT> except (Exception) as e: <NEW_LINE> <INDENT> raise ValueErro... | Accept an argument for the :class:`~ccp_util.IPv4Obj` to be
considered, and return a boolean for whether this interface is within
the requested :class:`~ccp_util.IPv4Obj`.
Kwargs:
- ipv4network (:class:`~ccp_util.IPv4Obj`): An object to compare against IP addresses configured on this :class:`~models_cisco.IOSIntf... | 625941c463b5f9789fde70cc |
def _get_group(self, name): <NEW_LINE> <INDENT> groups = bpy.data.groups <NEW_LINE> if name in groups.keys(): <NEW_LINE> <INDENT> group = groups[name] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> group = bpy.data.groups.new(name) <NEW_LINE> <DEDENT> return group | name: name of group (String)
Finds group by name or creates it if it does not exist. | 625941c467a9b606de4a7ea1 |
def a_1_2(): <NEW_LINE> <INDENT> pass | >>> a = [3, 1, 4, 2, 5, 3]
>>> a[1::2]
[1, 2, 3]
>>> a[:]
[3, 1, 4, 2, 5, 3]
>>> a[4:2]
[]
>>> a[1:-2]
[1, 4, 2]
>>> a[::-1]
[3, 5, 2, 4, 1, 3] | 625941c45fdd1c0f98dc0219 |
def main(): <NEW_LINE> <INDENT> poly = [float(x) for x in input().split()] <NEW_LINE> x = float(input()) <NEW_LINE> print(numpy.polyval(poly, x)) | Main function. | 625941c45510c4643540f3cf |
def _eda_simulate_scr(sampling_rate=1000, length=None, time_peak=3.0745, rise=0.7013, decay=[3.1487, 14.1257]): <NEW_LINE> <INDENT> if length is None: <NEW_LINE> <INDENT> length = 9 * sampling_rate <NEW_LINE> <DEDENT> t = np.linspace(sampling_rate / 10000, 90, length) <NEW_LINE> gt = np.exp(-((t - time_peak) ** 2) / (2... | Simulate a canonical skin conductance response (SCR)
Based on `Bach (2010)
<https://sourceforge.net/p/scralyze/code/HEAD/tree/branches/version_b2.1.8/scr_bf_crf.m#l24>`_
Parameters
-----------
sampling_rate : int
The desired sampling rate (in Hz, i.e., samples/second). Defaults to 1000Hz.
length : int
The des... | 625941c415baa723493c3f5b |
def STJ(self, address, F, C) -> None: <NEW_LINE> <INDENT> self.ST(self.rJ, address, F) | Same as ST, except that rJ is stored, and its sign is always
positive.
With STJ, the normal field specification for F is (0:2), not
(0:5) | 625941c450485f2cf553cd80 |
def make_sql(self, **kwargs): <NEW_LINE> <INDENT> dataList = [] <NEW_LINE> dataList.append((self._sql_id, kwargs.get('con_id', None))) <NEW_LINE> dataList.append((self._sql_hash, kwargs.get('con_hash', None))) <NEW_LINE> token = kwargs.get('token', None) <NEW_LINE> if token != None: <NEW_LINE> <INDENT> token = b64encod... | get the enter limited and return a sql cmd. | 625941c482261d6c526ab483 |
def process_item(self, item, spider): <NEW_LINE> <INDENT> self._item_buffer.append(item) <NEW_LINE> if len(self._item_buffer) >= config.crawling_local_storage_buffer_size: <NEW_LINE> <INDENT> self.__write_buffer_to_disk() | Process the given Scrapy item for writing to the local filesystem.
:param item: The item to process.
:param spider: The spider that resulted in this method being called.
:return: None | 625941c45fc7496912cc3965 |
@pytest.mark.parametrize('error', [False, True]) <NEW_LINE> def test_empty(tmpdir, caplog, error): <NEW_LINE> <INDENT> tmpdir.ensure('contents.rst') <NEW_LINE> local_conf = tmpdir.join('conf.py') <NEW_LINE> if error: <NEW_LINE> <INDENT> local_conf.write('undefined') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> local_c... | With no settings defined.
:param tmpdir: pytest fixture.
:param caplog: pytest extension fixture.
:param bool error: Malformed conf.py. | 625941c421bff66bcd68493b |
def test_login_denied_calls_TemplateCallArgsBasicCheck(self): <NEW_LINE> <INDENT> log = [] <NEW_LINE> def callback(*args): <NEW_LINE> <INDENT> log.append(args) <NEW_LINE> <DEDENT> class AuthenticatorMock: <NEW_LINE> <INDENT> def forget(self): return <NEW_LINE> <DEDENT> class UIMock: <NEW_LINE> <INDENT> username = "fake... | login_denied - The first argument sent to the template callback should request the "login_auth.html" template, the second should be a dictionary of key/value arguments to fill the template with | 625941c48e71fb1e9831d791 |
def backup(self): <NEW_LINE> <INDENT> return self.func.backup | return the backup policy as given by the underlying editor function
| 625941c42ae34c7f2600d118 |
def click_newhouse_detail_kptz(self): <NEW_LINE> <INDENT> with allure.step("新房详情页点击开盘通知我"): <NEW_LINE> <INDENT> self.steps("../../page_object/newhouse/newhousedetail.yaml") <NEW_LINE> <DEDENT> self.tsleep(2) <NEW_LINE> return self | 新房详情页点击开盘通知我
:return: | 625941c4236d856c2ad447bf |
def create(self, request, *args, **kwargs): <NEW_LINE> <INDENT> serializer = self.get_serializer(data=request.data) <NEW_LINE> serializer.is_valid(raise_exception=True) <NEW_LINE> self.perform_create(serializer) <NEW_LINE> return get_data_response(serializer.data, code=status.HTTP_201_CREATED) | 单个对象创建入口 | 625941c4d18da76e235324bb |
def test_server_for_weather_bot(self): <NEW_LINE> <INDENT> with mock.patch('server.addToDb', return_value=True): <NEW_LINE> <INDENT> with mock.patch('server.Bot.getWeather') as getBot: <NEW_LINE> <INDENT> getBot.return_value = 'weather details' <NEW_LINE> for message in ['!! weather newark', '!! weather']: <NEW_LINE> <... | function to mock weather sever | 625941c43539df3088e2e331 |
def main(): <NEW_LINE> <INDENT> poly = PolyglotConnector() <NEW_LINE> nserver = HarmonyHubNodeServer(poly, shortpoll=30, longpoll=300) <NEW_LINE> poly.connect() <NEW_LINE> poly.wait_for_config() <NEW_LINE> nserver.setup() <NEW_LINE> nserver.run() | setup connection, node server, and nodes | 625941c416aa5153ce36245f |
def setOperator(mode, operator=None): <NEW_LINE> <INDENT> req = '' <NEW_LINE> if operator is not None: <NEW_LINE> <INDENT> if (type(operator) == int): <NEW_LINE> <INDENT> req = "AT+COPS=%d,2,%d" % (mode, operator) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> req = "AT+COPS=%d,0,\"%s\"" % (mode, operator) <NEW_LINE> <D... | Sets the network operator and registration mode.
Command: AT+COPS
@param mode:
The connection/registration mode. Must be on of the C{MODE_...}
constants.
@type mode:
int
@param operator:
The operator the module should connect to. Only used when
mode is set to C{MODE_MANUAL} or C{MODE_AUTOSWITCH}. ... | 625941c4596a897236089aa9 |
def streamMetricData(self, data, metricID, modelSwapper): <NEW_LINE> <INDENT> if not data: <NEW_LINE> <INDENT> self._log.warn("Empty input metric data batch for metric=%s", metricID) <NEW_LINE> return <NEW_LINE> <DEDENT> @repository.retryOnTransientErrors <NEW_LINE> def storeDataWithRetries(): <NEW_LINE> <INDENT> with ... | Store the data samples in metric_data table if needed, and stream the
data samples to the model associated with the metric if the metric is
monitored.
If the metric is in PENDING_DATA state: if there are now enough data samples
to start a model, start it and stream it the entire backlog of data samples;
if there are s... | 625941c41f5feb6acb0c4b39 |
def join(self): <NEW_LINE> <INDENT> if self.p: <NEW_LINE> <INDENT> logging.info("Wating process with id: %d finish" % self.p.pid()) <NEW_LINE> return self.p.join() <NEW_LINE> <DEDENT> return None | wait process finish | 625941c476e4537e8c351658 |
def __mul__(self, b, imap=imap, izip=izip): <NEW_LINE> <INDENT> return imap(lambda row: imap(lambda col: itermatrix.sumprod(row, col), izip(*b)), self) | Matrix multiplication returning iterable of iterables | 625941c4ec188e330fd5a789 |
def get_userid(self, query, field=None): <NEW_LINE> <INDENT> users = self._slack.api_call('users.list')['members'] <NEW_LINE> if not field: <NEW_LINE> <INDENT> field = self._search_field <NEW_LINE> <DEDENT> for user in users: <NEW_LINE> <INDENT> if field in user: <NEW_LINE> <INDENT> if user[field] == query: <NEW_LINE> ... | uses the configured field and supplied value to search for and returns slack userid | 625941c407d97122c417886f |
def End(self): <NEW_LINE> <INDENT> return _btk.btkPointCollection_End(self) | End(self) -> btkPointIterator
Returns an iterator just past the last item. | 625941c43346ee7daa2b2d52 |
def __len__(self): <NEW_LINE> <INDENT> if hasattr(self, 'items'): <NEW_LINE> <INDENT> return len(self.items) <NEW_LINE> <DEDENT> return 0 | Returns the number of items this Page holds | 625941c494891a1f4081ba8f |
def process_overrides(self): <NEW_LINE> <INDENT> if zkshop.o_light.event == True: <NEW_LINE> <INDENT> if zkshop.o_light.value == True: <NEW_LINE> <INDENT> logging.info("override commanded light on ... doing it") <NEW_LINE> zkshop.light.value = True <NEW_LINE> <DEDENT> elif zkshop.o_light.value == False: <NEW_LINE> <IND... | take the appropriate actions based on the override values changing | 625941c4090684286d50eccb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.