code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def add_in_uc(self, tx): <NEW_LINE> <INDENT> self.in_uc.append(tx) | add a transaction to unconfirmed incoming tx array
:param tx: | 625941c4236d856c2ad447b4 |
def _write_packet(self, final): <NEW_LINE> <INDENT> status = 1 if final else 0 <NEW_LINE> _header.pack_into(self._buf, 0, self._type, status, self._pos, 0, self._packet_no) <NEW_LINE> self._packet_no = (self._packet_no + 1) % 256 <NEW_LINE> self.data += self._buf[:self._pos] <NEW_LINE> self._pos = 8 | Writes single TDS packet into underlying transport.
Data for the packet is taken from internal buffer.
:param final: True means this is the final packet in substream. | 625941c4f7d966606f6a9fdf |
def send_goal(self, group_name, pose, done_cb=None): <NEW_LINE> <INDENT> if isinstance(pose, geometry_msgs.msg.Pose): <NEW_LINE> <INDENT> goal = PlanMoveEEGoal() <NEW_LINE> goal.group_name = group_name <NEW_LINE> goal.pose = pose <NEW_LINE> goal.trans_only = False <NEW_LINE> util.info("Client sending goal [%s, %s]" % (... | "`pose` can either be a Pose, a list of coordinates for
end effector pose or a list of joint values | 625941c42eb69b55b151c889 |
def init_app(db_path: str) -> int: <NEW_LINE> <INDENT> config_code = _init_config_file() <NEW_LINE> if config_code != SUCCESS: <NEW_LINE> <INDENT> return config_code <NEW_LINE> <DEDENT> database_code = _create_database(db_path) <NEW_LINE> if database_code != SUCCESS: <NEW_LINE> <INDENT> return database_code <NEW_LINE> ... | Initialize the application. | 625941c430dc7b7665901944 |
def chain_expand(p: Probability, *, reorder: bool = True, ordering: OrderingHint = None) -> Product: <NEW_LINE> <INDENT> if reorder: <NEW_LINE> <INDENT> _ordering = ensure_ordering(p, ordering=ordering) <NEW_LINE> if any(v not in _ordering for v in p.children): <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> o... | Expand a probability distribution to a product of conditional probabilities on single variables.
:param p: The given probability expression
:param reorder: Should the variables be reordered with respect to the ordering before expanding? This is important
because there are a variety of equivalent expressions that c... | 625941c4460517430c394165 |
def items(self): <NEW_LINE> <INDENT> yield from map(lambda x: (x[0], x[1].value), self._hparams.items()) | Returns an iterator of (hyp. name, hyp. value) items
| 625941c4287bf620b61d3a41 |
def compatible_moves_for_agent(mas, agents, agent, moves, filtered): <NEW_LINE> <INDENT> agent_cube = mas.inputs_cube_for_agents({agent}) <NEW_LINE> others_cube = mas.bddEnc.inputsCube - agent_cube <NEW_LINE> compatible = BDD.false(mas) <NEW_LINE> while moves.isnot_false(): <NEW_LINE> <INDENT> si = mas.pick_one_state_i... | Return the subset of given moves for agents that are non-agent-conflicting
with the filtered set of moves.
mas -- a multi-agents system;
agents -- a subset of agents of mas;
agent -- an agent of agents;
moves -- a subset of moves for agents;
filtered -- a subset of moves for agents. | 625941c44a966d76dd550fea |
def black_litterman(w_prior, Sigma_prior, P, Q, Omega=None, delta=2.5, tau=0.02): <NEW_LINE> <INDENT> if Omega is None: <NEW_LINE> <INDENT> Omega = omega_uncertain_prior(Sigma_prior, tau, P) <NEW_LINE> <DEDENT> N = w_prior.shape[0] <NEW_LINE> K = Q.shape[0] <NEW_LINE> Pi = implied_returns(Sigma_prior, w_prior, delta) ... | Black-Litterman model.
Computes the posterior expected returns and covariaces based on the original Black-Litterman model
using the Master formulas, where:
- w_prior is the N x 1 pd.Series of prior weights
- Sigma_prior is the N x N covariance matrix as a pd.DataFrame
- P is the projection K x N matrix of weights port... | 625941c430bbd722463cbda1 |
def createTasksBySize( self, lfns, replicaSE, fileSizes = None, flush = False ): <NEW_LINE> <INDENT> tasks = [] <NEW_LINE> if fileSizes is None: <NEW_LINE> <INDENT> fileSizes = self._getFileSize( lfns ).get( 'Value' ) <NEW_LINE> <DEDENT> if fileSizes is None: <NEW_LINE> <INDENT> self.logWarn( 'Error getting file sizes,... | Split files in groups according to the size and create tasks for a given SE | 625941c48a349b6b435e814f |
@manager.command <NEW_LINE> def drop_db(): <NEW_LINE> <INDENT> db.drop_all() | Drops the db tables | 625941c499fddb7c1c9de36e |
def get_oss_file_list(oss_handler, prefix, date_range_min, date_range_max=None): <NEW_LINE> <INDENT> date_range_max = date_range_max or date_range_min <NEW_LINE> date_format = "/".join( ["%Y", "%m", "%d", "%H", "%M", "%S"][: date_range_min.count("/") + 1] ) <NEW_LINE> time_interval = [ {"days": 365}, {"days": 31}, {"da... | 获取文件列表
@param prefix: 路径前缀 如 data/car_service_line/yiche/yiche_serial_zongshu_info
@param date_range_min: 时间范围 最小值 日期分隔符为/ 如 2019/03/01 或 2019/03/01/00/00/00
@param date_range_max: 时间范围 最大值 日期分隔符为/ 如 2019/03/01 或 2019/03/01/00/00/00
@return: 每个文件路径 如 html/e_commerce_service_line/alibaba/alibaba_shop_info/2019/03/22/15/... | 625941c4fbf16365ca6f619d |
def refresh(self, *args): <NEW_LINE> <INDENT> self.irrevEntry.refreshDisplay() | Refresh data in all active display widgets. | 625941c407f4c71912b1145d |
def search(self, word: str) -> bool: <NEW_LINE> <INDENT> return self.recursiveSearch(word, self.root) | Returns if the word is in the trie. | 625941c44a966d76dd550feb |
def convert_ipv4_netmask_prefix(network): <NEW_LINE> <INDENT> temp_address = "0.0.0.0" <NEW_LINE> net = IPv4Network(u"{0}/{1}".format(temp_address, network), False) <NEW_LINE> if isinstance(network, int) and (0 < network < 33): <NEW_LINE> <INDENT> return str(net.netmask) <NEW_LINE> <DEDENT> elif isinstance(network, bas... | Convert network mask to equivalent network prefix length or vice versa.
Example: mask 255.255.0.0 -> prefix length 16
:param network: Network mask or network prefix length.
:type network: str or int
:returns: Network mask or network prefix length.
:rtype: str or int | 625941c4cdde0d52a9e5300e |
def test_custom_tokenizer(self): <NEW_LINE> <INDENT> wc = self.corpus_class(self.enwiki, processes=1, tokenizer_func=custom_tokenizer, token_max_len=16, token_min_len=1, lower=False) <NEW_LINE> row = wc.get_texts() <NEW_LINE> list_tokens = next(row) <NEW_LINE> self.assertTrue(u'Anarchism' in list_tokens) <NEW_LINE> sel... | define a custom tokenizer function and use it | 625941c4091ae35668666f3e |
def has_generic_permission(self, request, perm_type, user=None): <NEW_LINE> <INDENT> if not user: <NEW_LINE> <INDENT> user = request.user <NEW_LINE> <DEDENT> att_name = "permission_%s_cache" % perm_type <NEW_LINE> if (not hasattr(self, "permission_user_cache") or not hasattr(self, att_name) or user.pk != self.permissio... | Return true if the current user has permission on the page.
Return the string 'All' if the user has all rights. | 625941c455399d3f05588690 |
def __setitem__(self, key, value): <NEW_LINE> <INDENT> keyValidity = self.validateKey(key) <NEW_LINE> if not keyValidity[0]: <NEW_LINE> <INDENT> raise IndexError(keyValidity[1], key) <NEW_LINE> <DEDENT> if value is not None and not isinstance(value, Piece): <NEW_LINE> <INDENT> raise TypeError("Given value must be eithe... | Called to implement assignment to self[key]
When key is a position tuple, (0-7, 0-7) the given
value is written to that position.
If the key is not a tuple, or the values are outside
of the valid range, IndexError is raised. This is
done by the 'validateKey' method.
If the given value is neither None or an instance
... | 625941c48a349b6b435e8150 |
def set_column_style(column, **style_args): <NEW_LINE> <INDENT> global _TABLE <NEW_LINE> _TABLE.set_column_style(column, **style_args) <NEW_LINE> return get_interactive_return_value() | Apply style(s) to a table column. | 625941c41b99ca400220aa8e |
def get_job(self, job_id: str) -> Job: <NEW_LINE> <INDENT> job = None <NEW_LINE> url = self.get_endpoint('invoke', 'jobs') <NEW_LINE> authorization_token = self.get_authorization_token() <NEW_LINE> data = self._adapter.get_job(job_id, url, authorization_token) <NEW_LINE> if data: <NEW_LINE> <INDENT> job = Job.create_fr... | Get a job from the invoke service ( koi )
:param str job_id: Id of the job to get
:return: a job class
:type: :class:`starfish.job.Job` class | 625941c4379a373c97cfab21 |
def run_wgquick(self, task, interface): <NEW_LINE> <INDENT> command = f'wg-quick {task} "{interface}"' <NEW_LINE> try: <NEW_LINE> <INDENT> out, err, ret = self.execute(command, suppressoutput=True, suppresserrors=True) <NEW_LINE> if ret > 0: <NEW_LINE> <INDENT> logger.error(err) <NEW_LINE> raise Exception('wg-quick ret... | Runs "wg-quick <task> <interface> | 625941c40a50d4780f666e6d |
def eval_step(total_loss): <NEW_LINE> <INDENT> inputs = dequeue_fn() <NEW_LINE> features, labels = inputs.features_and_labels() <NEW_LINE> tpu_estimator_spec = self._call_model_fn(features, labels) <NEW_LINE> if not isinstance(tpu_estimator_spec, model_fn_lib._TPUEstimatorSpec): <NEW_LINE> <INDENT> raise RuntimeError( ... | Evaluation step function for use inside a while loop. | 625941c47b180e01f3dc47dd |
def promote(self, nick, chan=None): <NEW_LINE> <INDENT> admin = db.from_('_admins').where('server', self.server) .and_('channel', chan) .and_('nickname', nick).single() <NEW_LINE> if admin: <NEW_LINE> <INDENT> if chan: <NEW_LINE> <INDENT> raise Environ... | Promote given user to administrator, optionally only in `chan`. | 625941c4d6c5a10208144026 |
def _set_router_id(self, v, load=False): <NEW_LINE> <INDENT> if hasattr(v, "_utype"): <NEW_LINE> <INDENT> v = v._utype(v) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> t = YANGDynClass( v, base=RestrictedClassType( base_type=six.text_type, restriction_dict={ "pattern": "(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]... | Setter method for router_id, mapped from YANG variable /network_instances/network_instance/protocols/protocol/ospfv2/areas/area/interfaces/interface/neighbors/neighbor/state/router_id (yang:dotted-quad)
If this variable is read-only (config: false) in the
source YANG file, then _set_router_id is considered as a private... | 625941c415baa723493c3f51 |
def handle_order_placement(self, order_number, user, basket, shipping_address, shipping_method, shipping_charge, billing_address, order_total, surcharges=None, **kwargs): <NEW_LINE> <INDENT> order = self.place_order( order_number=order_number, user=user, basket=basket, shipping_address=shipping_address, shipping_method... | Write out the order models and return the appropriate HTTP response
We deliberately pass the basket in here as the one tied to the request
isn't necessarily the correct one to use in placing the order. This
can happen when a basket gets frozen. | 625941c4d486a94d0b98e122 |
def _by_taylor_expansion_m1(self, f_divs, k, is_integral=False) : <NEW_LINE> <INDENT> r <NEW_LINE> if is_integral : <NEW_LINE> <INDENT> PS = self.integral_power_series_ring() <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> PS = self.power_series_ring() <NEW_LINE> <DEDENT> qexp_prec = self._qexp_precision() <NEW_LINE> fd... | This provides special, faster code in the Jacobi index `1` case. | 625941c4bf627c535bc131ab |
@pytest.mark.parametrize('values', [ [None, None, None], ['Message', None, None], [None, [{ 'type': 'dismiss' }], None], [None, None, 'test-template.html'], ]) <NEW_LINE> def test_valid_message_actions_body_template(note, values): <NEW_LINE> <INDENT> note.message = values[0] <NEW_LINE> note.actions = values[1] <NEW_LIN... | Test valid values for message/actions/body_template. | 625941c450485f2cf553cd76 |
def test_delete_dhcp_ip_pool(self): <NEW_LINE> <INDENT> pass | Test case for delete_dhcp_ip_pool
Delete a DHCP server's IP pool # noqa: E501 | 625941c4ec188e330fd5a77f |
def inputNumber(message): <NEW_LINE> <INDENT> tuttoOk = False <NEW_LINE> while not tuttoOk: <NEW_LINE> <INDENT> v=input(message) <NEW_LINE> tuttoOk = True <NEW_LINE> if not v.isnumeric(): <NEW_LINE> <INDENT> tuttoOk = False <NEW_LINE> print("A quanto pare, non hai inserito un numero…") <NEW_LINE> <DEDENT> <DEDENT> retu... | Permette l'inserimento di un numero in maniera controllata.
Chiede in input una stringa usando *message* come prompt, verifica
che la stringa contenga un valore numerico e restituisce il valore
corrispondente. Se viene inserito un valore che non è un numero,
viene richiesto di nuovo l'inserimento. | 625941c44527f215b584c436 |
def addmob(self, n): <NEW_LINE> <INDENT> for x in range(int(n)): <NEW_LINE> <INDENT> self.append("commoner") <NEW_LINE> <DEDENT> return self | Adds _n_ commoners to the battle
:param n: number of commoners
:return: self | 625941c46aa9bd52df036d80 |
def update_site_forward(apps, schema_editor): <NEW_LINE> <INDENT> Site = apps.get_model('sites', 'Site') <NEW_LINE> Site.objects.update_or_create( id=settings.SITE_ID, defaults={ 'domain': 'example.com', 'name': 'habb' } ) | Set site domain and name. | 625941c40a50d4780f666e6e |
def variable_statistics(var_data, stdev=None): <NEW_LINE> <INDENT> if stdev is None: <NEW_LINE> <INDENT> varD = var_data <NEW_LINE> num_outliers = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ind = reject_extreme_values(var_data) <NEW_LINE> var = var_data[ind] <NEW_LINE> if len(var) > 0: <NEW_LINE> <INDENT> ind2 ... | Calculate statistics for a variable of interest
:param variable: array containing data
:param stdev: desired standard deviation to exclude from analysis | 625941c4236d856c2ad447b5 |
def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'capacity': 'Any', 'gce_persistent_disk': 'V1GCEPersistentDiskVolumeSource', 'aws_elastic_block_store': 'V1AWSElasticBlockStoreVolumeSource', 'host_path': 'V1HostPathVolumeSource', 'glusterfs': 'V1GlusterfsVolumeSource', 'nfs': 'V1NFSVolumeSource', 'rbd': '... | V1PersistentVolumeSpec - 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. | 625941c4adb09d7d5db6c76d |
def expand(row, col): <NEW_LINE> <INDENT> if row < 0 or row >= gheight: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if col < 0 or col >= gwidth: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if ggrid[row][col] != 1: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> perimeter = cell_perimeter(row, col) <NEW_LINE>... | Expands the island searching for 1's | 625941c46e29344779a625f0 |
def mandel_1(real_coord, imag_coord, max_iters): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> z_real = 0. <NEW_LINE> z_imag = 0. <NEW_LINE> while i < max_iters: <NEW_LINE> <INDENT> z_real_n = z_real * z_real - z_imag * z_imag + real_coord <NEW_LINE> z_imag = 2. * z_real * z_imag + imag_coord <NEW_LINE> z_real = z_real_n <NEW_L... | Given a the real and imaginary parts of a complex number,
determine if it is a candidate for membership in the Mandelbrot
set given a fixed number of iterations.
Inspired by code at http://wiki.cython.org/examples/mandelbrot | 625941c4009cb60464c63390 |
def transition_probability(state, action, next_state): <NEW_LINE> <INDENT> return transitions_A[state[0] - action, next_state[0]][1] * transitions_B[state[1] + action, next_state[1]][1] | TODO
| 625941c43d592f4c4ed1d04f |
def hex2oct(number): <NEW_LINE> <INDENT> number = str(number) <NEW_LINE> prefix_num = "0x{0}".format(number) <NEW_LINE> conversion = oct(int(prefix_num, 16)) <NEW_LINE> conversion = conversion.replace("0o", "") <NEW_LINE> return conversion | Converts a hexadecimal number to a binary number | 625941c43317a56b86939c39 |
def within_proximity(l1, l2, distance): <NEW_LINE> <INDENT> shifted_l1 = [(i + distance) for i in l1] <NEW_LINE> match = union(shifted_l1, l2) <NEW_LINE> return match | checks if there are any elements in l1 and l2, i and j,
where difference between |i - j| = distance. | 625941c4c432627299f04c22 |
def opensearch(request): <NEW_LINE> <INDENT> site = Site.objects.get_current() <NEW_LINE> return render(request, 'trombi/opensearch.xml', locals(), mimetype='text/xml') | OpenSearch XML file | 625941c4090684286d50ecc1 |
def enable_monitoring(self): <NEW_LINE> <INDENT> print(self.mon_adapter) <NEW_LINE> process = subprocess.Popen(['sudo', 'airmon-ng', 'start', self.mon_adapter], stdin=PIPE, stdout=PIPE, stderr=PIPE) | enable monitoring mode of the network card that is defined by 'adapter' | 625941c494891a1f4081ba85 |
def check_thermodynamic_feasibility(data_dict: dict) -> tuple: <NEW_LINE> <INDENT> print('\nChecking if fluxes and Gibbs energies are compatible.\n') <NEW_LINE> flag = False <NEW_LINE> temperature = 298 <NEW_LINE> gas_constant = 8.314 * 10**-3 <NEW_LINE> stoic_df = data_dict['stoic'] <NEW_LINE> flux_df = data_dict['mea... | Given a dictionary representing a GRASP input file, it checks if the reaction's dG are compatible with the
respective fluxes. It works both when all fluxes are specified in measRates and when robust fluxes are calculated
for a fully determined system. If the fluxes are not fully specified not the system is fully determ... | 625941c4dc8b845886cb5511 |
def generate_summary(self, content, keywords): <NEW_LINE> <INDENT> summary = [] <NEW_LINE> content_length = str(content).count(' ') <NEW_LINE> estimated_sent_min = max(1, int((content_length * 0.17) / 10)) <NEW_LINE> estimated_sent_max = int((content_length * 0.23) / 10) <NEW_LINE> keywords = keywords.split(',') <NEW_L... | content: original news article, full lengthed
keywords: Key-phrases returned from Azure Text Analytics API
in the order of decreasing importance | 625941c41f5feb6acb0c4b30 |
def go_to_baobiaochaxun(driver): <NEW_LINE> <INDENT> actions = ActionChains(driver) <NEW_LINE> try: <NEW_LINE> <INDENT> WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//a[text()='报表查询']"))) <NEW_LINE> el = driver.find_element_by_xpath("//a[text()='报表查询']") <NEW_LINE> actions.move_to_elemen... | 报表查询 | 625941c4b57a9660fec33860 |
def chunks(arr, size): <NEW_LINE> <INDENT> for i in range(0, len(arr), size): <NEW_LINE> <INDENT> yield arr[i:i + size] | >>> for chunk in chunks([1,2,3,4,5], 2): print(chunk)
[1, 2]
[3, 4]
[5] | 625941c4d268445f265b4e4c |
def add_to_group(strategy, details, backend, user=None, *args, **kwargs): <NEW_LINE> <INDENT> if backend.name == 'facebook' or backend.name == 'google-oauth2': <NEW_LINE> <INDENT> groups_list = user.groups.values_list('name',flat=True) <NEW_LINE> if len(groups_list) == 0: <NEW_LINE> <INDENT> g = Group.objects.get(name=... | Checks if user belongs to any groups. If not, adds user to 'Consumers'
group. | 625941c45fdd1c0f98dc0210 |
def _populate_history(self, user): <NEW_LINE> <INDENT> entries = LogEntry.objects.by_user(user)[:12] <NEW_LINE> r = TxRedisMapper() <NEW_LINE> key = redis_key_for_user(user) <NEW_LINE> for entry in entries: <NEW_LINE> <INDENT> data = { 'action_time': entry.action_time, 'message': entry.message, 'action_type': entry.act... | Store the latest action log items for the specified team. | 625941c407d97122c4178865 |
def createSocket(self): <NEW_LINE> <INDENT> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <NEW_LINE> s.setsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST, 1 ) <NEW_LINE> return s | Creates and returns a new socket object to be used by the handler. | 625941c4de87d2750b85fd6e |
def print_options(): <NEW_LINE> <INDENT> print("1. Get the number of vertices") <NEW_LINE> print("2. Iterate the set of vertices") <NEW_LINE> print("3. Find if there is an edge between 2 vertices") <NEW_LINE> print("4. Check if a given number if a vertex in graph") <NEW_LINE> print("5. Add a new edge") <NEW_LINE> print... | function which prints the menu
:return: - | 625941c42ae34c7f2600d10f |
def reset_stats(self): <NEW_LINE> <INDENT> self.ships_left = self.ai_settings.ship_limit <NEW_LINE> self.score = 0 <NEW_LINE> self.level = 1 | Intialsie statsistics that can change during the game | 625941c4c4546d3d9de72a10 |
def __getattr__(self, name): <NEW_LINE> <INDENT> if str(name) in self.__dict__: <NEW_LINE> <INDENT> return self.__dict__[str(name)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> db = current.db <NEW_LINE> if name in db: <NEW_LINE> <INDENT> return db[name] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s3 = current.respo... | Model auto-loader | 625941c4cc0a2c11143dce6d |
def begin_text_resource(self, resource, text): <NEW_LINE> <INDENT> return text | Called when a text resource is about to be processed for generation.
The `text` parameter contains the resource text at this point
in its lifecycle. It is the text that has been loaded and any
plugins that are higher in the order may have tampered with it.
But the text has not been processed by the template yet. Note t... | 625941c47d43ff24873a2c7d |
def _set_decided_lfs(row, column): <NEW_LINE> <INDENT> row.decided(column.index).p4_request = common.P4_REQUEST_LFS_COPY | Mark this cell as "needs to be copied from LFS de-dupe" | 625941c4f9cc0f698b1405da |
def saveNewsPost(self, post): <NEW_LINE> <INDENT> pass | Saves a HLNewsPost object to the database. | 625941c497e22403b379cf77 |
def send_payload(payload, access_token): <NEW_LINE> <INDENT> payload = events.on_payload(payload) <NEW_LINE> if payload is False: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> payload_str = _serialize_payload(payload) <NEW_LINE> handler = SETTINGS.get('handler') <NEW_LINE> if handler == 'blocking': <NEW_LINE> <INDENT>... | Sends a payload object, (the result of calling _build_payload() + _serialize_payload()).
Uses the configured handler from SETTINGS['handler']
Available handlers:
- 'blocking': calls _send_payload() (which makes an HTTP request) immediately, blocks on it
- 'thread': starts a single-use thread that will call _send_paylo... | 625941c4a05bb46b383ec800 |
def _store(self, cachepath, template): <NEW_LINE> <INDENT> raise NotImplementedError.new("%s#_store(): not implemented yet." % self.__class__.__name__) | (abstract) load dict object which represents template object attributes from cache file. | 625941c4bf627c535bc131ac |
def analyze_user_files(jar_path, files): <NEW_LINE> <INDENT> with open(tmpfile, 'w') as f: <NEW_LINE> <INDENT> for row in files: <NEW_LINE> <INDENT> f.write(' '.join(row['content'])+'\n') <NEW_LINE> <DEDENT> <DEDENT> cmd = ['java', '-jar', jar_path, '-comp', tmpfile] <NEW_LINE> pipe = Popen(cmd, cwd='../data', stdout=P... | あるユーザに関して,
問題ごとの提出リストが与えられる
各問題の提出リストについて,隣接提出の差分を計算し,
差分行列 result[][] を返す | 625941c444b2445a33932074 |
def delete(self, using=None, keep_parents=False): <NEW_LINE> <INDENT> super().delete(using=using, keep_parents=keep_parents) <NEW_LINE> if os.path.exists(self.field.file.name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.remove(self.field.file.name) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> p... | удаление объекта
:param using:
:param keep_parents:
:return: | 625941c4d7e4931a7ee9defa |
def get_func_result_from_cache(args_key): <NEW_LINE> <INDENT> function_data = function_args_dict[args_key] <NEW_LINE> call_counter = function_data['call_counter'] <NEW_LINE> call_counter += 1 <NEW_LINE> function_data['call_counter'] = call_counter <NEW_LINE> function_args_dict[args_key] = function_data <NEW_LINE> retur... | Function used for getting function result for given args_key.
:param args_key: string
:return: func_result, object | 625941c438b623060ff0adcb |
def test_timezone(self): <NEW_LINE> <INDENT> import datetime <NEW_LINE> d = datetime.datetime(2009, 9, 24, 15, 52, 12) <NEW_LINE> td = datetime.timedelta(hours=-5) <NEW_LINE> msg = remoting.Envelope(pyamf.AMF0) <NEW_LINE> msg['/1'] = remoting.Response(body=[d]) <NEW_LINE> stream = remoting.encode(msg, timezone_offset=t... | Ensure that the timezone offsets work as expected | 625941c4956e5f7376d70e4b |
def test_incorrect_collinear_vertex_nonpositive(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError) as raised_exception: <NEW_LINE> <INDENT> calculate_area_triangle([[0, 0], [0, 0], [0, 0]]) <NEW_LINE> <DEDENT> self.assertEqual(raised_exception.exception.args[0], "Vertex can't to be vertex triangle. Vertex is... | Negative test.
Checks exception if user entered vertex is a collinear | 625941c47b25080760e39437 |
def start_netreg(self): <NEW_LINE> <INDENT> self.do_next() <NEW_LINE> return self.deferred | Starts the network registration process
@rtype: C{defer.Deferred}
@raise ex.NetworkTemporalyUnavailableError: If AT+COPS keeps replying
+COPS: 0 (No network)
@raise ex.NetworkRegistrationError: Raised when we can't register with
the network we want to register to | 625941c4baa26c4b54cb10fe |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'winter_night.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... | Run administrative tasks. | 625941c4d53ae8145f87a250 |
def scrape_options(html): <NEW_LINE> <INDENT> option_types = ['calls', 'puts'] <NEW_LINE> html = BeautifulSoup(html, 'html.parser') <NEW_LINE> tables = html.find_all('table') <NEW_LINE> options_data = {} <NEW_LINE> for i, table in enumerate(tables): <NEW_LINE> <INDENT> headers = [] <NEW_LINE> options = {} <NEW_LINE> fo... | Given some html look for and scape options data from tables | 625941c4ff9c53063f47c1d2 |
def load_blueprints(): <NEW_LINE> <INDENT> from server.sms.views import sms_bp <NEW_LINE> from server.server import server_bp <NEW_LINE> app.register_blueprint(server_bp, url_prefix="/") <NEW_LINE> app.register_blueprint(sms_bp, url_prefix="/sms") | Load all blueprints for app | 625941c491af0d3eaac9b9f5 |
def __init__( self, *, connection_id: str = None, enc_payload: Union[str, bytes] = None, endpoint: str = None, payload: Union[str, bytes], reply_session_id: str = None, reply_thread_id: str = None, reply_to_verkey: str = None, reply_from_verkey: str = None, target: ConnectionTarget = None, target_list: Sequence[Connect... | Initialize an outgoing message. | 625941c45166f23b2e1a5137 |
def MonteCarlo(epochs, K, S0, r, sigma, T, plot=False): <NEW_LINE> <INDENT> path_value = [] <NEW_LINE> for epoch in range(epochs): <NEW_LINE> <INDENT> path = StockPriceSim(S0, sigma, r, T) <NEW_LINE> path_value.append(PathValue(path, K, r)) <NEW_LINE> if plot: <NEW_LINE> <INDENT> plt.plot(path) <NEW_LINE> <DEDENT> <DED... | K: strike price
S0: initial value
r: interest rate measured yearly
sigma: yearly volatility
T: yrs | 625941c4442bda511e8be3f8 |
def annulus_bound(self): <NEW_LINE> <INDENT> self.cmin = max(0.0, self.range - self.vcw * self.sstd) <NEW_LINE> self.cmax = self.range + self.vcw * self.sstd | annulus_bound():
Compute the minimum and maximum distance of the enclosing annulus of the constraint
Returns
-------
Nothing but update cmin, cmax and mean | 625941c4de87d2750b85fd6f |
def predict_proba(self, x, **kwargs): <NEW_LINE> <INDENT> kwargs = self.filter_sk_params(Model.predict, kwargs) <NEW_LINE> probas = self.model.predict(x, **kwargs) <NEW_LINE> return probas | Predict classes from features.
Args:
x: np.array or scipy.sparse.*matrix array of features
**kwargs: additional keyword arguments
Returns:
y_pred: np.array
2-D array of class predicted probabilities | 625941c4bd1bec0571d9060d |
def send_result(task: ExternalTask) -> TaskResult: <NEW_LINE> <INDENT> logger = get_logger() <NEW_LINE> logger.info("send_result") <NEW_LINE> operation_result = task.get_variable("operation_result") <NEW_LINE> interest = json.loads(task.get_variable("interest")) <NEW_LINE> pg_username = interest.get("prontogram_usernam... | Sends the result message to the client through RabbitMQ.
:param task: the current task instance
:return: the task result | 625941c44f6381625f114a1a |
def scott(x): <NEW_LINE> <INDENT> h = (24 * np.pi**0.5 / x.size)**(1.0 / 3) * np.std(x) <NEW_LINE> if h > 0: <NEW_LINE> <INDENT> return np.ceil(x.ptp() / h) <NEW_LINE> <DEDENT> return 1 | Scott Estimator
The binwidth is proportional to the standard deviation of the
data and inversely proportional to the cube root of data size
(asymptotically optimal). | 625941c49f2886367277a86c |
@periodic_task(run_every=datetime.timedelta(hours=24)) <NEW_LINE> def clean_expired_tokens(): <NEW_LINE> <INDENT> now = datetime.datetime.now().strftime('%H') <NEW_LINE> mode_1 = Tokens.objects.filter(mode=1, is_used=True) <NEW_LINE> mode_2 = Tokens.objects.filter(mode=2, is_used=True) <NEW_LINE> mode_3 = Tokens.object... | Clean expired tokens each 24h. | 625941c463f4b57ef00010fb |
def migrate_settings(): <NEW_LINE> <INDENT> if settings.get_option( migrated_option, False ): <NEW_LINE> <INDENT> default_groups = settings.get_option( 'plugin/grouptagger/default_groups', None ) <NEW_LINE> if default_groups is not None: <NEW_LINE> <INDENT> group_categories = { _('Uncategorized'): [True, default_groups... | Automatically migrate group tagger 0.1 settings to 0.2 | 625941c4a934411ee3751671 |
def get_time(): <NEW_LINE> <INDENT> return time.strftime('%Y-%m-%d %H:%M:%S ', time.localtime(time.time())) | 生成时间戳
:return: 时间戳 | 625941c429b78933be1e568c |
def generate_samples_for_checking_mes_of_perf(samples_num): <NEW_LINE> <INDENT> key_f = "samples/key.txt" <NEW_LINE> key = b'\xff\xee\xdd\xcc\xbb\xaa\x99\x88\x77\x66\x55\x44\x33\x22\x11\x00\xf0\xe0\xd0\xc0\xb0\xa0\x90\x80\x70\x60\x50\x40\x30\x20\x10\x00' <NEW_LINE> with open(key_f, "wb") as file: <NEW_LINE> <INDENT> fi... | Генерирует файл (samples/pts.txt) с открытыми текстами, длины которых равны 16 байтам (128 битам)
и файл с ключем (samples/key.txt) длинны 32 байта (256 бита).
В файле 128*sample_num*2 открытых текстов, т.к. для проверки каждой из 128 координат требуется samples_num пар векторов соседних (внутри своей пары) по данной к... | 625941c430bbd722463cbda3 |
def index(request): <NEW_LINE> <INDENT> return render(request, 'index.html') | the public main page | 625941c46fb2d068a760f079 |
def get_projects(self): <NEW_LINE> <INDENT> response = self.request("GET", self.url) <NEW_LINE> projects_dict = response.json() <NEW_LINE> return [Project.from_dict(proj) for proj in projects_dict] | List all user projects. | 625941c463f4b57ef00010fc |
def _delete_value(self, hass, data, config_key): <NEW_LINE> <INDENT> return data.pop(config_key) | Delete value. | 625941c4e64d504609d7481e |
def filter_(data, axis='time', low_cut=None, high_cut=None, order=4, ftype='butter', Rs=None): <NEW_LINE> <INDENT> nyquist = data.s_freq / 2. <NEW_LINE> btype = None <NEW_LINE> if low_cut is not None and high_cut is not None: <NEW_LINE> <INDENT> if low_cut > nyquist or high_cut > nyquist: <NEW_LINE> <INDENT> raise Valu... | Design filter and apply it.
Parameters
----------
ftype : str
'butter', 'cheby1', 'cheby2', 'ellip', 'bessel' or 'diff'
low_cut : float, optional
low cutoff for high-pass filter
high_cut : float, optional
high cutoff for low-pass filter
order : int, optional
filter order
data : instance of Data
the... | 625941c41b99ca400220aa8f |
def facets(mesh): <NEW_LINE> <INDENT> def facets_nx(): <NEW_LINE> <INDENT> graph_parallel = nx.from_edgelist(face_idx[parallel]) <NEW_LINE> facets_idx = [list(i) for i in nx.connected_components(graph_parallel)] <NEW_LINE> return facets_idx <NEW_LINE> <DEDENT> def facets_gt(): <NEW_LINE> <INDENT> graph_parallel = G... | Find the list of parallel adjacent faces.
Arguments
---------
mesh: Trimesh
Returns
---------
facets: list of groups of face indexes (in mesh.faces) of parallel
adjacent faces. | 625941c4fff4ab517eb2f419 |
def pdf(self, param_vals): <NEW_LINE> <INDENT> return self.quasi(param_vals)/self.mlike | Return the posterior density for the provided param values
(scalar or vector). | 625941c44527f215b584c437 |
def get_article_title(el: element.Tag) -> str: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> title = el.find("h3").text <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> title = "" <NEW_LINE> <DEDENT> return title | Get the article title in the element "el" | 625941c4379a373c97cfab22 |
def __init__(self, sourcefile, filename, lookup, offset, word_size): <NEW_LINE> <INDENT> self.source = sourcefile <NEW_LINE> self.reopen_path = filename <NEW_LINE> self.offset = offset <NEW_LINE> self.word_size = word_size <NEW_LINE> self.lookup_entry = lookup | Create a provider that can load a lookup's data.
Args:
* sourcefile: (file)
An open file. This is essentially a shortcut, to avoid having to
always open a file. If it is *not* open when get_data is called,
a temporary file will be opened for 'filename'.
* filename: (string)
Path to the containing file... | 625941c46fece00bbac2d71b |
def reverse_list(l): <NEW_LINE> <INDENT> return list(reversed(l)) | Reverses order of elements in list l. | 625941c4851cf427c661a4ef |
def __setup_toolbar(self): <NEW_LINE> <INDENT> self.button_exit.clicked.connect(self.close) <NEW_LINE> self.button_draw_charts.clicked.connect(self.draw_charts) <NEW_LINE> self.button_save_tables.clicked.connect(self.create_tables) <NEW_LINE> self.button_merge.clicked.connect(self.merge_result_files) <NEW_LINE> self.bo... | toolbar setup | 625941c4442bda511e8be3f9 |
def fuse(self, threshold=0.5, exponent=1, num_parses=50, use_parser_scores=False): <NEW_LINE> <INDENT> parses = self.parses[:num_parses] <NEW_LINE> if use_parser_scores or not self._reranked: <NEW_LINE> <INDENT> scores = [scored_parse.parser_score for scored_parse in parses] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT... | Combine the parses in this n-best list into a single Tree
using parse fusion. This results in a significant accuracy
improvement. You may want to tune the parameters for your specific
parsing model. See Choe, McClosky, and Charniak (EMNLP 2015) for
more details. This will use the scores from the reranker unless
the n-b... | 625941c426068e7796caecbb |
def propertyTypes(self): <NEW_LINE> <INDENT> return self.criteriaType.propertyTypes() | Provides the criteria entry properties types.
@return: list[TypeProperty]
The criteria entry types. | 625941c4009cb60464c63391 |
def convertstore(self, inputstore, duplicatestyle="msgctxt"): <NEW_LINE> <INDENT> outputstore = po.pofile() <NEW_LINE> outputheader = outputstore.init_headers(charset="UTF-8", encoding="8bit") <NEW_LINE> outputheader.addnote("extracted from %s" % inputstore.filename, "developer") <NEW_LINE> for inputunit in inputstore.... | converts a .php file to a .po file... | 625941c45510c4643540f3c7 |
def single(alphabet, node, regexp, regexp_type, wrapper=None): <NEW_LINE> <INDENT> from lepl.matchers.transform import TransformationWrapper <NEW_LINE> matcher = regexp_type(regexp, alphabet) <NEW_LINE> matcher = matcher.compose(TransformationWrapper(empty_adapter)) <NEW_LINE> if wrapper is None and hasattr(node, 'wrap... | Create a matcher for the given regular expression. | 625941c4379a373c97cfab23 |
def process_crisis(crisis): <NEW_LINE> <INDENT> assert type(crisis) == dict <NEW_LINE> references = {} <NEW_LINE> result = {} <NEW_LINE> c = {} <NEW_LINE> assert crisis['id'] <NEW_LINE> c['us_id'] = crisis['id'] <NEW_LINE> for attribute_dictionary in crisis['crisis']: <NEW_LINE> <INDENT> assert type(at... | Parses crisis xml data into a dictionary to eventually end up in a model. | 625941c4be8e80087fb20c24 |
def which(name, flags=os.X_OK): <NEW_LINE> <INDENT> result = [] <NEW_LINE> exts = filter(None, os.environ.get('PATHEXT', '').split(os.pathsep)) <NEW_LINE> path = os.environ.get('PATH', None) <NEW_LINE> if path is None: <NEW_LINE> <INDENT> raise EnvironmentError("Cannot find $PATH variable.") <NEW_LINE> <DEDENT> for p i... | Copyright (c) 2001-2008
Allen Short
Andrew Bennetts
Apple Computer, Inc.
Benjamin Bruheim
Bob Ippolito
Canonical Limited
Christopher Armstrong
David Reid
Donovan Preston
Eric Mangold
Itamar Shtull-Trauring
James Knight
Jason A. Mobarak
Jean-Paul Calderone
Jonathan Lange
Jonathan D. Simms
Jargen Hermann
Kevin Turner
Mar... | 625941c40a50d4780f666e6f |
def __add__(self, scalar: "ssize_t") -> "types::RowCol< sys::SSize_T >": <NEW_LINE> <INDENT> return _coda_types.RowColInt___add__(self, scalar) | __add__(RowColInt self, ssize_t scalar) -> RowColInt | 625941c4bf627c535bc131ad |
def get_issues_by_server(self, server_id): <NEW_LINE> <INDENT> pagination_key = 'issues' <NEW_LINE> url = '/v2/issues' <NEW_LINE> params = { 'agent_id': server_id, 'status': 'active' } <NEW_LINE> hh = cloudpassage.HttpHelper(self.session) <NEW_LINE> issues = hh.get_paginated(url, pagination_key, 5, params=params) <NEW_... | Return all issues for server identified by arg:server_id. | 625941c4627d3e7fe0d68e2d |
def __init__(self, status=None, message=None): <NEW_LINE> <INDENT> responses = BaseHTTPRequestHandler.responses <NEW_LINE> responses[418] = ("I'm a teapot", TOTALLY_NORMAL_CODE) <NEW_LINE> responses[422] = ( "Unprocessable Entity", "The request was well-formed but was" " unable to be followed due to semantic errors", )... | Initialize class. | 625941c421bff66bcd684933 |
def add_index(self, table, field, index_type, index_name=''): <NEW_LINE> <INDENT> if index_type in ("index", "unique"): <NEW_LINE> <INDENT> sql = "create {} {} on {}({})".format(index_type, index_name, table, field) <NEW_LINE> <DEDENT> elif index_type == 'primary key': <NEW_LINE> <INDENT> sql = "alter table {} add prim... | 为表添加index, unique, 或者 primary key(默认不添加auto_increment)
index_type: 索引类型
index_name: 索引名 | 625941c423e79379d52ee544 |
def highlight(self, view, rg): <NEW_LINE> <INDENT> scope = settings.get('highlight', 'invalid') <NEW_LINE> gutter_icon = settings.get('gutter_icon', 'circle') <NEW_LINE> view.add_regions(self.region_id, [rg], scope, gutter_icon, sublime.PERSISTENT) | colorize the breakpoint's region | 625941c482261d6c526ab47b |
def __parity_close_vault(self, vault): <NEW_LINE> <INDENT> return [vault] | https://github.com/paritytech/parity/wiki/JSONRPC-parity-module#parity_closevault
Response body returns if the vault closure was successful.
Parity only.
:param vault: vault name. | 625941c40383005118ecf5c3 |
@click.command() <NEW_LINE> @click.option('--deployment-name', nargs=1, default="mainnet", help='Project section id inside the YAML file. The topmost YAML key. Example YAML files use "mainnet" or "kovan".', required=True) <NEW_LINE> @click.option('--deployment-file', nargs=1, help='Deployment script YAML .yml file to p... | Makes a scripted multiple contracts deployed based on a YAML file.
Reads the chain configuration information from populus.json.
The resulting deployed contracts can be automatically verified on etherscan.io.
Example files:
* https://github.com/TokenMarketNet/ico/blob/master/crowdsales/crowdsale-token-example.yml
* ... | 625941c496565a6dacc8f6aa |
def plot_energies(self, np = None, ax=None): <NEW_LINE> <INDENT> if not ax: <NEW_LINE> <INDENT> import matplotlib.pyplot as plt <NEW_LINE> fig = plt.figure() <NEW_LINE> ax = fig.add_subplot(111) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fig = None <NEW_LINE> <DEDENT> if np: <NEW_LINE> <INDENT> datas = self.results[... | Plots the NEB band on matplotlib axes object 'ax'. If ax=None
returns a new figure object. | 625941c40a50d4780f666e70 |
def lateral(self, parent, parent_index, dest, dest_index): <NEW_LINE> <INDENT> if parent_index > dest_index: <NEW_LINE> <INDENT> dest.contents.append(self.contents.pop(0)) <NEW_LINE> dest.data.append(self.data.pop(0)) <NEW_LINE> parent.contents[dest_index] = self.contents[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT... | Utilizado para mover nodos nas operações sobre a arvore | 625941c476e4537e8c351650 |
def gammaN(pixel,N): <NEW_LINE> <INDENT> R = pixel.getRed() <NEW_LINE> G = pixel.getGreen() <NEW_LINE> B = pixel.getBlue() <NEW_LINE> Y = min((0.00117 * R + 0.00230 * G + 0.000447 * B),1) <NEW_LINE> U = max(min((-0.000577 * R - 0.00113 * G + 0.00171 * B),0.5),-0.5) <NEW_LINE> V = max(min((0.00241 * R - 0.00202 * G - 0.... | Takes in a pixel object and does gamma correction on
it with a gamma value of N | 625941c432920d7e50b281ad |
def delete_scheme(url): <NEW_LINE> <INDENT> if url.startswith('https://'): <NEW_LINE> <INDENT> return url.replace('https://', '') <NEW_LINE> <DEDENT> return url.replace('http://', '') | Delete a scheme of url.
Args:
url: str
Returns:
url without scheme: str | 625941c4656771135c3eb84b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.