code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
@csrf_exempt <NEW_LINE> @api_view(['POST']) <NEW_LINE> @authentication_classes((SessionAuthentication, BasicAuthentication, JSONWebTokenAuthentication, JSONWebTokenAuthenticationQS)) <NEW_LINE> @permission_classes((IsAuthenticated, AccessPermission,)) <NEW_LINE> def access(request): <NEW_LINE> <INDENT> data = JSONParse... | :param request: `card_id`
:return: `status` | 625941f331939e2706e4d45d |
def smoothscale(surface, size): <NEW_LINE> <INDENT> return scale(surface, size) | Calls scale().
Return Surface resized by the given size. | 625941f30c0af96317bb87e3 |
def activate(self): <NEW_LINE> <INDENT> print("{} - activate()".format(self.__class__.__name__)) <NEW_LINE> self._update_games() | Form activated. Load all defined games into tblGames. | 625941f392d797404e304789 |
def find_offset(text, call): <NEW_LINE> <INDENT> text_list = text.split('\n') <NEW_LINE> offset = 0 <NEW_LINE> for l in range(call.lineno - 1): <NEW_LINE> <INDENT> offset += len(text_list[l]) + 1 <NEW_LINE> <DEDENT> offset += call.col_offset <NEW_LINE> return offset | Takes in a text and function call and finds the start of call within text | 625941f3a8370b7717052e99 |
def update_baseline(self, t, r_bar, r): <NEW_LINE> <INDENT> if t == 0: <NEW_LINE> <INDENT> return r_bar + r <NEW_LINE> <DEDENT> return r_bar + (1 / t) * (r - r_bar) | Returns the updated reward baseline
Arguments:
----------
int t : current timesteps
float r_bar : current reward baseline
float r : current reward
Returns:
--------
float new_r_bar : updated reward baseline for timestep | 625941f35fcc89381b1e1cc1 |
def remove_blacklist(self, ips): <NEW_LINE> <INDENT> if type(ips) == str: <NEW_LINE> <INDENT> self._remove_list('blacklist', ips) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for _ip in ips: <NEW_LINE> <INDENT> self._remove_list('blacklist', _ip) | 删除黑名单
@param {str|list} ips - 要删除的ip或ip列表 | 625941f360cbc95b062c6b40 |
def full_way(self, fpdf, ftrans, forigin_name): <NEW_LINE> <INDENT> full_output = complete_it(self.open_file_path, self.save_file_path, self.index_num, forigin_name) <NEW_LINE> for i in range(fpdf.pageCount): <NEW_LINE> <INDENT> pm = fpdf[i].getPixmap(matrix=ftrans, alpha=False) <NEW_LINE> output_main = full_output[0] ... | 全量及原文件名输出 | 625941f376d4e153a657f12f |
def walk(uri, **kwargs): <NEW_LINE> <INDENT> with open(uri, **kwargs) as walker: <NEW_LINE> <INDENT> return walker.walk() | Walk a Directory given a URI. | 625941f3a79ad161976cc742 |
def all_connected_players(self): <NEW_LINE> <INDENT> return list(set(session.player for session in self.values() if session.logged_in and session.player)) | Get a unique list of connected and logged-in Players.
Returns:
players (list): All conected Players (which may be fewer than the
amount of Sessions due to multi-playing). | 625941f3851cf427c661ab06 |
def test_continous_paging(self): <NEW_LINE> <INDENT> for ep in self.execution_profiles.keys(): <NEW_LINE> <INDENT> results = list(self.session_with_profiles.execute(self.select_all_statement, execution_profile= ep)) <NEW_LINE> self.assertEqual(len(results), 150) | Test to ensure that various continuous paging schemes return the full set of results.
@since 3.20
@jira_ticket PYTHON-615
@expected_result various continous paging options should fetch all the results
@test_category queries | 625941f399fddb7c1c9de98a |
def list_all_files( base_path, api_scheme, api_host, api_port, logger, version, username, password ): <NEW_LINE> <INDENT> RECORDS_IN_BATCH = 1000 <NEW_LINE> logger.info(f'[+] Starting with base_path: {base_path}') <NEW_LINE> http_client = HttpClient( api_scheme=api_scheme, api_host=api_host, api_port=api_port, logger=l... | Iterate over all files. Hash and generate output | 625941f3b545ff76a8914412 |
def draw_qq_plots_for_sets(self, set_files, pheno_nr): <NEW_LINE> <INDENT> set_file = set_files[pheno_nr-1] <NEW_LINE> image_filename = self.inout.out + "qq-plot_all_sets.P" + str(pheno_nr) + ".pdf" <NEW_LINE> log.info("Saved QQ plot(s) from gene set(s) as " + image_filename) <NEW_LINE> r_variables = {"p_values_file" :... | Draw quantile-quantile plots for P values of gene sets. | 625941f31f5feb6acb0c5146 |
def test_create_user_page(self): <NEW_LINE> <INDENT> form = {"username":"test_create_user", "password1":"azerJkdfe123", "password2":"azerJkdfe123", 'email':"g@g.com", 'first_name':"jean", 'last_name':"claude", } <NEW_LINE> response = self.client.post(reverse('create_user'), form ) <NEW_LINE> self.assertEqual(response.s... | This test will make sure url 'create_user' works properly | 625941f3090684286d50f2ed |
def requirements_need_update(reqfile): <NEW_LINE> <INDENT> current_hash = hexhash(reqfile) <NEW_LINE> if not files.exists('.requirements.hash'): <NEW_LINE> <INDENT> run('touch .requirements.hash') <NEW_LINE> <DEDENT> existing_hash = run('cat .requirements.hash') <NEW_LINE> if current_hash != existing_hash: <NEW_LINE> <... | Do our requirements need an update? Returns a boolean | 625941f3596a89723608a0b4 |
def update_io_details(self, name, directory): <NEW_LINE> <INDENT> if sys.platform.startswith("win"): <NEW_LINE> <INDENT> directory = self.unix_path_to_windows(directory) <NEW_LINE> <DEDENT> self.out_name_str.set(name) <NEW_LINE> self.out_dir_str.set(directory) | Updates the name and location of the generated workbook | 625941f3091ae35668667551 |
def validate_file(fpath, file_hash, algorithm='auto', chunk_size=65535): <NEW_LINE> <INDENT> if ((algorithm == 'sha256') or (algorithm == 'auto' and len( file_hash) == 64)): <NEW_LINE> <INDENT> hasher = 'sha256' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hasher = 'md5' <NEW_LINE> <DEDENT> if str(hash_file(fpath, has... | Validates a file against a sha256 or md5 hash.
:param fpath: path to the file being validated
:param file_hash: The expected hash string of the file.
The sha256 and md5 hash algorithms are both supported.
:param algorithm: Hash algorithm, one of 'auto', 'sha256', or 'md5'.
The default 'auto' detects the hash ... | 625941f3435de62698dfe24a |
def upload_network(network, w_file, b_file): <NEW_LINE> <INDENT> w_df = pd.read_csv(w_file, header=None) <NEW_LINE> b_df = pd.read_csv(b_file, header=None) <NEW_LINE> populate_network(network, w_df, b_df) | upload with given weights and bias | 625941f350485f2cf553d399 |
def between(x, xxx_todo_changeme, tol): <NEW_LINE> <INDENT> (x0, x1) = xxx_todo_changeme <NEW_LINE> assert x0 < x1 <NEW_LINE> return x >= x0 - tol and x <= x1 + tol | Approx x0 <= x <= x1 | 625941f3b57a9660fec33e89 |
def of_type(self, of_type): <NEW_LINE> <INDENT> if not isinstance(of_type, type): <NEW_LINE> <INDENT> raise TypeError("Value for 'of_type' is not a type.") <NEW_LINE> <DEDENT> return Queryable((element for element in self if isinstance(element, of_type))) | Filters the elements based on the specified type.
:param of_type: The type to keep.
:type of_type: type
:return: The elements of the sequence with the specified type.
:rtype: :class:`Queryable`
:raise TypeError: if 'of_type' is not a type | 625941f3d99f1b3c44c67b7f |
def _calculate_delta(self, prediction, targets): <NEW_LINE> <INDENT> return ( (targets - prediction) ** 2) | Calculates an error delta.
:param prediction: Current prediction.
:param targets: Desired prediction.
:return: Delta of error difference. | 625941f3b57a9660fec33e8a |
def symmetrize(direction: typing.Union[int, str] = 'NEGATIVE_X', threshold: float = 0.0001): <NEW_LINE> <INDENT> pass | Enforce symmetry (both form and topological) across an axis
:param direction: Direction, Which sides to copy from and to
:type direction: typing.Union[int, str]
:param threshold: Threshold, Limit for snap middle vertices to the axis center
:type threshold: float | 625941f3fb3f5b602dac3c97 |
def rms_update(self, learning_rate, decay_rate): <NEW_LINE> <INDENT> for op in self.ops: <NEW_LINE> <INDENT> op.rms_update(learning_rate, decay_rate) | Updates the parameters of each differentiable operation using RMSprop rule.
Note: differentiable operations without learnable parameters do nothing when .rms_update() is invoked. | 625941f37b25080760e39a52 |
@main.command() <NEW_LINE> @click.argument('package', required=True) <NEW_LINE> @needs_repo <NEW_LINE> def show(package): <NEW_LINE> <INDENT> repo = pomu_active_repo() <NEW_LINE> category, _, name = package.rpartition('/') <NEW_LINE> name, _, slot = name.partition(':') <NEW_LINE> pkg = repo.get_package(name, category, ... | Display installed package info | 625941f315fb5d323cde1116 |
def load_dir(self, dir=None, recursive=False): <NEW_LINE> <INDENT> def _process_list(root, mylist): <NEW_LINE> <INDENT> shape = None <NEW_LINE> for f in mylist: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> shape = self.parse_and_append(os.path.join(root, f), flist, shape) <NEW_LINE> if not self.consider_equal: <NEW_LIN... | Look for files in `dir` recursively and populate data structures.
Parameters
----------
dir : path | 625941f3d4950a0f3b08c943 |
def line_width(line): <NEW_LINE> <INDENT> return len(line.translate(_remove_combining)) | Unicode combining symbols (modifiers) are not ever displayed as
separate symbols and thus shouldn't be counted | 625941f37cff6e4e81117f82 |
@bp.route('/jobs/<job_id>') <NEW_LINE> @apimethod(rest.BadpennyJob, int) <NEW_LINE> @p.base.badpenny.view.require() <NEW_LINE> def get_job(job_id): <NEW_LINE> <INDENT> j = tables.BadpennyJob.query.filter( tables.BadpennyJob.id == job_id).first() <NEW_LINE> if not j: <NEW_LINE> <INDENT> raise NotFound <NEW_LINE> <DEDENT... | Get information on a badpenny job by its ID. Use this to poll for job
completion. | 625941f3bd1bec0571d90c2c |
def execute_db_config(project_name): <NEW_LINE> <INDENT> supported_databases = { '1': 'MongoDB', } <NEW_LINE> failed_attempts = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> install = input('Do you want to install database for your application? [YES/NO] : ') <NEW_LINE> if install.lower() == 'yes': <NEW_LINE> <INDENT> pr... | Function to execute database config
:param project_name: Name of the project
:return: | 625941f373bcbd0ca4b2c672 |
def get_items(chapter="news", n_items=10): <NEW_LINE> <INDENT> n_items = int(n_items) <NEW_LINE> request_url = BBC_BASE_URL + "/" + chapter <NEW_LINE> exception_message = None <NEW_LINE> title_and_url = [] <NEW_LINE> try: <NEW_LINE> <INDENT> with requests.Session() as s: <NEW_LINE> <INDENT> data = s.get(request_url) <N... | This function takes in a name of chapter (like "news" or "sports")
and number of items required from that chapter and returns a list
of tuples having title and url | 625941f3d164cc617578334c |
def __init__(self, game, action_level, power_name): <NEW_LINE> <INDENT> assert action_level in {'power', 'observer', 'omniscient', 'master'} <NEW_LINE> self.game = game <NEW_LINE> self.power_name = power_name <NEW_LINE> self.__action_level = action_level | Initialize a game request level.
:param game: related game data
:param action_level: action level, either:
- 'power'
- 'observer'
- 'omniscient'
- 'master'
:param power_name: (optional) power name specified in game request. Required if level is 'power'.
:type game: diplomacy.server.server_game.Server... | 625941f34f88993c3716c65d |
def download_enstaller(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader): <NEW_LINE> <INDENT> expected_sha256 = None <NEW_LINE> for k, v in VERSION_TO_SHA256: <NEW_LINE> <INDENT> if k == version: <NEW_LINE> <INDENT> expected_sha256 = v <NEW_LINE> bre... | Download enstaller egg from a specified location and return its filename
Parameters
----------
version : str
The version to fetch. | 625941f3be8e80087fb21234 |
def __init__(self): <NEW_LINE> <INDENT> self.graph_parameters = {} | Initialization. | 625941f396565a6dacc8fcc6 |
def expectation_db_operator_with_pw_basis_state( operator, plane_wave_occ_orbitals, n_spatial_orbitals, grid, spinless): <NEW_LINE> <INDENT> expectation_value = operator.terms.get((), 0.0) <NEW_LINE> for single_action, coefficient in iteritems(operator.terms): <NEW_LINE> <INDENT> if len(single_action) == 2: <NEW_LINE> ... | Compute expectation value of a dual basis operator with a plane
wave computational basis state.
Args:
operator: Dual-basis representation of FermionOperator to evaluate
expectation value of. Can have at most 3-body terms.
plane_wave_occ_orbitals (list): list of occupied plane-wave orbitals.
n... | 625941f38da39b475bd65579 |
def convert_effectsize_fsqu(f2=None, eta2=None): <NEW_LINE> <INDENT> if f2 is not None: <NEW_LINE> <INDENT> eta2 = 1 / (1 + 1 / f2) <NEW_LINE> <DEDENT> elif eta2 is not None: <NEW_LINE> <INDENT> f2 = eta2 / (1 - eta2) <NEW_LINE> <DEDENT> res = Holder(f2=f2, eta2=eta2) <NEW_LINE> return res | convert squared effect sizes in f family
f2 is signal to noise ratio, var_explained / var_residual
eta2 is proportion of explained variance, var_explained / var_total
omega2 is ...
uses the relationship:
f2 = eta2 / (1 - eta2)
Parameters
----------
f2 : None or float
Squared Cohen's F effect size. If f2 is not No... | 625941f33539df3088e2e948 |
def main(): <NEW_LINE> <INDENT> argument_spec = dict( dfs_id=dict(required=False, type='str'), dfs_source_ip=dict(required=False, type='str'), dfs_source_vpn=dict(required=False, type='str'), dfs_udp_port=dict(required=False, type='str'), dfs_all_active=dict(required=False, type='str', choices=['enable', 'disable']), d... | Module main | 625941f3be383301e01b5a76 |
def get_subset(data, col=None, cond_value=0, flag=None): <NEW_LINE> <INDENT> def pd_get_subset(df, col, cond_value, flag=None): <NEW_LINE> <INDENT> if flag == "==": <NEW_LINE> <INDENT> return df[df[col] == cond_value] <NEW_LINE> <DEDENT> elif flag == "<": <NEW_LINE> <INDENT> return df[df[col] < cond_value] <NEW_LINE> <... | Get a subset of the data based on < > != == <= >= flags
Parameters
----------
data : pd.DataFrame|np.array
Data to slice
col : str(Optional)
column name if using a pd.DataFrame
cond_value : int|float
Conditional value to compare against
flag : str(==,!=,<,<=,>,>=)
nil
Returns
-------
pd.DataFrame|np.... | 625941f331939e2706e4d45e |
def wingsTab(self): <NEW_LINE> <INDENT> tab_wings_label = QLabel("TRY OUR AMAZING WINGS") <NEW_LINE> tab_wings_label.setObjectName("Header") <NEW_LINE> description_box = QWidget() <NEW_LINE> description_box.setObjectName("ImageBorder") <NEW_LINE> wings_image_path = "images/wings.png" <NEW_LINE> wings_image = self.loadI... | Set up widgets and layouts to display information to the user about the page | 625941f30a366e3fb873ee1d |
def create_api( CONSUMER_KEY=CONSUMER_KEY, CONSUMER_SECRET_KEY=CONSUMER_SECRET_KEY, ACCESS_TOKEN=ACCESS_TOKEN, ACCESS_TOKEN_SECRET=ACCESS_TOKEN_SECRET, ): <NEW_LINE> <INDENT> auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET_KEY) <NEW_LINE> auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) <NEW_LINE> api ... | Authentication for the Twitter API
Credentials are based on @optombot account
Instructions on how to set up API authentication keys here:
- https://developer.twitter.com/ | 625941f3be383301e01b5a77 |
def test_get_cloud_db_image_product_list(self): <NEW_LINE> <INDENT> pass | Test case for get_cloud_db_image_product_list
get_cloud_db_image_product_list_request = ncloud_clouddb.GetCloudDBImageProductListRequest()
try:
api_response = self.api.get_cloud_db_image_product_list(get_cloud_db_image_product_list_request)
print(api_response)
except ApiE... | 625941f3ff9c53063f47c7ed |
def fit_words(self, frequencies): <NEW_LINE> <INDENT> return self.generate_from_frequencies(frequencies) | Create a word_cloud from words and frequencies.
Alias to generate_from_frequencies.
Parameters
----------
frequencies : dict from string to float
A contains words and associated frequency.
Returns
-------
self | 625941f33539df3088e2e949 |
def __del__(self): <NEW_LINE> <INDENT> self._free_context(self.pContext) | free the context returned by createContext. | 625941f32c8b7c6e89b35db9 |
def book_start(line): <NEW_LINE> <INDENT> return (line.startswith('PRELUDE') or line.startswith('FINALE') or line.startswith('BOOK ')) | Does this line start a book? | 625941f338b623060ff0b3ea |
def maybe_wraps(method): <NEW_LINE> <INDENT> def inner_wrapper(fn): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return wraps(method)(fn) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return fn <NEW_LINE> <DEDENT> <DEDENT> return inner_wrapper | Ignore wrapping exceptions. | 625941f3283ffb24f3c55ef7 |
def cumsum(item_list, initial=0): <NEW_LINE> <INDENT> def accum(acc, itm): <NEW_LINE> <INDENT> return op.iadd(acc, [acc[-1] + itm]) <NEW_LINE> <DEDENT> return reduce(accum, item_list, [initial])[1:] | python cumsum
Args:
item_list (list): list of numbers or items supporting addition
initial (value): initial zero value
Returns:
list: list of accumulated values
References:
stackoverflow.com/questions/9258602/elegant-pythonic-cumsum
CommandLine:
python -m utool.util_alg cumsum
Example:
>>> ... | 625941f3a4f1c619b28b0627 |
def mots_score_obtenus(self, nouvelles_positions): <NEW_LINE> <INDENT> positions_decodees = [Plateau.decode_position(p) for p in nouvelles_positions] <NEW_LINE> score_total = 0 <NEW_LINE> lignes, cols = zip(*positions_decodees) <NEW_LINE> mots = [] <NEW_LINE> for ligne in set(lignes): <NEW_LINE> <INDENT> lmots, score =... | *** Vous n'avez pas à coder cette méthode ***
Trouver les mots ajoutés et le score total obtenu lorsque le joueur vient juste d'ajouter des jetons aux
positions de la liste en argument.
:param nouvelles_positions: str list, liste de chaînes de caractères représentant les dernières positions où
des jetons ont ét... | 625941f33eb6a72ae02ecaec |
def from_dict(self, data): <NEW_LINE> <INDENT> self.name = data['name'] <NEW_LINE> if 'start_temperature' in data: <NEW_LINE> <INDENT> self.startTemperature = TemperatureType(json=data['start_temperature']) <NEW_LINE> <DEDENT> if 'end_temperature' in data: <NEW_LINE> <INDENT> self.endTemperature = TemperatureType(json=... | Convert a BeerJSON dict into values for this instance. | 625941f345492302aab5e8c7 |
def __init__(self, getter=None, setter=None, type=None, default=None, nick='', blurb='', flags=_gobject.PARAM_READWRITE, minimum=None, maximum=None): <NEW_LINE> <INDENT> self.name = None <NEW_LINE> if type is None: <NEW_LINE> <INDENT> type = object <NEW_LINE> <DEDENT> self.type = self._type_from_python(type) <NEW_LINE>... | @param getter: getter to get the value of the property
@type getter: callable
@param setter: setter to set the value of the property
@type setter: callable
@param type: type of property
@type type: type
@param default: default value
@param nick: short description
@type nick: string
@param blurb: l... | 625941f3c432627299f05248 |
def authenticate(): <NEW_LINE> <INDENT> return Response( 'Could not verify your access level for that URL.\nYou have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login required"'} ) | Sends a 401 response that enables basic auth | 625941f391af0d3eaac9c01a |
def find_ugly(data): <NEW_LINE> <INDENT> tests = { 'numeric': lambda x: x.isnumeric(), 'lower': lambda x: x.islower(), 'upper': lambda x: x.isupper(), 'length': lambda x: False, } <NEW_LINE> i = 0 <NEW_LINE> for c in data: <NEW_LINE> <INDENT> if 'length' in tests: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> if i == ... | Effective, though a little ugly-readable solution.
We construct a dict of tests and POP from it elements when first passed.
This way not only we solve the task with O(n) complexity, but also
avoid unneccessary checks of every test on every character. | 625941f3187af65679ca571d |
def calculateHandlen(hand): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for l in hand: <NEW_LINE> <INDENT> if hand[l] > 0: <NEW_LINE> <INDENT> count += hand[l] <NEW_LINE> <DEDENT> <DEDENT> return count | Returns the length (number of letters) in the current hand.
hand: dictionary (string-> int)
returns: integer | 625941f31b99ca400220b0b1 |
def get(self, endpoint, params=None): <NEW_LINE> <INDENT> url = '{}/{}.json'.format(self.api_url, endpoint) <NEW_LINE> logger.debug('GET: {} - Params: {}'.format(url, params)) <NEW_LINE> return self.api.get(url, params=params, auth=self.auth) | DHIS2 HTTP GET, returns requests.Response object | 625941f3a79ad161976cc743 |
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(CalibrateDistanceResponse, self).__init__(*args, **kwds) <NEW_LINE> if self.aov is None: <NEW_LINE> <INDENT> self.aov = 0. <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.aov = 0. | Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
aov
@param args: complete set of ... | 625941f3507cdc57c63072e7 |
def visit_dictorsetmaker(self, values, ctx): <NEW_LINE> <INDENT> raise NotImplementedError("dictorsetmaker") | dictorsetmaker: ( (test ':' test (comp_for | (',' test ':' test)* [','])) |
(test (comp_for | (',' test)* [','])) ) | 625941f326068e7796caf2e6 |
def add_all_untracked(self): <NEW_LINE> <INDENT> self.repo.index.add(self.repo.untracked_files) <NEW_LINE> modified = [] <NEW_LINE> deleted = [] <NEW_LINE> for i in self.repo.index.diff(None): <NEW_LINE> <INDENT> if os.path.exists(self.localdir+'/'+i.a_path): <NEW_LINE> <INDENT> modified.append(i.a_path) <NEW_LINE> <DE... | Commit all untracked and modified files. This method shouldn't
generate any exceptions as we don't allow unexpected
operations to be invoked. | 625941f3462c4b4f79d1dccd |
def _create_widget_layer(self): <NEW_LINE> <INDENT> ux_start, ux_end = self.pos.x0, self.pos.x0 + self.pos.width <NEW_LINE> pad = self._padding * (ux_end - ux_start) <NEW_LINE> self._widget_axis = self.figure.add_axes([self.pos.x0 + pad, self.pos.y0, self.pos.width - 2*pad, self.pos.height]) <NEW_LINE> self._widget_axi... | Add the `matplotlib.widget.Slider` over the UX axis and make transparent. | 625941f3ec188e330fd5ad8f |
def update(self, data, length=None): <NEW_LINE> <INDENT> if self.digest_finalized: <NEW_LINE> <INDENT> raise DigestError("No updates allowed") <NEW_LINE> <DEDENT> if not isinstance(data, bintype): <NEW_LINE> <INDENT> raise TypeError("A byte string is expected") <NEW_LINE> <DEDENT> if length is None: <NEW_LINE> <INDENT>... | Hashes given byte string
@param data - string to hash
@param length - if not specifed, entire string is hashed,
otherwise only first length bytes | 625941f3a8ecb033257d36c8 |
def load(self, instance, request, data): <NEW_LINE> <INDENT> values = data.pop(self.name, []) <NEW_LINE> yield from self.from_field_values(instance, request, values) | Find the appropriate key(s) and their values and call
:meth:`from_field_values` on the values. Yields any errors encountered.
The *data* dictionaries keys must be rebased such that they can be
indexed by using the field :attr:`name`. | 625941f36aa9bd52df0373a5 |
def _set_index(x, index): <NEW_LINE> <INDENT> if index is None: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> if hasattr(x, "index"): <NEW_LINE> <INDENT> x.index = index <NEW_LINE> <DEDENT> return x | set the index attribute of something it is possible
if index is None, or x doesn't have an index attribute it won't do anything | 625941f3f8510a7c17cf9cff |
def test_geospatial_query_point_incorrect_param_helper_method(self): <NEW_LINE> <INDENT> query = TestGeospatial.client.query("test", "demo") <NEW_LINE> try: <NEW_LINE> <INDENT> query.where(p.geo_contains_point("loc_polygon", -121.7, 37)) <NEW_LINE> <DEDENT> except e.ParamError as exception: <NEW_LINE> <INDENT> assert e... | Perform a positive geospatial query for a point with incorrect
params for helper method | 625941f3adb09d7d5db6cd89 |
def check_atomic_group_create_job(synch_count, host_objects, metahost_objects, dependencies, atomic_group, labels_by_name): <NEW_LINE> <INDENT> minimum_required = synch_count or 1 <NEW_LINE> if (host_objects and not metahost_objects and len(host_objects) < minimum_required): <NEW_LINE> <INDENT> raise model_logic.Valida... | Attempt to reject create_job requests with an atomic group that
will be impossible to schedule. The checks are not perfect but
should catch the most obvious issues.
:param synch_count - The job's minimum synch count.
:param host_objects - A list of models.Host instances.
:param metahost_objects - A list of models.Lab... | 625941f3d18da76e23532adc |
def build_word_list(filename): <NEW_LINE> <INDENT> infile = open(filename, "r") <NEW_LINE> word_set = set() <NEW_LINE> for line in infile: <NEW_LINE> <INDENT> word_list = line.split() <NEW_LINE> for word in word_list: <NEW_LINE> <INDENT> word = word.strip(string.punctuation).lower() <NEW_LINE> if word != '': <NEW_LINE>... | (str) -> list of str
Return a list of all the words in the specified file,
sorted in ascending order.
>>> word_list = build_word_list('sons_of_martha.txt')
>>> word_list
>>> len(word_list) # How many different words are in the file? | 625941f382261d6c526abaa7 |
def cyclicEt(self, size, base=0, noise=2, amp=10, period=25, phase = 0, noise_type = 'gauss'): <NEW_LINE> <INDENT> if noise_type == 'gauss': <NEW_LINE> <INDENT> series = normal(base,noise,size) <NEW_LINE> <DEDENT> elif noise_type == 'uni' : <NEW_LINE> <INDENT> series = uniform(0-noise,noise,size) + base... | Extend Time series by size using cyclic control chart pattern | 625941f3b7558d58953c5504 |
def draw_bounding_boxes(self, image: torch.Tensor, boxes: torch.Tensor, labels: Optional[List[str]] = None, colors: Optional[List[Union[str, Tuple[int, int, int]]]] = None, fill: Optional[bool] = False, width: int = 1, font: Optional[str] = None, font_size: int = 10 ) -> torch.Tensor: <NEW_LINE> <INDENT> if not isinsta... | Draws bounding boxes on given image.
The values of the input image should be uint8 between 0 and 255.
If filled, Resulting Tensor should be saved as PNG image.
Args:
image (Tensor): Tensor of shape (C x H x W)
boxes (Tensor): Tensor of size (N, 4) containing bounding boxes in (xmin, ymin, xmax, ymax) format. No... | 625941f3566aa707497f4b5e |
def _process_image_files(thread_index, ranges, name, images, decoder, vocab, num_shards): <NEW_LINE> <INDENT> num_threads = len(ranges) <NEW_LINE> assert not num_shards % num_threads <NEW_LINE> num_shards_per_batch = int(num_shards / num_threads) <NEW_LINE> shard_ranges = np.linspace(ranges[thread_index][0], ranges[thr... | Processes and saves a subset of images as TFRecord files in one thread.
Args:
thread_index: Integer thread identifier within [0, len(ranges)].
ranges: A list of pairs of integers specifying the ranges of the dataset to
process in parallel.
name: Unique identifier specifying the dataset.
images: List of Ima... | 625941f37d847024c06be8bf |
def parse_tuple(self,t): <NEW_LINE> <INDENT> if self._true_dist: <NEW_LINE> <INDENT> self._parse_tuple_dist(t) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._parse_tuple_edge_type(t) | Parse one tupel (nb_vehi, manager_stop). Update corresponding self attribute
:param t: the corresponding tuple. | 625941f38a349b6b435e8770 |
@app.before_request <NEW_LINE> def csrf_protection(): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> token = session.pop('csrf_token', None) <NEW_LINE> if not token or token != request.form.get('csrf_token'): <NEW_LINE> <INDENT> return render_template('errors/403.html'), 403 | Handling the CSRF protection when user send the post request | 625941f3b7558d58953c5505 |
def noslash(self, bot, update): <NEW_LINE> <INDENT> msg = update.message.text <NEW_LINE> if msg == "quit": <NEW_LINE> <INDENT> self.quit(bot, update) <NEW_LINE> <DEDENT> elif msg == "restart": <NEW_LINE> <INDENT> self.restart(bot, update) <NEW_LINE> <DEDENT> elif msg == "reloadconf" or msg == "reconf": <NEW_LINE> <INDE... | Use strings or words instead of commands | 625941f3956e5f7376d71469 |
def mctFromLeafValues(self, arr): <NEW_LINE> <INDENT> n = len(arr) <NEW_LINE> m = [[float("inf") for i in range(n)] for i in range(n)] <NEW_LINE> """----------------- Preprocessing(elements at diagnol = 0)----------------------""" <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> m[i][i] = 0 <NEW_LINE> <DEDENT> for l i... | :type arr: List[int]
:rtype: int | 625941f3099cdd3c635f1256 |
def euler28(n=1001): <NEW_LINE> <INDENT> return 1 + sum(16 * j * j + 36 * j + 24 for j in range(n // 2)) | Solution for problem 28. | 625941f35510c4643540f9d2 |
def sendjson(self, method, urlpath, obj): <NEW_LINE> <INDENT> headers = {'Content-Type': 'application/json'} <NEW_LINE> data = jsonutils.dumps(obj, indent=2) if obj else None <NEW_LINE> url = '/'.join([self.url, urlpath]) <NEW_LINE> LOG.debug("Sending METHOD (%(method)s) URL (%(url)s) JSON (%(obj)s)", {'method': method... | Send json to the OpenDaylight controller. | 625941f3498bea3a759ba0ab |
def path_parser(path: str, args: str) -> list: <NEW_LINE> <INDENT> path = format_path(path) <NEW_LINE> path_list = path.split('/') <NEW_LINE> if is_absolute_path(args): <NEW_LINE> <INDENT> return args <NEW_LINE> <DEDENT> if args == '/': <NEW_LINE> <INDENT> return path_list[0] <NEW_LINE> <DEDENT> if args[:2] == '..': <N... | 传入当前路径和参数
如果args是绝对路径则返回args
如果args是相对路径则返回path与args拼接后的路径 | 625941f34d74a7450ccd47c3 |
def finish_initializing(self, builder): <NEW_LINE> <INDENT> super(AboutTilegenDialog, self).finish_initializing(builder) | Set up the about dialog | 625941f399cbb53fe67931e2 |
def _fill_statistics_table_context(self, context, queryset_filter): <NEW_LINE> <INDENT> links_added_removed = LinkAggregate.objects.filter(queryset_filter).aggregate( links_added=Sum("total_links_added"), links_removed=Sum("total_links_removed"), links_diff=Sum("total_links_added") - Sum("total_links_removed"), ) <NEW_... | This function adds the Statistics table information to the context
dictionary to display in OrganisationDetailView
Parameters
----------
context : dict
The context dictionary that the function will be adding information to
queryset_filter: Q
If the information is filtered, this set of filters will filter it.
... | 625941f3ab23a570cc250786 |
def validate_scale_count(value, _): <NEW_LINE> <INDENT> if value is not None and value < 3: <NEW_LINE> <INDENT> return 'need at least 3 scaling factors.' | Validate the `scale_count` input. | 625941f376e4537e8c351c76 |
def test_ParametricChain(self): <NEW_LINE> <INDENT> wmsClient = WMSClient() <NEW_LINE> jobStateUpdate = JobStateUpdateClient() <NEW_LINE> jobMonitor = JobMonitoringClient() <NEW_LINE> job = parametricJob() <NEW_LINE> jobDescription = createFile(job) <NEW_LINE> res = wmsClient.submitJob(job._toJDL(xmlFile=jobDescription... | This test will submit a parametric job which should generate 3 actual jobs | 625941f3a4f1c619b28b0628 |
def update(self, *args, **kwargs): <NEW_LINE> <INDENT> if len(args) > 1: <NEW_LINE> <INDENT> raise TypeError("update expected at most 1 arguments, got %d" % len(args)) <NEW_LINE> <DEDENT> if args: <NEW_LINE> <INDENT> otherDict = args[0] <NEW_LINE> if isinstance(otherDict, MultiValueDict): <NEW_LINE> <INDENT> for key, v... | update() extends rather than replaces existing key lists.
Also accepts keyword args. | 625941f38c3a8732951589c1 |
def no_warn_sysmsg(fn): <NEW_LINE> <INDENT> @functools.wraps(fn) <NEW_LINE> def inner(*args, **kwargs): <NEW_LINE> <INDENT> context.no_warn_sysmsg = True <NEW_LINE> return fn(*args, **kwargs) <NEW_LINE> <DEDENT> return inner | Suppress system message warnings on login | 625941f3a8370b7717052e9b |
def get_toppredictors(self, max_depth=None): <NEW_LINE> <INDENT> if self._df_test is None: <NEW_LINE> <INDENT> raise RuntimeError('MyDecisionTreeClassifier: please train the ' 'model first') <NEW_LINE> <DEDENT> elif max_depth is None: <NEW_LINE> <INDENT> max_depth = self.get_bestparameter() <NEW_LINE> <DEDENT> tree = D... | Return the top predictors, model must be first trained
Parameters
----------
max_depth : int, default=None
The maximum depth of the tree. If None, then nodes are expanded
until all leaves are pure or until all leaves contain less than
min_samples_split samples.
Returns
-------
get_toppredictors : pandas.D... | 625941f3ff9c53063f47c7ee |
def readRoutes(graph, routingXml, host, logger, name, timeout, readElements): <NEW_LINE> <INDENT> if not routingXml: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if routingXml: <NEW_LINE> <INDENT> logger.debug("Reading all Routes from XML for host {0}.".format(host.getID())) <NEW_LINE> for routeXml in routingXml: <NE... | Load all routes of a host. The routes will be added to the host automatically.
:param graph: Data Interface object for this scanner
:type graph: :class: `Graph`
:param routingXml: Part of the parsed XML containing the routes.
:type routingXml: list
:param host: The host that contains the read routes.
:type host: ins... | 625941f324f1403a9260115f |
def recv_from(self, size, addr): <NEW_LINE> <INDENT> if not self.is_ready(addr): <NEW_LINE> <INDENT> self.not_found_address() <NEW_LINE> <DEDENT> return self._recv(size=size, addr=addr, timeout=self.get_timeout()) | Receive a data from slave device safely with checking address
routine.
:return bytes: A buffer of the bytes received. | 625941f399cbb53fe67931e3 |
def create_user_table(dynamo_interface, logger=None): <NEW_LINE> <INDENT> throughput = { 'read' : 2, 'write' : 2 } <NEW_LINE> table = dynamo_interface.create_table( 'users', 'username', 'password', throughput) <NEW_LINE> time.sleep(10) <NEW_LINE> users = seed_user_table(table) <NEW_LINE> if logger: <NEW_LINE> <INDENT> ... | Takes a boto.dynamodb.conn object and creates
a users table on it.
We want to do this programatically so we can easily
create this table across different domain and realms | 625941f360cbc95b062c6b42 |
def get_weather_from_provider(lat: str, lon: str) -> str: <NEW_LINE> <INDENT> url = _build_url(lat=lat, lon=lon) <NEW_LINE> response = requests.get(url) <NEW_LINE> status_code = response.status_code <NEW_LINE> if 200 <= status_code < 300: <NEW_LINE> <INDENT> return response.text <NEW_LINE> <DEDENT> else: <NEW_LINE> <IN... | HTTP request to DarkSky API to get weather forecast for the given location based
on the latitude and longitude args
Args:
lat (str): latitude of the location
lon (str): longitude of the location
Returns:
JSON response object: weather forecast of the location | 625941f316aa5153ce362a77 |
def subscribers_insert(subreddit_name, new_data): <NEW_LINE> <INDENT> subreddit_name = subreddit_name.lower() <NEW_LINE> CURSOR_STATS.execute( "SELECT * FROM subreddit_subscribers_new WHERE subreddit = ?", (subreddit_name,) ) <NEW_LINE> result = CURSOR_STATS.fetchone() <NEW_LINE> if result is None: <NEW_LINE> <INDENT> ... | This function merges subscriber data in a dictionary passed to
it with the already saved information, or creates a new entry by
the subreddit's name.
It's designed to be able to accept more than one date at a time
and be able to save information in fewer writes to the database.
This is integrated into `subreddit_subsc... | 625941f35fcc89381b1e1cc3 |
def __init__(self): <NEW_LINE> <INDENT> self.args = self.parse_cli_args() <NEW_LINE> self.settings = self.read_settings() <NEW_LINE> self.connect() <NEW_LINE> self.build_inventory() <NEW_LINE> if self.args.host: <NEW_LINE> <INDENT> data_to_print = self.json_format_dict(self.inventory['_meta']['hostvars'][self.args.host... | Main execution path | 625941f32eb69b55b151ceb7 |
def get_index(self): <NEW_LINE> <INDENT> if self.__team == Game.red_team: <NEW_LINE> <INDENT> return self.__game.get_index_red(self) <NEW_LINE> <DEDENT> elif self.__team == Game.blue_team: <NEW_LINE> <INDENT> return self.__game.get_index_blue(self) | Returns the index of the player in his team's list of players. | 625941f345492302aab5e8c8 |
def _qemuVMChangedSlot(self): <NEW_LINE> <INDENT> item = self.uiQemuVMsTreeWidget.currentItem() <NEW_LINE> if item: <NEW_LINE> <INDENT> self.uiDeleteQemuVMPushButton.setEnabled(True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.uiDeleteQemuVMPushButton.setEnabled(False) | Enables the use of the delete button. | 625941f3442bda511e8bea0e |
def Collection_change_prices(l: list) -> list: <NEW_LINE> <INDENT> result = [] <NEW_LINE> for obj in l: <NEW_LINE> <INDENT> result.append(Restaurant_raise_prices(obj)) <NEW_LINE> <DEDENT> return result | Takes the collection and raises the prize of every dish by 2.50 | 625941f31f5feb6acb0c5148 |
def upload(access_token, metadata, files, publish=False, request_factory=None): <NEW_LINE> <INDENT> client = DepositClient( access_token, ssl_verify=False, request_factory=request_factory, ) <NEW_LINE> r = client.post('invenio_deposit_rest.depid_list', data={}) <NEW_LINE> if r.status_code != 201: <NEW_LINE> <INDENT> ra... | Deposit Upload. | 625941f38a349b6b435e8771 |
def _merge_outputs_by_key(keys_and_outputs, outputs_dtype): <NEW_LINE> <INDENT> num_outputs = len(outputs_dtype) <NEW_LINE> sorted_keys_and_outputs = sorted(keys_and_outputs, key=lambda x: x[0]) <NEW_LINE> key = [] <NEW_LINE> outputs = [] <NEW_LINE> for k, o in sorted_keys_and_outputs: <NEW_LINE> <INDENT> key.append(k)... | Merge outputs of analyzers per key into a single output.
Takes a list of elements of the form (key, [output0, ..., output{N-1}]) and
returns a list of ndarrays of the form [keys, outputs0, ..., outputs[{N-1}]]
where keys is formed by stacking the values of `key` from the list and
similarly outputs{k} is formed by stac... | 625941f3091ae35668667552 |
def get_engine(self): <NEW_LINE> <INDENT> return self.engine | Return the engine for use in querying. | 625941f3596a89723608a0b6 |
def __ifloordiv__(self, other): <NEW_LINE> <INDENT> oth = sanitize_units_mul(self, other) <NEW_LINE> np.floor_divide(self, oth, out=self) <NEW_LINE> return self | See __div__. | 625941f3b57a9660fec33e8b |
def elw_trade_performance_per_investor(self): <NEW_LINE> <INDENT> if self.search_type == "일별추이": <NEW_LINE> <INDENT> bld = "dbms/MDC/STAT/standard/MDCSTAT08702" <NEW_LINE> <DEDENT> elif self.search_type == "상세보기": <NEW_LINE> <INDENT> bld = "dbms/MDC/STAT/standard/MDCSTAT08703" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDE... | 투자자별 거래실적[13305] | 625941f34527f215b584ca50 |
def adam(x, dx, config=None): <NEW_LINE> <INDENT> if config is None: config = {} <NEW_LINE> config.setdefault('learning_rate', 1e-3) <NEW_LINE> config.setdefault('beta1', 0.9) <NEW_LINE> config.setdefault('beta2', 0.999) <NEW_LINE> config.setdefault('epsilon', 1e-8) <NEW_LINE> config.setdefault('m', np.zeros_like(x)) <... | Uses the Adam update rule, which incorporates moving averages of both the
gradient and its square and a bias correction term.
config format:
- learning_rate: Scalar learning rate.
- beta1: Decay rate for moving average of first moment of gradient.
- beta2: Decay rate for moving average of second moment of gradient.
- ... | 625941f310dbd63aa1bd31a0 |
def Transmit(self, msg): <NEW_LINE> <INDENT> self.Message.append(msg) | Cette fonction permet à mes camarades d'envoyer du contenu tel qu'une chaine de caractères (un tuple, une image, etc...) au client.
Par Joris Placette | 625941f3498bea3a759ba0ac |
def _execute(self): <NEW_LINE> <INDENT> if self._check_params(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._read_configs() <NEW_LINE> processing_raw_data(self.excel_matrix[1:], PROCESSING_DATA_FILE) <NEW_LINE> self._set_status_var_text(RAW_DATA_PROCESSED_INFO) <NEW_LINE> generate_info_file(PROCESSING_DATA_FILE,... | Do validation and execution | 625941f3091ae35668667553 |
@pytest.fixture() <NEW_LINE> def sample_performance_results(): <NEW_LINE> <INDENT> return get_sample_json("performance_results.json") | Return sample performance results. | 625941f3be7bc26dc91cdbf3 |
def setup_table(sc, sqlContext, reviews_filename): <NEW_LINE> <INDENT> df = sqlContext.read.csv(reviews_filename, header=True, inferSchema=True) <NEW_LINE> df = df.dropna(how='any', thresh=None, subset=None) <NEW_LINE> df = df.drop_duplicates() <NEW_LINE> df = df.filter(df.Description != "SIMPLE") <NEW_LINE> sqlContext... | Args:
sc: The Spark Context
sqlContext: The Spark SQL context
reviews_filename: Filename of the Amazon reviews file to use, where each line represents a review
Parse the reviews file and register it as a table in Spark SQL in this function | 625941f3cad5886f8bd275d7 |
def __create_find_all(self, result, rrsets, flags): <NEW_LINE> <INDENT> def new_find_all(name, fflags): <NEW_LINE> <INDENT> return (result, rrsets, flags) <NEW_LINE> <DEDENT> self.find_all = new_find_all | Overwrites the local find() method with a method that returns
the tuple (result, rrsets, flags) | 625941f3d99f1b3c44c67b82 |
@front.route('/') <NEW_LINE> @front.route('/home') <NEW_LINE> def home(n=1): <NEW_LINE> <INDENT> return render_template( 'login.html', title='Home Page', year=datetime.now().year, ) | Renders the home page. | 625941f3e5267d203edce294 |
def go_to_renyuanguanxiweihu(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> el1 = driver.find_element_by_xpath("//a[text()='系统设置']") <NEW_LINE> el2 = driver.fin... | 人员关系维护 | 625941f37c178a314d6efa69 |
def get_questions_hour_mapping(): <NEW_LINE> <INDENT> posts = pd.read_csv('posts.csv', delimiter='|', usecols= ['Id', 'CreationDate', 'PostTypeId']) <NEW_LINE> questions = posts.loc[posts['PostTypeId'] == 1] <NEW_LINE> questions['CreationDate'] = questions['CreationDate'].apply(lambda x: datetime.strptime(x, "%Y-%m-%dT... | - Reads questions from posts file and return mapping from question to its created hour
- This map consists of questions only from 2016. This is done as user availability feature
is based on user's activity in 2016 | 625941f37d43ff24873a32a4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.