code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def delete(self, **kwargs): <NEW_LINE> <INDENT> if self.is_comment(): <NEW_LINE> <INDENT> activity_types = const.RESPONSE_ACTIVITY_TYPES_FOR_DISPLAY <NEW_LINE> activity_types += (const.TYPE_ACTIVITY_MENTION,) <NEW_LINE> from askbot.models.user import Activity <NEW_LINE> comment_content_type = ContentType.objects.get_fo... | deletes comment and concomitant response activity
records, as well as mention records, while preserving
integrity or response counts for the users | 625941d50c0af96317bb83f2 |
@app.route('/capability-descriptor', methods=['GET']) <NEW_LINE> def capability_descriptor(): <NEW_LINE> <INDENT> last_slash_index = request.base_url.rfind('/') <NEW_LINE> webhook_url = request.base_url[0:last_slash_index] <NEW_LINE> cd = get_capabilities_descriptor(webhook_url) <NEW_LINE> if cd.status.success: <NEW_LI... | the route/url that receives the http GET request from a hipchat room Admin requesting to integrate DZbot into their
chat room
:return: the capabilities descriptor containing details of how | 625941d55e10d32532c5f130 |
def market_search_by_ticker_get(self, ticker, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.market_search_by_ticker_get_with_http_info(ticker, **kwargs) | Получение инструмента по тикеру # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.market_search_by_ticker_get(ticker, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:... | 625941d5dc8b845886cb5740 |
def _build_JSON_result(self, result_dict): <NEW_LINE> <INDENT> sResult = json.dumps(result_dict) <NEW_LINE> result = HttpResponse(sResult) <NEW_LINE> return result | Builds json result
@param resultDict: dict : Dictionary with json data
@return: result : HttpResponse | 625941d57d43ff24873a2eaa |
def __init__(self): <NEW_LINE> <INDENT> self.ffi = FFI <NEW_LINE> self.ffilib = FFILIB <NEW_LINE> self.pollpairs = self.ffi.new('pollpair[]', 65536) | Initialize. | 625941d58a43f66fc4b5426d |
def selectedPoints(selectionThreshold): <NEW_LINE> <INDENT> pass | selectedPoints(selectionThreshold) -> iterator
Return an iterator which yields the position of every point currently
selected in the Viewer in turn.
The selectionThreshold parameter is used when working with a soft selection.
Only points with a selection level >= the selection threshold will be
returned by this funct... | 625941d573bcbd0ca4b2c280 |
def test_in_group_with_when_target_not_in_group(self): <NEW_LINE> <INDENT> r1 = Room(1, 1, 1) <NEW_LINE> r2 = Room(2, 2, 2) <NEW_LINE> r3 = Room(3, 3, 3) <NEW_LINE> g = Group(r1, r2) <NEW_LINE> self.assertEqual(r1.in_group_with(r3), False) | Tests group membership when the target isn't in a group | 625941d51b99ca400220acbb |
def print_file(self, filename): <NEW_LINE> <INDENT> import os <NEW_LINE> self.clear() <NEW_LINE> stuff = [] <NEW_LINE> with open(os.path.join(config.screens_folder, filename)) as f: <NEW_LINE> <INDENT> y = 0 <NEW_LINE> y_beg = None <NEW_LINE> for line in f.readlines(): <NEW_LINE> <INDENT> if line[0] != "#": <NEW_LINE> ... | Print the contents of a text file. | 625941d58c3a8732951585c5 |
def __init__(self, fmc, **kwargs): <NEW_LINE> <INDENT> super().__init__(fmc, **kwargs) <NEW_LINE> logging.debug("In __init__() for StaticRoutes class.") <NEW_LINE> self.parse_kwargs(**kwargs) | Initialize StaticRoutes object.
:param fmc (object): FMC object
:param **kwargs: Any other values passed during instantiation.
:return: None | 625941d597e22403b379d1a5 |
def draw_label(self): <NEW_LINE> <INDENT> x, y, z = self.position <NEW_LINE> self.label.text = '%02d FPS(%.2f, %.2f, %.2f) %d / %d [MINECRAFT RELOADED DEV-0024]' % ( pyglet.clock.get_fps(), x, y, z, len(self.model._shown), len(self.model.world)) <NEW_LINE> self.label.draw() | Draw the label in the top left of the screen.
| 625941d516aa5153ce362682 |
def esc(x): <NEW_LINE> <INDENT> rep = {'%%':'%%%%','^%^':'%%^', '%$$':'%%$','%(':'%%(','%)':'%%)', '%.':'%%.', '%[':'%%[','%]':'%%]','%*':'%%*','%+':'%%+','%-':'%%-','%?':'%%?'} <NEW_LINE> rep = dict((re.escape(k), v) for k, v in rep.items()) <NEW_LINE> pattern = re.compile("|".join(rep.keys())) <NEW_LINE> return patte... | Handles escape characters in string matching | 625941d5ff9c53063f47c3fd |
def seq_from_stack(self, stack, selected=[]): <NEW_LINE> <INDENT> if not isinstance(selected, list): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if len(selected) == 0: <NEW_LINE> <INDENT> selected = self.base[stack].keys() <NEW_LINE> <DEDENT> tab = {k: self.base[stack][k] for k in selected if k in self.base[st... | returning dict with Sequence objects from pointed stack.
if list with sequence names was submited only pointed will be returned.
stack = str
selected = [] | 625941d53eb6a72ae02ec6eb |
def package_collaborator_create(context, data_dict): <NEW_LINE> <INDENT> user = context['user'] <NEW_LINE> model = context['model'] <NEW_LINE> pkg = model.Package.get(data_dict['id']) <NEW_LINE> user_obj = model.User.get(user) <NEW_LINE> if not authz.can_manage_collaborators(pkg.id, user_obj.id): <NEW_LINE> <INDENT> re... | Checks if a user is allowed to add collaborators to a dataset
See :py:func:`~ckan.authz.can_manage_collaborators` for details | 625941d599cbb53fe6792df1 |
def islandPerimeter(self, grid): <NEW_LINE> <INDENT> if not grid: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> row_num = grid.__len__() <NEW_LINE> col_num = grid[0].__len__() <NEW_LINE> res = 0 <NEW_LINE> for i in range(row_num): <NEW_LINE> <INDENT> for j in range(col_num): <NEW_LINE> <INDENT> if grid[i][j] == 1: <... | :type grid: List[List[int]]
:rtype: int | 625941d5d164cc6175782f58 |
def set_url_query_parameter( url: str, param_name: str, param_value: str ) -> str: <NEW_LINE> <INDENT> if not isinstance(param_name, str): <NEW_LINE> <INDENT> raise Exception( 'URL query parameter name must be a string, received %s' % param_name) <NEW_LINE> <DEDENT> scheme, netloc, path, query_string, fragment = urllib... | Set or replace a query parameter, and return the modified URL.
Args:
url: str. URL string which contains the query parameter.
param_name: str. Parameter name to be removed.
param_value: str. Set the parameter value, if it exists.
Returns:
str. Formated URL that has query parameter set or replaced.
Ra... | 625941d59f2886367277aa97 |
def _pretty_print(self): <NEW_LINE> <INDENT> def print_underlined(text): <NEW_LINE> <INDENT> underline = '-' * len(text) <NEW_LINE> print(f"{text}\n{underline}") <NEW_LINE> <DEDENT> print_underlined("Graph:") <NEW_LINE> for link in self.links(): <NEW_LINE> <INDENT> source = link[0] <NEW_LINE> dest = link[1] <NEW_LINE> ... | Print out links in easy-to-read format. | 625941d58c3a8732951585c6 |
def findAllUsers(self): <NEW_LINE> <INDENT> admins = DBSession.query(User).filter_by(admin=True).all() <NEW_LINE> return set(self.users + admins) | Return users in this report group and admins,
all users with access | 625941d5377c676e912723b2 |
def tokenize(movies): <NEW_LINE> <INDENT> movies.insert(len(movies.columns),'tokens',[tokenize_string(g) for g in movies['genres']]) <NEW_LINE> return movies | Append a new column to the movies DataFrame with header 'tokens'.
This will contain a list of strings, one per token, extracted
from the 'genre' field of each movie. Use the tokenize_string method above.
Note: you may modify the movies parameter directly; no need to make
a new copy.
Params:
movies...The movies DataF... | 625941d5f7d966606f6aa210 |
def filter_oxygen(binary_lines, col=0): <NEW_LINE> <INDENT> if len(binary_lines) == 1: <NEW_LINE> <INDENT> return binary_lines[0] <NEW_LINE> <DEDENT> current_column = list(map(lambda x: x[col], binary_lines)) <NEW_LINE> one_count = current_column.count("1") <NEW_LINE> zero_count = current_column.count("0") <NEW_LINE> i... | Determine most common value in current column | 625941d557b8e32f524836a6 |
def selfDividingNumbers2(self, left, right): <NEW_LINE> <INDENT> is_self_dividing = lambda num: '0' not in str(num) and all([num % int(digit) == 0 for digit in str(num)]) <NEW_LINE> x = filter(is_self_dividing, range(left, right + 1)) <NEW_LINE> return list(x) | :type left: int
:type right: int
:rtype: List[int] | 625941d5090684286d50eef1 |
def test_add_log_line(event_log, sample_log_lines): <NEW_LINE> <INDENT> log_line = sample_log_lines.make_insert_log_line() <NEW_LINE> event_log.add_log_line(log_line) <NEW_LINE> assert event_log.log_lines == [log_line] | Test adding a log line. | 625941d563b5f9789fde72f0 |
def make_weapon_table(env, node): <NEW_LINE> <INDENT> table = nodes.table() <NEW_LINE> tgroup = nodes.tgroup(cols=7) <NEW_LINE> table += tgroup <NEW_LINE> for i in range(7): <NEW_LINE> <INDENT> colspec = nodes.colspec(colwidth = 1) <NEW_LINE> tgroup += colspec <NEW_LINE> <DEDENT> rows = [] <NEW_LINE> thead = nodes.thea... | Utility method to create a table for weapons | 625941d52c8b7c6e89b359ca |
def observables(self, _prediction, parameters): <NEW_LINE> <INDENT> if _prediction not in self.predictions: <NEW_LINE> <INDENT> raise RuntimeError('Cannot create observables for unknown set of predictions: \'{}\''.format(_prediction)) <NEW_LINE> <DEDENT> prediction = self.predictions[_prediction] <NEW_LINE> options = e... | Creates a list of eos.Observable objects for the named set of predictions. | 625941d54c3428357757c532 |
def p_statement_import(self, p): <NEW_LINE> <INDENT> if self.importlvl > 8: <NEW_LINE> <INDENT> raise ImportError('Recrusive import level too deep > 8 (circular import ?)') <NEW_LINE> <DEDENT> ipath = utility.destring(p[3]) <NEW_LINE> fn, fe = os.path.splitext(ipath) <NEW_LINE> if not fe or fe.lower() == '.less': <NEW_... | statement : css_import t_ws css_string ';'
| css_import t_ws css_string dom ';' | 625941d58a349b6b435e837e |
def __contains__(self, x): <NEW_LINE> <INDENT> return RowStandardTableaux.__contains__(self, x) and [len(_) for _ in x] == self.shape | EXAMPLES::
sage: ST = RowStandardTableaux([2,1,1])
sage: all([st in ST for st in ST])
True
sage: len(filter(lambda x: x in ST, RowStandardTableaux(4)))
12
sage: ST.cardinality()
12 | 625941d5442bda511e8be620 |
def red_tag_dmg_limit(self, sample_size=1, **kwargs): <NEW_LINE> <INDENT> output = self._red_tag_CF.sample_unit_DV(sample_size=sample_size, **kwargs) <NEW_LINE> return output | Sample the red tag consequence function and return the proportion of
components that needs to be damaged to trigger a red tag.
The red tag consequence function is assumed to have a fixed median
value that does not depend on the quantity of damaged components.
Parameters
----------
sample_size: int, optional, d... | 625941d53617ad0b5ed68101 |
def interpolate_to_new_center_wl(self, new_wavelength_nm): <NEW_LINE> <INDENT> working_pulse = self.create_cloned_pulse() <NEW_LINE> working_pulse.set_center_wavelength_nm(new_wavelength_nm) <NEW_LINE> interpolator = interp1d(self.W_mks, self. AW, bounds_error = False, fill_value = 0.0) <NEW_LINE> working_pulse.set_AW(... | Change grids by interpolating the electric field onto a new
frequency grid, defined by the new center wavelength and the current
pulse parameters. This is useful when grid overlaps must be avoided,
for example in difference or sum frequency generation.
Parameters
----------
new_wavelength_nm : float
New c... | 625941d57047854f462a1612 |
def test_standard_quality(self): <NEW_LINE> <INDENT> def master_curve(x): <NEW_LINE> <INDENT> return 1. / (1. + np.exp(5 * (1. - x))) <NEW_LINE> <DEDENT> x = np.linspace(0, 2) <NEW_LINE> x_array = np.row_stack([x for i in range(10)]) <NEW_LINE> y_array = master_curve(x_array) <NEW_LINE> dy = 0.05 <NEW_LINE> dy_array = ... | Test that function returns close to one value if fed with the same x
and y values with some standard error applied | 625941d5435de62698dfde57 |
def clone(src, dst_path, skip_globals, skip_dimensions, skip_variables): <NEW_LINE> <INDENT> if os.path.exists(dst_path): <NEW_LINE> <INDENT> os.unlink(dst_path) <NEW_LINE> <DEDENT> dst = netCDF4.Dataset(dst_path, 'w') <NEW_LINE> for attname in src.ncattrs(): <NEW_LINE> <INDENT> if attname not in skip_globals: <NEW_LIN... | Mostly ripped from nc3tonc4 in netCDF4-python.
Added ability to skip dimension and variables.
Removed all of the unpacking logic for shorts. | 625941d53539df3088e2e555 |
def massaro_blair(): <NEW_LINE> <INDENT> return load(_os.path.join("npc", "massaro_blair.csv")) | The
| 625941d5adb09d7d5db6c999 |
def cate_stat(self,data,group0, group1, decimal=2): <NEW_LINE> <INDENT> distribution = self.label_dist(data) <NEW_LINE> binary_cate = self.binary_var <NEW_LINE> binary_all_descr = pd.DataFrame(np.sum(data[binary_cate]),columns = ['All']) <NEW_LINE> binary_g0_descr = pd.DataFrame(np.sum(group0[binary_cate]),columns = ['... | Input:
df:Whole dataset
group0: Group 0 of df
group1: Group 1 of df
decimal: Decimal precision
Output:
Statistical analysis of all categorical variables,
corresponding p values are also presented.
Binary variables and multi-category variables are included | 625941d556b00c62f0f14865 |
def invoke(bin_folder, interface_folder, last_exec_info, contract_name, endpoint, kwargs): <NEW_LINE> <INDENT> script_path = find_script(bin_folder, contract_name) <NEW_LINE> if not script_path: <NEW_LINE> <INDENT> raise ValueError(f'No executable for contract {contract_name}.') <NEW_LINE> <DEDENT> interface = _get_con... | Invoke a contract endpoint with provided arguments.
Storage variables are restored from previous contract execution and saved
once the execution is complete and only if it is successful.
:param bin_folder: Path to the folder containing contract compiled scripts.
:type bin_folder: str
:param interface_folder: Path to ... | 625941d5f548e778e58cd789 |
def parse_options(self, directory, benchmark_name, lang): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> long_options = ["micro", "plag-path=", "plag-tag=", "det-path=", "det-tag=", "help"] <NEW_LINE> opts, _ = getopt.getopt(sys.argv[1:], "p:d:h", long_options) <NEW_LINE> <DEDENT> except getopt.GetoptError as err: <NEW_L... | Parses the command line options. | 625941d5046cf37aa974cf51 |
def p_objlit_key(p): <NEW_LINE> <INDENT> if len(p) == 2: <NEW_LINE> <INDENT> p[0] = p[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p[0] = RuntimeObjectKey(p[2]) | objlit_key : id_str_or_num
| LSBRACKET expr RSBRACKET | 625941d592d797404e304395 |
def download_weight_filtering_user_repair_exec (): <NEW_LINE> <INDENT> write_message("Repairing for this ranking method is not defined. Skipping.") <NEW_LINE> return | Repair download weight filtering user ranking method | 625941d5a4f1c619b28b0241 |
def read_row(self, row, start_col=1): <NEW_LINE> <INDENT> values = [] <NEW_LINE> obj = {} <NEW_LINE> obj['Row: ' + str(row)] = values <NEW_LINE> col = start_col <NEW_LINE> while True: <NEW_LINE> <INDENT> cell = self.sheet.cell(row=row, column=col).value <NEW_LINE> if cell is None: <NEW_LINE> <INDENT> break <NEW_LINE> <... | Read values from a row
@row - The row to read
@start_col - The column to read past | 625941d5bde94217f3682ffa |
def to_hsv(img): <NEW_LINE> <INDENT> return cv2.cvtColor(img, cv2.COLOR_RGB2HSV) | Returns the same image in HSV format
The input image must be in RGB format | 625941d5ec188e330fd5a9a7 |
def istitle(s: str) -> bool: <NEW_LINE> <INDENT> pass | Returns true if string is properly "titlecased" and false otherwise. | 625941d59b70327d1c4e0fe0 |
def set_planet_resource_foci(): <NEW_LINE> <INDENT> Reporter.print_resource_ai_header() <NEW_LINE> resource_timer.start("Priority") <NEW_LINE> aistate = get_aistate() <NEW_LINE> production_priority = aistate.get_priority(PriorityType.RESOURCE_PRODUCTION) <NEW_LINE> research_priority = aistate.get_priority(PriorityType.... | set resource focus of planets | 625941d53cc13d1c6d3c7584 |
@app.route('/users/<int:user_id>/posts/new', methods=["POST"]) <NEW_LINE> def posts_new(user_id): <NEW_LINE> <INDENT> user = User.query.get_or_404(user_id) <NEW_LINE> tag_ids = [int(num) for num in request.form.getlist("tags")] <NEW_LINE> tags = Tag.query.filter(Tag.id.in_(tag_ids)).all() <NEW_LINE> new_post = Post(tit... | Handle form submission for creating a new post | 625941d5de87d2750b85ff9e |
def write_file(self, filename="WAVECAR.vasp", part="real"): <NEW_LINE> <INDENT> if not ( hasattr(self, "volumetricdata_real") and hasattr(self, "volumetricdata_imaginary") and hasattr(self, "volumetricdata_density") ): <NEW_LINE> <INDENT> self.set_volumetric_data(self.grid, self.structure) <NEW_LINE> <DEDENT> if part =... | will save the wavefunction in a file format that can be read by VESTA
This will only work if the wavefunction from lobster was constructed with:
"printLCAORealSpaceWavefunction kpoint 1 coordinates 0.0 0.0 0.0 coordinates 1.0 1.0 1.0 box bandlist 1 2 3 4
5 6 "
or similar (the whole unit cell has to be covered!)
Args:
... | 625941d5097d151d1a223063 |
def effectiveEdgePos(text): <NEW_LINE> <INDENT> if self._lineLengthEdge is None: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> tabExtraWidth = self.indentWidth - 1 <NEW_LINE> fullWidth = len(text) + (text.count('\t') * tabExtraWidth) <NEW_LINE> if fullWidth <= self._lineLengthEdge: <NEW_LINE> <INDENT> return -1 <NE... | Position of edge in a block.
Defined by self._lineLengthEdge, but visible width of is more than 1,
therefore effective position depends on count and position of symbols
Return -1 if line is too short to have edge | 625941d55fcc89381b1e18cb |
def decode(self, Y): <NEW_LINE> <INDENT> Y_decoded = [self.int_to_label[i] for i in Y] <NEW_LINE> return Y_decoded | input:
np.array of integers of length n_samples
returns:
list of strings of length n_samples | 625941d57c178a314d6ef66c |
def show_status(self): <NEW_LINE> <INDENT> print(self.name + "の現在位置は" + str(self.cur_pos) + "、HPは" + str(self.hp) + "です。") | 現在の状態を表示する
Parameters
----------
なし
Returns
-------
なし | 625941d515fb5d323cde0d1c |
@before.each_feature <NEW_LINE> def setup_feature_workdir(feature): <NEW_LINE> <INDENT> world.feature_workdir = join(world.lettuce_work_dir, feature.name) <NEW_LINE> os.mkdir(world.feature_workdir) | Create workdir for this feature | 625941d5fbf16365ca6f63d0 |
def background_model(depth): <NEW_LINE> <INDENT> depth = depth*-1.0 <NEW_LINE> depth_lst = np.array([-0.1, 5.0, 6.0, 10.0, 15.5, 16.5, 22.0, 31.0, 33.0, np.inf]) <NEW_LINE> depth_lst *= 1000.0 <NEW_LINE> vp_lst = np.array([5.0, 5.5, 6.3, 6.3, 6.4, 6.7, 6.75, 6.8, 7.8, 7.8]) <NEW_LINE> vp_lst *= 1000.0 <NEW_LINE> vp_int... | This is the SCEC-H background velocity model | 625941d5627d3e7fe0d6905c |
def delete_account(self, username): <NEW_LINE> <INDENT> self.a.delete_user(username) | -aa USERNAME, --add-account USERNAME
COMMANDS: Add a unix account. | 625941d557b8e32f524836a7 |
def hovmoller(array, lat_array, lon_array, latmin, latmax, lonmin, lonmax, mean): <NEW_LINE> <INDENT> latmin, lonmin, ilatmin, ilonmin = Dg.gridpoint(lat_array, lon_array, latmin, lonmin) <NEW_LINE> latmax, lonmax, ilatmax, ilonmax = Dg.gridpoint(lat_array, lon_array, latmax, lonmax) <NEW_LINE> lat = lat_array[ilatmin:... | Calcula a media meridional ou zonal
:param array:
:param lat_array:
:param lon_array:
:param latmin:
:param latmax:
:param lonmin:
:param lonmax:
:param mean: | 625941d5d18da76e235326e2 |
def example_decorator2(func): <NEW_LINE> <INDENT> def inner(): <NEW_LINE> <INDENT> func() <NEW_LINE> <DEDENT> return inner | 装饰器 | 625941d5f9cc0f698b140805 |
def invmod(a, N): <NEW_LINE> <INDENT> return xgcd(a, N)[1] % N | What is the multiplicative inverse of a, inv_a,
such that a * inv_a = 1 mod N. | 625941d571ff763f4b549899 |
def total_crime_rates(v, p): <NEW_LINE> <INDENT> totals = [] <NEW_LINE> append = totals.append <NEW_LINE> for i in range(len(v)): <NEW_LINE> <INDENT> v_state, v_rate = v[i] <NEW_LINE> p_state, p_rate = p[i] <NEW_LINE> if v_state == p_state: <NEW_LINE> <INDENT> append((v_state, v_rate + p_rate)) <NEW_LINE> <DEDENT> else... | Given that v and p are the list of violent crime rate and property crime
rate repectively, this function return a list of tuples containing the name
of the state and the total crime rate for that state. | 625941d5a219f33f34628b72 |
def wsfe_update_journal_class(self, cr, uid, ids, conn_id, context=None): <NEW_LINE> <INDENT> conn_obj = self.pool.get('wsafip.connection') <NEW_LINE> for srv in self.browse(cr, uid, ids, context=context): <NEW_LINE> <INDENT> if srv.code != 'wsfe': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> conn = conn_obj.browse... | Update journal class.
AFIP Description: Recuperador de valores referenciales de códigos de
Tipos de comprobante (FEParamGetTiposCbte) | 625941d53317a56b86939e60 |
def __delitem__(self, key): <NEW_LINE> <INDENT> del self.__data[key] <NEW_LINE> self.dao.save(self.__data) | Remove all `item` identifier content::
>>> del component_data_controller[key]
:param string key: Identifier | 625941d5fff4ab517eb2f647 |
def pack(self): <NEW_LINE> <INDENT> opcode_encoded = int_to_bytes(self.opcode) <NEW_LINE> block_num_encoded = int_to_bytes(self.block_num) <NEW_LINE> return opcode_encoded + block_num_encoded + self.data | Take internal values and return a string satisfying the tftp
specification with this packet's values. | 625941d5566aa707497f4772 |
def args_parser(lst): <NEW_LINE> <INDENT> result = Dotdict() <NEW_LINE> for e in lst: <NEW_LINE> <INDENT> if "=" not in e: <NEW_LINE> <INDENT> print("The arguments should be obeyed with the map format such as TEST_MODE=True, but was " + e) <NEW_LINE> continue <NEW_LINE> <DEDENT> key, value = e.split("=") <NEW_LINE> res... | :param list(String): contains args ex) TEST_MODE=True
:return: Dotdict | 625941d5e76e3b2f99f3aa14 |
def make_train_feed_dict(model, batch): <NEW_LINE> <INDENT> feed_dict = {model.x_elmo_input: batch[0], model.x: batch[1], model.pos: batch[2], model.labels['a']: batch[3], model.labels['b']: batch[4], model.labels['c']: batch[5], model.seq_len: batch[6], model.glove: batch[7], model.keep_prob: .5} <NEW_LINE> return fee... | Create feed_dict for training.
:param model:
:param batch:
:return feed_dict: | 625941d50fa83653e46571c6 |
def remove(self, targetType, key): <NEW_LINE> <INDENT> data = self.graphqlClient.request( query=QUERY["removeUdf"], params={ "targetType": targetType, "key": key, }, token=self.tokenProvider.getAccessToken(), ) <NEW_LINE> return data["removeUdf"] | 删除自定义字段
Args:
targetType (str) 自定义字段目标类型, USER 表示用户、ROLE 表示角色。
key (str) 字段 key | 625941d596565a6dacc8f8d6 |
def expand_define(expr): <NEW_LINE> <INDENT> if not is_list(expr): <NEW_LINE> <INDENT> return expr <NEW_LINE> <DEDENT> new_expr = [] <NEW_LINE> n = len(expr) <NEW_LINE> i = 0 <NEW_LINE> while i<n: <NEW_LINE> <INDENT> if is_symbol(expr[i]) and expr[i].name == 'define' and is_list(expr[i+1]): <NEW_LINE> <INDENT> symbol, ... | Converts (define (fn x) ...) to (define fn (lambda (x) ...)) | 625941d521bff66bcd684b5d |
def nuss_square(x, radix): <NEW_LINE> <INDENT> n = len(x) <NEW_LINE> pow = log2(n) <NEW_LINE> if 2 ** pow < n: <NEW_LINE> <INDENT> pow += 1 <NEW_LINE> <DEDENT> newn = 2 ** (pow + 1) <NEW_LINE> z = cyc_sqr(x + ([ZERO] * (newn - n)), radix) <NEW_LINE> return z[:2 * n - 1] | Square a list of longs using the Nussbaumer convolution algorithm.
Still need to add more intelligence about when to use kmult and how
to handle x and y with radically different lengths. Currently, the shorter
list is padded to the same length as the padded longer list. | 625941d57d847024c06be4c9 |
def path_exists(self, path): <NEW_LINE> <INDENT> path = path.replace(os.environ['HOME'], "/home/{}".format(self.DOCKER_USER)) <NEW_LINE> command = self.command_as_list([os.path.join(get_tools_helper_dir(), "path_exists"), path]) <NEW_LINE> return self._exec_command(command)[0] | Check if a path exists inside the container | 625941d510dbd63aa1bd2dae |
def load_test_data(filename): <NEW_LINE> <INDENT> D = [] <NEW_LINE> with open(filename, encoding='utf-8') as f: <NEW_LINE> <INDENT> for l in f: <NEW_LINE> <INDENT> l = l.strip().split('\t') <NEW_LINE> D.append((l[-2], l[-1], float(l[-3]))) <NEW_LINE> <DEDENT> <DEDENT> return D | 加载测试数据(带标签)
单条格式:(文本1, 文本2, 标签) | 625941d531939e2706e4d074 |
def yp(y, t): <NEW_LINE> <INDENT> return t * sqrt(y) | derivata parțială de ordinul I | 625941d5009cb60464c635bc |
def test_shell_discovery_plugin_found(): <NEW_LINE> <INDENT> manager = PluginManager() <NEW_LINE> manager.setPluginPlaces( [os.path.join(os.path.dirname(statick_tool.__file__), "plugins")] ) <NEW_LINE> manager.setCategoriesFilter( { "Discovery": DiscoveryPlugin, } ) <NEW_LINE> manager.collectPlugins() <NEW_LINE> assert... | Test that the plugin manager finds the Shell discovery plugin. | 625941d532920d7e50b283dd |
def _create_builder(taxonomy, data_producer_id, packet_factory_type): <NEW_LINE> <INDENT> packet_factory = PacketFactory.get_packet_factory(packet_factory_type) <NEW_LINE> def builder(**sample_data): <NEW_LINE> <INDENT> granule = packet_factory.build_packet(data_producer_id=data_producer_id, taxonomy=taxonomy, data=sam... | Creates a builder function corresponding to the given parameters. | 625941d5851cf427c661a719 |
def enroll(self, courseCode: str, mode: str='add', pnp: bool=None, varUnits: int=None, authCode: str='') -> requests.Response: <NEW_LINE> <INDENT> post = { 'mode': mode, 'courseCode': courseCode, 'gradeOption': {False: '1', True: '2', None: ''}[pnp], 'varUnits': '' if varUnits is None else str(varUnits), 'authCode': au... | Attempts to add, drop or change a course.
Args:
courseCode (str): The course code
mode (str, optional): One of 'add', 'drop' and 'change'. Defaults to 'add'.
pnp (bool, optional): Whether to take the course P/NP. Defaults to None.
varUnits (int, optional): The requested number of variable units. Defaul... | 625941d58e05c05ec3eea582 |
def randomize_stimuli(self): <NEW_LINE> <INDENT> rand_stimuli_data = self.stimuli_data <NEW_LINE> random.shuffle(rand_stimuli_data) <NEW_LINE> self.rand_stimuli_data = rand_stimuli_data | Randomize the stimuli presentation order. | 625941d5d268445f265b507a |
def test_dual_rate_periodic_send(): <NEW_LINE> <INDENT> msg = can.Message(arbitration_id=0x0c112200, data=[0, 1, 2, 3, 4, 5]) <NEW_LINE> print("Creating cyclic task to send message 10 times at 1ms, then every 500ms") <NEW_LINE> task = can.interface.MultiRateCyclicSendTask('vcan0', msg, 10, 0.001, 0.50) <NEW_LINE> time.... | Send a message 10 times at 1ms intervals, then continue to send every 500ms | 625941d5379a373c97cfad52 |
def sigma_rel(self, params=None): <NEW_LINE> <INDENT> return np.squeeze(self.sigma(params)/self.mu(params)) | Value of the standard deviation in the covariance model sigma**2 * exp(-t/tau), normalized by the
mean.
Parameters
----------
params : list
Parameters of the GP covariance model, a * exp(-c*t).
These are log(a), log(c), and the (constant) mean, mu.
If None, the parameters currently set in the QuiescenceMod... | 625941d51f037a2d8b946409 |
def update_extra_selections(self): <NEW_LINE> <INDENT> extra_selections = [] <NEW_LINE> for key, extra in list(self.extra_selections_dict.items()): <NEW_LINE> <INDENT> extra_selections.extend(extra) <NEW_LINE> <DEDENT> self.decorations.add(extra_selections) | Add extra selections to DecorationsManager.
TODO: This method could be remove it and decorations could be
added/removed in set_extra_selections/clear_extra_selections. | 625941d597e22403b379d1a6 |
def search_missing_revision_ids(self, find_ghosts=True, revision_ids=None, if_present_ids=None, limit=None): <NEW_LINE> <INDENT> with self.lock_read(): <NEW_LINE> <INDENT> source_ids_set = self._present_source_revisions_for( revision_ids, if_present_ids) <NEW_LINE> target_ids = set(self.target._all_possible_ids()) <NEW... | See InterRepository.search_missing_revision_ids(). | 625941d5dc8b845886cb5742 |
def checkinput(self, input): <NEW_LINE> <INDENT> input = [int(i) for i in str(input)] <NEW_LINE> if input[0] == 1: <NEW_LINE> <INDENT> return 'distance' <NEW_LINE> <DEDENT> elif input[0] == 2: <NEW_LINE> <INDENT> return 'temp' <NEW_LINE> <DEDENT> elif input[0] == 3: <NEW_LINE> <INDENT> return 'status' | Check de input op wat voor waarde deze weergeeft. Er zijn drie mogelijke waarden: 1: afstand van de ultrasonoor | 2: temperatuur | 3: status van het zonnescherm (in- of uitgerold)
Deze input komt binnen via Serial
param {int} input De input vanuit Serial
return {String} distance | temp | status | 625941d5ad47b63b2c50a18b |
def __load(self): <NEW_LINE> <INDENT> scriptsDir = QDir(self.scriptsDirectory()) <NEW_LINE> if not scriptsDir.exists(): <NEW_LINE> <INDENT> scriptsDir.mkpath(self.scriptsDirectory()) <NEW_LINE> <DEDENT> if not scriptsDir.exists("requires"): <NEW_LINE> <INDENT> scriptsDir.mkdir("requires") <NEW_LINE> <DEDENT> self.__dis... | Private slot to load the available scripts into the manager. | 625941d5167d2b6e31218da1 |
def __init__(self): <NEW_LINE> <INDENT> self.TryCount = None <NEW_LINE> self.UserCount = None | :param TryCount: 尝试次数
:type TryCount: int
:param UserCount: 用户请求数量
:type UserCount: int | 625941d51b99ca400220acbe |
def onInputKey(self, key): <NEW_LINE> <INDENT> if key == QtCore.Qt.Key_Up: <NEW_LINE> <INDENT> if self.history_index > 0: <NEW_LINE> <INDENT> self.history_index -= 1 <NEW_LINE> item = self.history.item(self.history_index) <NEW_LINE> self.input.setText(item.text()) <NEW_LINE> <DEDENT> <DEDENT> elif key == QtCore.Qt.Key_... | Input line edit key pressed. | 625941d53d592f4c4ed1d276 |
def _on_canvas_clicked(self, event: tkinter.Event) -> None: <NEW_LINE> <INDENT> width = self._canvas.winfo_width() <NEW_LINE> height = self._canvas.winfo_height() <NEW_LINE> click_point = point.from_pixel(event.x, event.y, width, height) <NEW_LINE> move_click = click_point.pixel(width, height) <NEW_LINE> for row in ran... | Makes a Othello move and redraws the board when tkinter window is clicked. | 625941d563f4b57ef0001321 |
def add_context(self): <NEW_LINE> <INDENT> if self._added_context: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self._added_context = True <NEW_LINE> if ('codebefore' in exercice) or ('codeafter' in exercice): <NEW_LINE> <INDENT> file_src = open(self.source_path(), "r") <NEW_LINE> content_src = file_src.read() <... | Add contextual code around original submission before
compiling a programm. | 625941d59f2886367277aa98 |
def canonicalize(self,verbose=0): <NEW_LINE> <INDENT> if (verbose): <NEW_LINE> <INDENT> print(" ... canonicalizing permutation operator expressions") <NEW_LINE> <DEDENT> another = self.duplicate() <NEW_LINE> for tensor in self.tensors: <NEW_LINE> <INDENT> super = [] <NEW_LINE> for nindex in range(len(tensor.indexes)/2)... | Canonicalizes the permutation operators | 625941d5d4950a0f3b08c55a |
def main(): <NEW_LINE> <INDENT> create_process("./server_config.json", update_blog_post_callback) | main entrance for the whole project | 625941d5ff9c53063f47c3ff |
def copyVariable(self, var, key=None, dtype=None, dimensions=None, fill_value=None, withdata=True): <NEW_LINE> <INDENT> if key is None: <NEW_LINE> <INDENT> for propk in ['_name', 'name', 'standard_name', 'long_name']: <NEW_LINE> <INDENT> if hasattr(var, propk): <NEW_LINE> <INDENT> key = getattr(var, propk) <NEW_LINE> b... | Copy var into self as vark
Parameters
----------
var : PseudoNetCDFVariable
netCDF4.Variable-like object (must have ncattrs and setncatts)
key : string
key for variable in self (can be omitted if var has name,
standard_name, or long_name)
dtype : string or numpy.dtype
change the data type to dtype
dime... | 625941d52ae34c7f2600d33d |
def read(self,source): <NEW_LINE> <INDENT> self._conf.read(source) <NEW_LINE> return self | !reads and parses a config file
Opens the specified config file and reads it, adding its
contents to the configuration. This is used to implement the
from_file module-scope function. You can use it again on an
ProdConfig object to read additional files.
@param source the file to read
@return self | 625941d563b5f9789fde72f1 |
@app.route('/') <NEW_LINE> def Home(): <NEW_LINE> <INDENT> return current_app.send_static_file("index.html") | Landing page for application | 625941d53617ad0b5ed68102 |
def constructMaximumBinaryTree(self, nums): <NEW_LINE> <INDENT> if not nums: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> max_num = max(nums) <NEW_LINE> max_pos = nums.index(max_num) <NEW_LINE> new_node = TreeNode(max_num) <NEW_LINE> new_node.left = self.constructMaximumBinaryTree(nums[:max_pos]) <NEW_LINE> new_... | :type nums: List[int]
:rtype: TreeNode | 625941d599cbb53fe6792df3 |
def _fillEdgeMissingWithSuccessor (self, nA, nB, nC): <NEW_LINE> <INDENT> edgesBC = self.G[nB][nC].values() <NEW_LINE> edgesAC = self.G[nA][nC].values() <NEW_LINE> lengthA = self._getNodeLength(nA) <NEW_LINE> lengthB = self._getNodeLength(nB) <NEW_LINE> lengthC = self._getNodeLength(nC) <NEW_LINE> minBC= self.edgeBound... | Return a new edge between nA->nB when the following edges exist:
nA->nC, nB->nC. | 625941d507f4c71912b11690 |
def forward(self, g, inputs, mod_args=None, mod_kwargs=None): <NEW_LINE> <INDENT> if mod_args is None: <NEW_LINE> <INDENT> mod_args = {} <NEW_LINE> <DEDENT> if mod_kwargs is None: <NEW_LINE> <INDENT> mod_kwargs = {} <NEW_LINE> <DEDENT> outputs = {nty : [] for nty in g.dsttypes} <NEW_LINE> if isinstance(inputs, tuple): ... | Forward computation
Invoke the forward function with each module and aggregate their results.
Parameters
----------
g : DGLHeteroGraph
Graph data.
inputs : dict[str, Tensor] or pair of dict[str, Tensor]
Input node features.
mod_args : dict[str, tuple[any]], optional
Extra positional arguments for the sub-... | 625941d5eab8aa0e5d26dd64 |
def test_next_pointer(test_lists): <NEW_LINE> <INDENT> assert test_lists[2].head.next.data is 4 | Test next pointer. | 625941d5627d3e7fe0d6905d |
def get(self): <NEW_LINE> <INDENT> student = self.personalize_page_and_get_enrolled() <NEW_LINE> if not student: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.template_value['student'] = student <NEW_LINE> self.template_value['navbar'] = {'registration': True} <NEW_LINE> self.template_value['student_unenroll_xsrf... | Handles GET requests. | 625941d55e10d32532c5f133 |
def allopen(fname, *args, **kwargs): <NEW_LINE> <INDENT> if hasattr(fname, 'write'): <NEW_LINE> <INDENT> return fname <NEW_LINE> <DEDENT> if args: <NEW_LINE> <INDENT> mode = args[0] <NEW_LINE> <DEDENT> elif 'mode' in kwargs: <NEW_LINE> <INDENT> mode = kwargs['mode'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mode = ... | Generic file-like object open
If input ``fname`` already looks like a file, pass through.
If ``fname`` ends with recognizable compressed types, use python
libraries to open as file-like objects (read or write)
Otherwise, use standard ``open``. | 625941d55f7d997b87174ca5 |
def _resource_and_snap_data_from_snapshot(self, snapshot, empty_ok=False): <NEW_LINE> <INDENT> s_uuid = snapshot['id'] <NEW_LINE> res, rs = self.call_or_reconnect(self.odm.list_snapshots, self.empty_list, self.empty_list, dm_utils.dict_to_aux_props( {CINDER_AUX_PROP_id: s_uuid}), self.empty_list) <NEW_LINE> self._check... | Find the DRBD Resource and the snapshot name
from the snapshot ID. | 625941d582261d6c526ab6ad |
def test_2_header_type(self): <NEW_LINE> <INDENT> xlsfo = open(os.path.join(self.testdata_path, 'simple.xls')) <NEW_LINE> iterator, metadata = xls.parse(xlsfo) <NEW_LINE> assert_equal([{'type': 'String', 'id': u'date'}, {'id': u'temperature', 'type': 'Integer'}, {'id': u'place', 'type': 'String'}], metadata['fields']) | Test guessing header type | 625941d54f88993c3716c273 |
def Sentence2Embedding(sentences, word_to_index): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for sentence in sentences: <NEW_LINE> <INDENT> temp = [] <NEW_LINE> for word in sentence.split(): <NEW_LINE> <INDENT> temp.append(word_to_index[word.lower()]) <NEW_LINE> <DEDENT> result.append(temp) <NEW_LINE> <DEDENT> return r... | translate sentence to vector using word embedding | 625941d54d74a7450ccd43d0 |
def output_chromosome_sizes(args): <NEW_LINE> <INDENT> if args.assembly == 'auto': <NEW_LINE> <INDENT> assm = os.path.basename(args.genome).split('.')[0].strip() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assm = args.assembly <NEW_LINE> <DEDENT> out = [] <NEW_LINE> selector = re.compile(args.select.strip('"')) <NEW_... | :param args:
:return: | 625941d5be7bc26dc91cd80a |
def validate(self, value): <NEW_LINE> <INDENT> if (self._type is not None and value is not None) and (self._type != Any and type(value) != self._type): <NEW_LINE> <INDENT> raise TypeException(self.field, str(self._type)) <NEW_LINE> <DEDENT> if self._default_value and value is None: <NEW_LINE> <INDENT> value = self._def... | Validates the Schema with ``value``.
:param value: Value to validate
:return: Returns the validated value, or throws an exception if validation fails. | 625941d50383005118ecf7ee |
def findPairs(self, nums, k): <NEW_LINE> <INDENT> if k<0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> nset=set() <NEW_LINE> res=set() <NEW_LINE> for num in nums: <NEW_LINE> <INDENT> if num+k in nset: <NEW_LINE> <INDENT> res.add((num,num+k)) <NEW_LINE> <DEDENT> if num-k in nset: <NEW_LINE> <INDENT> res.add((num-k,n... | :type nums: List[int]
:type k: int
:rtype: int | 625941d52eb69b55b151cabd |
def __init__(self, host, db, username, password): <NEW_LINE> <INDENT> self.host = host <NEW_LINE> self.db = db <NEW_LINE> self.username = username <NEW_LINE> self.password = password <NEW_LINE> self.common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(self.host)) <NEW_LINE> self.uid = self.common.authenticate... | Connect via xml-rpc | 625941d50c0af96317bb83f5 |
def test_served(self): <NEW_LINE> <INDENT> e = Customer('abcd') <NEW_LINE> assert hasattr(e, 'served') <NEW_LINE> assert type(e.served) == bool <NEW_LINE> assert e.served == False | `test_served()`
Tests the pre- and post-conditions of the served attribute | 625941d5d53ae8145f87a47a |
def sf(array_standard, array_new): <NEW_LINE> <INDENT> return c(array_new) * np.abs(d_scalars(array_standard) - d_scalars(difference(array_standard, array_new))) | Smoothing factor
:param array_standard: standard set
:param array_new: new set
:return: smoothing factor | 625941d557b8e32f524836a8 |
def get_order(self, order_id): <NEW_LINE> <INDENT> for index, order in enumerate(self.orders): <NEW_LINE> <INDENT> if order['id'] == order_id: <NEW_LINE> <INDENT> return order, index <NEW_LINE> <DEDENT> <DEDENT> return None, None | Return market order and index in list of orders for the order id.
This method looks up the order with the specified order id and returns
the order and its index in the list of orders managed by the market
simulator if found, otherwise None.
:param int order_id: Order id for the order to retrieve from the market
si... | 625941d53317a56b86939e61 |
def test_under_first_page(self): <NEW_LINE> <INDENT> page_info = Paginator.page_info(page=6, total=50, items_per_page=10) <NEW_LINE> self.assertEqual(page_info['page'], { 'current_page': 6, 'previous_page': 5, 'next_page': None, }) | Pagination info for the a page before the first page of multiple pages
under page
it lists current page
it has no previous page
it lists first page as next page | 625941d524f1403a92600d71 |
def _hard_reboot(self, context, instance, network_info, block_device_info=None): <NEW_LINE> <INDENT> self._destroy(instance) <NEW_LINE> self._undefine_domain(instance) <NEW_LINE> instance_dir = libvirt_utils.get_instance_path(instance) <NEW_LINE> fileutils.ensure_tree(instance_dir) <NEW_LINE> disk_info = blockinfo.get_... | Reboot a virtual machine, given an instance reference.
Performs a Libvirt reset (if supported) on the domain.
If Libvirt reset is unavailable this method actually destroys and
re-creates the domain to ensure the reboot happens, as the guest
OS cannot ignore this action. | 625941d52c8b7c6e89b359cc |
def requestFile(self, relName, mode='r', openMethod=open, *args, **kwargs): <NEW_LINE> <INDENT> writingMode = (('w' in mode) or ('a' in mode)) <NEW_LINE> ana = self._analyzeFilename(relName, pedantic=writingMode) <NEW_LINE> fullName = ana["fullname"] <NEW_LINE> if writingMode: <NEW_LINE> <INDENT> self.createSubfolder(a... | Obtain a file object within the PyA data path.
This method opens and creates files within PyA's data path.
If the directory in which a file shall be created does not
yet exist, it will be created.
Parameters
----------
relName : string
The filename. Usually, it will be given relative to the PyA
data path, but... | 625941d57d43ff24873a2ead |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.