code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_authenticate_user_returns_endpoint_list(self): <NEW_LINE> <INDENT> result = self.successResultOf(self.st.authenticate_tenant('1111111')) <NEW_LINE> self.assertEqual(result, ('auth-token', fake_service_catalog)) | authenticate_tenant returns the impersonation token and the endpoint
list. | 625941c28da39b475bd64f14 |
def remove_browser_layer(name): <NEW_LINE> <INDENT> existing = component.queryUtility(ILocalBrowserLayerType, name=name) <NEW_LINE> if existing is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> site_manager = component.getSiteManager() <NEW_LINE> site_manager.unregisterUtility(component=existing, provided=ILocalB... | this will remove browser layer even if the addon has been removed
from the system.
Created and used to remove collective.groupdashboard
symptom: can't apply portlets import step ->
2013-01-23 12:15:51 ERROR Zope.SiteErrorLog 1358939751.450.337074106184 ...
Traceback (innermost last):
Module ZPublisher.Publish, line 1... | 625941c2d58c6744b4257c03 |
def dist(self): <NEW_LINE> <INDENT> return list(map(lambda x: x / float(100), self.distance)) | Returns the distance from the previous point in meters. | 625941c23c8af77a43ae3741 |
def __new__(cls, subset, superset): <NEW_LINE> <INDENT> if len(subset) > len(superset): <NEW_LINE> <INDENT> raise ValueError('Invalid arguments have been provided. The superset must be larger than the subset.') <NEW_LINE> <DEDENT> for elem in subset: <NEW_LINE> <INDENT> if elem not in superset: <NEW_LINE> <INDENT> rais... | Default constructor.
It takes the subset and its superset as its parameters.
Examples
========
>>> from sympy.combinatorics.subsets import Subset
>>> a = Subset(['c','d'], ['a','b','c','d'])
>>> a.subset
['c', 'd']
>>> a.superset
['a', 'b', 'c', 'd']
>>> a.size
2 | 625941c2596a897236089a66 |
def setRange(self, x1, y1, x2, y2): <NEW_LINE> <INDENT> self.x1 = float(x1) <NEW_LINE> self.y1 = float(y1) <NEW_LINE> self.x2 = float(x2) <NEW_LINE> self.y2 = float(y2) <NEW_LINE> self.w = self.x2 - self.x1 <NEW_LINE> self.h = self.y2 - self.y1 <NEW_LINE> self.xmult = self.sw / self.w <NEW_LINE> self.ymult = self.sh / ... | Set the virtual coordinate range. | 625941c207f4c71912b11424 |
def setTimestampData(inv, alltimestamps): <NEW_LINE> <INDENT> totalcons = []; totalgen = []; totalID = [] <NEW_LINE> for i in range(len(alltimestamps)): <NEW_LINE> <INDENT> timestamp = alltimestamps[i] <NEW_LINE> cons = []; gen = []; ID = [] <NEW_LINE> for j in range(len(inv)): <NEW_LINE> <INDENT> for k in range(len(in... | Function to set the consumption and generation associated with each timestamp, for all the apartments.
If an apartment has a value for a given timestamp, it will be added in an array representing that timestamp. | 625941c21f037a2d8b9461a1 |
def __deserialize(self, data, klass): <NEW_LINE> <INDENT> if data is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if type(klass) == str: <NEW_LINE> <INDENT> if klass.startswith('list['): <NEW_LINE> <INDENT> sub_kls = re.match('list\[(.*)\]', klass).group(1) <NEW_LINE> return [self.__deserialize(sub_data, s... | Deserializes dict, list, str into an object.
:param data: dict, list or str.
:param klass: class literal, or string of class name.
:return: object. | 625941c2c4546d3d9de729d5 |
def reboot(self, names): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> pmap = self.map_providers_parallel() <NEW_LINE> acts = {} <NEW_LINE> for prov, nodes in six.iteritems(pmap): <NEW_LINE> <INDENT> acts[prov] = [] <NEW_LINE> for node in nodes: <NEW_LINE> <INDENT> if node in names: <NEW_LINE> <INDENT> acts[prov].append(node... | Reboot the named VMs | 625941c2283ffb24f3c558a6 |
def test_mod_admin_can_admin(self): <NEW_LINE> <INDENT> self.dbauth.user_create('charlie', 'foo', False) <NEW_LINE> self.dbauth.user_set_admin('charlie', True) <NEW_LINE> flask.request = FakeAuthRequest('charlie', 'foo') <NEW_LINE> local.auth = self.dbauth.User.query.filter_by(label='charlie').one() <NEW_LINE> self.dba... | Verify that a newly promoted admin can actually do admin stuff. | 625941c2e5267d203edcdc42 |
def _place_ships_based_on_stat_model(self): <NEW_LINE> <INDENT> self.reverse_probs() <NEW_LINE> for val in sorted(self._d.keys()): <NEW_LINE> <INDENT> for root in self._d[val]: <NEW_LINE> <INDENT> for ship in filter(lambda s: s not in self._placements, Ship.SHORT_NAMES): <NEW_LINE> <INDENT> if self.try_place_max_prob(r... | Place ships based on the stat model alone.
The problem with this method is it is non-stochastic - i.e. will generate
the same placements over and over again. | 625941c296565a6dacc8f66f |
def single_worker_inference(infer_model, ckpt, inference_input_file, inference_output_file, hparams): <NEW_LINE> <INDENT> output_infer = inference_output_file <NEW_LINE> infer_data = load_data(inference_input_file, hparams) <NEW_LINE> print ("Batch size type:", type(hparams.infer_batch_size)) <NEW_LINE> with tf.Session... | Inference with a single worker. | 625941c2b57a9660fec33825 |
def __init__(self, n_layer=12, growth_rate=12, n_class=10, dropout_ratio=0.2, in_ch=16, block=3): <NEW_LINE> <INDENT> in_chs = [in_ch + n_layer * growth_rate * i for i in moves.range(block + 1)] <NEW_LINE> super(DenseNet, self).__init__() <NEW_LINE> self.add_link( 'conv1', L.Convolution2D(3, in_ch, 3, 1, 1, wscale=np.s... | DenseNet definition.
Args:
n_layer: Number of convolution layers in one dense block.
If n_layer=12, the network is made out of 40 (12*3+4) layers.
If n_layer=32, the network is made out of 100 (32*3+4) layers.
growth_rate: Number of output feature maps of each convolution
layer in dense... | 625941c28da39b475bd64f15 |
def candidate_generation(f_y, f_y_size, symbol_size, ngram2mid, mid2index, question): <NEW_LINE> <INDENT> candidates = list() <NEW_LINE> ngram_list = ngram_generation(question) <NEW_LINE> ngram_list = ngram_clean(ngram_list, ngram2mid.keys()) <NEW_LINE> ngram_indexes = ngram_vectorisation(ngram2mid, mid2index, ngram_li... | Note:
generate candidates with ngrams
Args:
f_y: knowlege base matrice
f_y_size:
ngram2mid: map ngram to id
mid2index: map id to index
question: in natural language
Returns:
list of candidates | 625941c297e22403b379cf3c |
def upload_dsl_resources(dsl_resources, temp_dir, fabric_env, retries, wait_interval, timeout): <NEW_LINE> <INDENT> logger = get_logger() <NEW_LINE> remote_plugins_folder = '/opt/manager/resources/' <NEW_LINE> @retry(wait_fixed=wait_interval * 1000, stop_func=partial(_stop_retries, retries, wait_interval), retry_on_exc... | Uploads dsl resources to the manager.
:param dsl_resources: all of the dsl_resources.
:param temp_dir: the dir to push the resources to.
:param fabric_env: fabric env in order to upload the dsl_resources.
:param retries: number of retries per resource download.
:param wait_interval: interval between download retries.
... | 625941c28e05c05ec3eea316 |
def __init__(self, enabled, password): <NEW_LINE> <INDENT> ReqElement.__init__(self, 'LocalAdmin') <NEW_LINE> self.setAttribute('enabled', enabled) <NEW_LINE> self.setAttribute('password', password) | Create a LocalAdmin element.
:param password: The local admin password.
:param enabled: Switches local admin on or off. Switching off local
admin on a standalone server is rejected. | 625941c263f4b57ef00010c1 |
def update(self, instance, validated_data): <NEW_LINE> <INDENT> password = validated_data.pop("password", None) <NEW_LINE> user = super().update(instance, validated_data) <NEW_LINE> if password: <NEW_LINE> <INDENT> user.set_password(password) <NEW_LINE> user.save() <NEW_LINE> <DEDENT> return user | Update a user, setting the PWD correctly and return it | 625941c20c0af96317bb818b |
def __generate(self, kwargs): <NEW_LINE> <INDENT> result = [] <NEW_LINE> size = kwargs["count"] <NEW_LINE> prefix = kwargs["prefix"] <NEW_LINE> suffix = kwargs["suffix"] <NEW_LINE> protocol = kwargs["protocol"] <NEW_LINE> tld = kwargs["tld"] <NEW_LINE> workers = kwargs["workers"] <NEW_LINE> dry_run = kwargs["dry_run"] ... | Handles the operations -g, --generate and --dry-run
Parameters
----------
kwargs: dict
The dictionary parameter containing the attributes:
* count - The number of urls to generate
* prefix - The url prefix
* suffix - The url suffix
* protocol - The protocol
* tld - The top level dom... | 625941c282261d6c526ab440 |
def convert_line_to_html(self, empty): <NEW_LINE> <INDENT> line = [] <NEW_LINE> do_highlight = self.curr_row in self.hl_lines <NEW_LINE> while self.end <= self.size: <NEW_LINE> <INDENT> scope_name = self.view.scope_name(self.pt) <NEW_LINE> while self.view.scope_name(self.end) == scope_name and self.end < self.size: <NE... | Convert the line to its HTML representation. | 625941c266673b3332b92034 |
def json_dumps(data, **kwargs): <NEW_LINE> <INDENT> return json.dumps(data, cls=NumpyAwareJSONEncoder, allow_nan=False) | Uses json.dumps to serialize data into JSON. In addition to the standard
json.dumps function, we're also using the NumpyAwareJSONEncoder to handle
numpy arrays and the `ignore_nan` parameter by default to handle np.nan values. | 625941c28e71fb1e9831d74d |
def fail(error_message): <NEW_LINE> <INDENT> print(error_message) <NEW_LINE> exit(1) | Print error message and exit(1)
:param error_message: message to print | 625941c2dd821e528d63b14e |
@iterate_jit(nopython=True) <NEW_LINE> def ExpandIncome(e00200, pencon_p, pencon_s, e00300, e00400, e00600, e00700, e00800, e00900, e01100, e01200, e01400, e01500, e02000, e02100, p22250, p23250, e03500, cmbtp, ptax_was, benefit_value_total, ubi, expanded_income): <NEW_LINE> <INDENT> expanded_income = ( e00200 + pencon... | Calculates expanded_income from component income types. | 625941c294891a1f4081ba4c |
def get_final_application_state(self): <NEW_LINE> <INDENT> return self.to_application_state(self.final_state()) | Get final application state. | 625941c23cc13d1c6d3c731e |
def letterbox_image(image, size): <NEW_LINE> <INDENT> image_w, image_h = image.size <NEW_LINE> w, h = size <NEW_LINE> new_w = int(image_w * min(w*1.0/image_w, h*1.0/image_h)) <NEW_LINE> new_h = int(image_h * min(w*1.0/image_w, h*1.0/image_h)) <NEW_LINE> resized_image = image.resize((new_w,new_h), Image.BICUBIC) <NEW_LI... | resize image with unchanged aspect ratio using padding
Reference: https://github.com/qqwweee/keras-yolo3/blob/master/yolo3/utils.py | 625941c20c0af96317bb818c |
def custom_course_context(self): <NEW_LINE> <INDENT> return LTICourseContext.objects.get( enable=True, uuid=self.lti_params['custom_course_context']) | Returns the custom LTICourseContext id as provided by LTI
throws: KeyError or ValueError or LTICourseContext.DoesNotExist
:return: context -- the LTICourseContext instance or None | 625941c22c8b7c6e89b35765 |
def get_calendar(self, start: str = None, end: str = None) -> Calendars: <NEW_LINE> <INDENT> params = {} <NEW_LINE> if start is not None: <NEW_LINE> <INDENT> params['start'] = start <NEW_LINE> <DEDENT> if end is not None: <NEW_LINE> <INDENT> params['end'] = end <NEW_LINE> <DEDENT> resp = self.get('/calendar', data=para... | :param start: isoformat date string eg '2006-01-02T15:04:05Z' or
'2006-01-02'
:param end: isoformat date string | 625941c2a8370b7717052844 |
def harvey(self, hsig, htau, hexp): <NEW_LINE> <INDENT> return hsig / (1.0 + (self.f/htau)**hexp) | Extended Harvey profile to deal with super nyquist cases | 625941c2f548e778e58cd520 |
def newPage(self): <NEW_LINE> <INDENT> doc = self.tabs.currentWidget() <NEW_LINE> if doc is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> doc.newPage() | Append an empty page to the current document. | 625941c2851cf427c661a4b5 |
def get_trend_resolution(self, resolution=None): <NEW_LINE> <INDENT> if not resolution: <NEW_LINE> <INDENT> resolution = Error.Resolution.FIVE_MINUTE <NEW_LINE> <DEDENT> return self._client.get( "projects/{}/errors/{}/trend?resolution={}".format( self.project.id, self.id, resolution ) ) | get trend buckets for this error based on time resolution | 625941c24d74a7450ccd4167 |
def get_dynamic_property_mor(session, mor_ref, attribute): <NEW_LINE> <INDENT> return session._call_method(vim_util, "get_dynamic_property", mor_ref, mor_ref._type, attribute) | Get the value of an attribute for a given managed object. | 625941c2656771135c3eb810 |
def testPdfBadParser(self): <NEW_LINE> <INDENT> self.assertRaises(multivio.parser.ParserError.InvalidDocument, PdfParser, mets_file_name, "file://%s" % mets_file_name, mets_file_name) | Check PdfParser instance with a bad file. | 625941c299fddb7c1c9de335 |
def setup_logger(log_filename): <NEW_LINE> <INDENT> format_str = '%(asctime)s@%(name)s %(levelname)s # %(message)s' <NEW_LINE> basicConfig(filename=log_filename, level=DEBUG, format=format_str) <NEW_LINE> stream_handler = StreamHandler() <NEW_LINE> stream_handler.setFormatter(Formatter(format_str)) <NEW_LINE> getLogger... | setup a logger that logs lol
:arg log_filename : path to logfile | 625941c2167d2b6e31218b3a |
def create(self): <NEW_LINE> <INDENT> begin_id = 10000 <NEW_LINE> auto_increment_file = "%s/increment_id" % os.path.dirname(Account.db_path) <NEW_LINE> if os.path.exists(auto_increment_file): <NEW_LINE> <INDENT> line = Account.db.load_pickle_data(auto_increment_file) <NEW_LINE> auto_increment_id = int(line) + 1 <NEW_LI... | 创建新账号
:return: 账户实例 | 625941c2cc40096d615958f5 |
def run_from_cli(self, should_update, xml_path, tag, directory, destination, filename, extension): <NEW_LINE> <INDENT> self.git = Git(path=self.cwd, cpu_count=self.cpu_count) <NEW_LINE> if should_update: <NEW_LINE> <INDENT> self.git.update_all_repos() <NEW_LINE> if xml_path: <NEW_LINE> <INDENT> self.git.start_with_xml(... | This method handles run from CLI | 625941c291af0d3eaac9b9ba |
def parse_filters(filter_str): <NEW_LINE> <INDENT> filters_p = __FFI__.new('bxilog_filters_p[1]') <NEW_LINE> err = __BXIBASE_CAPI__.bxilog_filters_parse(filter_str, filters_p) <NEW_LINE> bxierr.BXICError.raise_if_ko(err) <NEW_LINE> return Filters(filters_p[0]) | Parse the given string and return the corresponding set of filters as
a bxilog_filter_p
@param[in] filters_str a string representing filters as
defined in ::bxilog_filters_parse()
@return an instance of the Filters class | 625941c2a79ad161976cc0e9 |
def customize_compiler_for_nvcc(self): <NEW_LINE> <INDENT> self.src_extensions.append('.cu') <NEW_LINE> default_compiler_so = self.compiler_so <NEW_LINE> super = self._compile <NEW_LINE> def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts): <NEW_LINE> <INDENT> self.set_executable('compiler_so', CUDA['nvcc']) <... | inject deep into distutils to customize how the dispatch
to gcc/nvcc works.
If you subclass UnixCCompiler, it's not trivial to get your subclass
injected in, and still have the right customizations (i.e.
distutils.sysconfig.customize_compiler) run on it. So instead of going
the OO route, I have this. Note, it's kindof... | 625941c2aad79263cf3909e2 |
def on_epoch_end(self, epoch: int, logs: Dict[str, float] = None) -> None: <NEW_LINE> <INDENT> if logs is None: <NEW_LINE> <INDENT> logs = {} <NEW_LINE> <DEDENT> current = logs.get(self.monitor) <NEW_LINE> if current is None: <NEW_LINE> <INDENT> warnings.warn("Early stopping requires %s available!" % self.monitor, Runt... | Method that stops training and produces log messages on early stopping
epoch: Epoch number
logs: Dictionary that holds the monitor being tracked and its value | 625941c292d797404e30412d |
def create_model(self, data): <NEW_LINE> <INDENT> model = Exchange() <NEW_LINE> model.set_id(data[0]) <NEW_LINE> model.set_name(data[1]) <NEW_LINE> model.set_public(data[2]) <NEW_LINE> model.set_private(data[3]) <NEW_LINE> model.set_user_id(data[4]) <NEW_LINE> model.set_uid(data[5]) <NEW_LINE> model.set_pw(data[6]) <NE... | Create an Exchange model from database data (id, exchangename, public, private, user_id)
:param data:
:return Bot: | 625941c2e5267d203edcdc43 |
def find_ini_config_file(warnings=None): <NEW_LINE> <INDENT> if warnings is None: <NEW_LINE> <INDENT> warnings = set() <NEW_LINE> <DEDENT> SENTINEL = object <NEW_LINE> potential_paths = [] <NEW_LINE> path_from_env = os.getenv("ANSIBLE_CONFIG", SENTINEL) <NEW_LINE> if path_from_env is not SENTINEL: <NEW_LINE> <INDENT> p... | Load INI Config File order(first found is used): ENV, CWD, HOME, /etc/ansible | 625941c226238365f5f0ee0f |
def sorting_theory(): <NEW_LINE> <INDENT> pass | 3.1 sorting_theory | 625941c22c8b7c6e89b35766 |
def compara_assinatura(assinatura_calculada, assinatura_infectada): <NEW_LINE> <INDENT> resultado_diferenca = [] <NEW_LINE> for i in range (0, len(assinatura_calculada), 1): <NEW_LINE> <INDENT> resultado_diferenca.append(abs(assinatura_infectada[i] - assinatura_calculada[i])) <NEW_LINE> <DEDENT> soma_diferenca = 0 <NEW... | Essa funcao recebe duas assinaturas de texto e deve devolver o grau de similaridade nas assinaturas. | 625941c2097d151d1a222dff |
def clean_dataframe(df, time_col): <NEW_LINE> <INDENT> df = df.dropna(subset=['Time', 'Outcome', 'Price']) <NEW_LINE> df['Price'] = strip_values(df['Price'], ['$', ' million', ',']) <NEW_LINE> df['Liftoff Thrust'] = strip_values(df['Liftoff Thrust'], [' kN', ',']) <NEW_LINE> df['Rocket Height'] = strip_values(df['Rocke... | Takes a dataframe and cleans it according to a slightly hardcoded system
where units are removed from Price, Liftoff Thrust, and Rocket Height
columns, None values are dropped, and a designated time column is
converted to official datetime format.
Args:
dataframe: the input dataframe to clean
time_col: the tim... | 625941c2d10714528d5ffc85 |
def scatter_update_tensor(x, indices, updates): <NEW_LINE> <INDENT> x_shape = tf.shape(x) <NEW_LINE> patch = tf.scatter_nd(indices, updates, x_shape) <NEW_LINE> mask = tf.greater(tf.scatter_nd(indices, tf.ones_like(updates), x_shape), 0) <NEW_LINE> return tf.where(mask, patch, x) | Utility function similar to `tf.scatter_update`, but performing on Tensor
indices is nd. Avoid error occured when using tf.scatter_update. | 625941c244b2445a3393203b |
@cpython_api([PyObject], lltype.Void) <NEW_LINE> def _PyObject_GC_TRACK(space, op): <NEW_LINE> <INDENT> raise NotImplementedError | A macro version of PyObject_GC_Track(). It should not be used for
extension modules. | 625941c263d6d428bbe44493 |
def subcloud_get(context, subcloud_id): <NEW_LINE> <INDENT> return IMPL.subcloud_get(context, subcloud_id) | Retrieve a subcloud or raise if it does not exist. | 625941c2e76e3b2f99f3a7b2 |
def json(self, **kwargs): <NEW_LINE> <INDENT> return json.dumps(self.dict(), default=_json_date, **kwargs) | Returns a JSON representation of the current query. Kwargs are passed to
``json.dumps``. | 625941c2293b9510aa2c323c |
def _es_args(self, resource, refresh=None, source_projections=None): <NEW_LINE> <INDENT> args = {"index": self._resource_index(resource)} <NEW_LINE> if source_projections: <NEW_LINE> <INDENT> args["_source"] = ",".join( [source_projections, RESOURCE_FIELD, config.ETAG] ) <NEW_LINE> <DEDENT> if refresh: <NEW_LINE> <INDE... | Get index and doctype args. | 625941c2fb3f5b602dac3635 |
def inference_trivial(net, input_layer): <NEW_LINE> <INDENT> net.use_batch_norm = False <NEW_LINE> x = net.input_layer(input_layer) <NEW_LINE> x = net.flatten(x) <NEW_LINE> x = net.fully_connected(x, 1) <NEW_LINE> return x | A trivial model for benchmarking input pipeline performance | 625941c267a9b606de4a7e5f |
def build_work_titles(work: Work, titles: Dict[str, Tuple[str, str]]) -> List[WorkTitle]: <NEW_LINE> <INDENT> if not titles: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> language_map = { 'english': anilist_langs.english_ext_lang, 'romaji': anilist_langs.romaji_ext_lang, 'japanese': anilist_langs.japanese_ext_lang,... | Insert WorkTitle objects for a given Work when required into Mangaki's database.
:param work: a work
:param titles: a list of alternative titles
:type work: Work
:type titles: Dict[str, Tuple[str, str]]
:return: a list of WorkTitle objects that were inserted in Mangaki's database
:rtype: List[WorkTitle] | 625941c20a366e3fb873e7bc |
def get_cfn_value(self): <NEW_LINE> <INDENT> return str(self.value if self.value is not None else self.definition.get("default", "NONE")) | Convert parameter value into CFN value.
Used when the parameter must go into a comma separated CFN parameter. | 625941c207f4c71912b11425 |
def site_config_dirs(appname): <NEW_LINE> <INDENT> if WINDOWS: <NEW_LINE> <INDENT> path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) <NEW_LINE> pathlist = [os.path.join(path, appname)] <NEW_LINE> <DEDENT> elif sys.platform == 'darwin': <NEW_LINE> <INDENT> pathlist = [os.path.join('/Library/Application Su... | Return a list of potential user-shared config dirs for this application.
"appname" is the name of application.
Typical user config directories are:
Mac OS X: /Library/Application Support/<AppName>/
Unix: /etc or $XDG_CONFIG_DIRS[i]/<AppName>/ for each value in
$XDG_CONFIG_DIRS
... | 625941c230bbd722463cbd68 |
def minutesPastMidnighttoPytime(t): <NEW_LINE> <INDENT> hour, min = t // 60, t % 60 <NEW_LINE> return datetime.time(hour, min) | converts an integer representing elapsed minutes past midnight to a
python datetime.time object
>>> minutesPastMidnighttoPytime(100)
datetime.time(1, 40) | 625941c21f5feb6acb0c4af7 |
def insert(self, word: str) -> None: <NEW_LINE> <INDENT> node = self.root <NEW_LINE> for char in word: <NEW_LINE> <INDENT> if char not in node.children: <NEW_LINE> <INDENT> node.children[char] = TreeNode() <NEW_LINE> <DEDENT> node = node.children[char] <NEW_LINE> <DEDENT> node.is_end = True | Inserts a word into the trie. | 625941c2a934411ee3751637 |
def get_youtube_id(video_id, lang_code=None): <NEW_LINE> <INDENT> if not lang_code: <NEW_LINE> <INDENT> lang_code = settings.LANGUAGE_CODE <NEW_LINE> <DEDENT> if not lang_code or lang_code == "en": <NEW_LINE> <INDENT> return video_id <NEW_LINE> <DEDENT> return get_dubbed_video_map(lcode_to_ietf(lang_code)).get(video_id... | Given a video ID, return the youtube ID for the given language.
If lang_code is None, return the base / default youtube_id for the given video_id.
If youtube_id for the given lang_code is not found, function returns None.
Accepts lang_code in ietf format | 625941c23eb6a72ae02ec47c |
def release_oldest_shortened_url(self): <NEW_LINE> <INDENT> shortened_url = ShortenedURL.objects.order_by( 'created_at' ).first() <NEW_LINE> if shortened_url: <NEW_LINE> <INDENT> Word.objects.filter( word=shortened_url.shortened_url ).update(used=False) <NEW_LINE> shortened_url.delete() | Release the oldest shortened url. | 625941c215fb5d323cde0ab1 |
def store_data(self, data, encoding='utf-8'): <NEW_LINE> <INDENT> path = random_filename(self.work_path) <NEW_LINE> try: <NEW_LINE> <INDENT> with open(path, 'wb') as fh: <NEW_LINE> <INDENT> if isinstance(data, six.text_type): <NEW_LINE> <INDENT> data = data.encode(encoding) <NEW_LINE> <DEDENT> if data is not None: <NEW... | Put the given content into a file, possibly encoding it as UTF-8
in the process. | 625941c2cdde0d52a9e52fd6 |
def _AskForProject(self, add_controller, path=None): <NEW_LINE> <INDENT> add_controller.SetPath(path) <NEW_LINE> add_controller.SetPort(self._table.UniquePort()) <NEW_LINE> if add_controller.ShowModal() == wx.ID_OK: <NEW_LINE> <INDENT> return add_controller.Project() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return... | Ask the user for a project using the specified controller.
Args:
add_controller: A class to use as the Add Project Controller for
our dialog.
path: A file sytem path to pre-poplate the controller's path with.
Returns:
A launcher.Project, or None. | 625941c24a966d76dd550fb2 |
def _print_change(self, rstfile, oldline, newline): <NEW_LINE> <INDENT> print ("%s: '%s' --> '%s'"%(self._get_relative_path(rstfile), oldline.rstrip(), newline.rstrip())) | Prints the change to the standard output | 625941c250485f2cf553cd3d |
def jaccard_distance(boxA, boxB): <NEW_LINE> <INDENT> xA = max(boxA[0], boxB[0]) <NEW_LINE> yA = max(boxA[1], boxB[1]) <NEW_LINE> xB = min(boxA[2], boxB[2]) <NEW_LINE> yB = min(boxA[3], boxB[3]) <NEW_LINE> interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1) <NEW_LINE> boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - b... | Calculate the Intersection over Union (IoU) of two bounding boxes.
:param bb1: list [x1, x2, y1, y2]
The (x1, y1) position is at the top left corner,
the (x2, y2) position is at the bottom right corner
:param bb2: list [x1, x2, y1, y2]
The (x1, y1) position is at the top left corner,
the (x2, y2) positi... | 625941c2f548e778e58cd521 |
def containing_profile(self): <NEW_LINE> <INDENT> raise NotImplementedError( 'operation containing_profile(...) not yet implemented') | The query containingProfile returns the closest profile directly or indirectly containing this stereotype.
result = (self.namespace.oclAsType(Package).containingProfile())
<p>From package UML::Packages.</p> | 625941c2099cdd3c635f0c00 |
def _set_grouper(self, obj, sort=False): <NEW_LINE> <INDENT> if self.key is not None and self.level is not None: <NEW_LINE> <INDENT> raise ValueError( "The Grouper cannot specify both a key and a level!") <NEW_LINE> <DEDENT> if self._grouper is None: <NEW_LINE> <INDENT> self._grouper = self.grouper <NEW_LINE> <DEDENT> ... | given an object and the specifications, setup the internal grouper
for this particular specification
Parameters
----------
obj : the subject object
sort : bool, default False
whether the resulting grouper should be sorted | 625941c29c8ee82313fbb718 |
def combine_gen_sources(source_a, source_b, mask): <NEW_LINE> <INDENT> animation = zip(source_a(), source_b(), mask()) <NEW_LINE> first_time = cv2.getTickCount() <NEW_LINE> for frame_a, frame_b, frame_mask in animation: <NEW_LINE> <INDENT> frame = primitives.mask_together(frame_a, frame_b, frame_mask) <NEW_LINE> last_t... | given two source generators and a mask generator, combine the two sources using the mask | 625941c215baa723493c3f18 |
def test_topo_c01b(self): <NEW_LINE> <INDENT> batch_size = 100 <NEW_LINE> c01b_test = TFD(which_set='test', axes=('c', 0, 1, 'b')) <NEW_LINE> c01b_X = c01b_test.X[0:batch_size, :] <NEW_LINE> c01b = c01b_test.get_topological_view(c01b_X) <NEW_LINE> assert c01b.shape == (1, 48, 48, batch_size) <NEW_LINE> b01c = c01b.tran... | Tests that a topological batch with axes ('c',0,1,'b')
can be dimshuffled back to match the standard ('b',0,1,'c')
format. | 625941c2a8ecb033257d3072 |
def symH(self, parity=0): <NEW_LINE> <INDENT> f = self.x <NEW_LINE> U = self.y <NEW_LINE> N = len(f) <NEW_LINE> ys = U.shape <NEW_LINE> ze_x = np.array([0]) <NEW_LINE> ze_y = np.zeros((ys[0],1)) <NEW_LINE> if parity == 0: <NEW_LINE> <INDENT> Up = np.concatenate((ze_y, U, np.flipud(np.conjugate(U[:, 0:-1]))), 1) <NEW_LI... | enforce Hermitian symetry
Parameters
----------
parity : integer
0 even 1 odd
Returns
-------
V : FHsignal | 625941c2e1aae11d1e749c5a |
def terms_stats_facet(self, key_field, value_field, facet_fieldname=None): <NEW_LINE> <INDENT> clone = self._clone() <NEW_LINE> clone.query.add_terms_stats_facet(key_field, value_field, facet_fieldname) <NEW_LINE> return clone | Adds term stats faceting to a query | 625941c28a43f66fc4b5400b |
def get_x_y(self, sentence_maxlen, dataset_name='all'): <NEW_LINE> <INDENT> raise NotImplementedError | Implement with own data source.
:param sentence_maxlen: maximum number of characters per sample
:param dataset_name: 'all', 'train', 'dev' or 'test'
:return: Tuple (x, y)
x: Array of shape (batch_size, sentence_maxlen). Entries in dimension 1 are alphabet indices, index 0 is the padding symbol
y: Array... | 625941c207d97122c417882c |
def _choose_one_theorem_at_random(thms): <NEW_LINE> <INDENT> size_of_thms = tf.size(thms) <NEW_LINE> def get_an_element(): <NEW_LINE> <INDENT> random_index = tf.random_uniform([], minval=0, maxval=size_of_thms, dtype=tf.int32) <NEW_LINE> return thms[random_index] <NEW_LINE> <DEDENT> return tf.cond(size_of_thms > 0, get... | Adds tf ops to pick one theorem at random from a list of theorems. | 625941c2c432627299f04be9 |
def replace_filter(text: str, pattern: dict) -> str: <NEW_LINE> <INDENT> for pat, rep in pattern.items(): <NEW_LINE> <INDENT> text = text.replace(pat, rep) <NEW_LINE> <DEDENT> return text | replace_filter filtering text by pattern key to value
slower than trans_filter
just use text_filter | 625941c2be383301e01b542e |
def save_collection(self): <NEW_LINE> <INDENT> if self.chosen_collection: <NEW_LINE> <INDENT> if self.chosen_collection.save_id_for_new(): <NEW_LINE> <INDENT> self.collections.append(self.chosen_collection) <NEW_LINE> <DEDENT> self.save_json() <NEW_LINE> self.sort() | Save a unique id number if the object is a newly instantiated :class:`Collection` object.
Then append this :class:`Collection` to :attr:`CollectionHolder.collections` :obj:`list`, update
`json` data file by calling :meth:`CollectionHolder.save_json()` and at last uptade the order of
:class:`Collection` instances in :... | 625941c2f7d966606f6a9fa7 |
def test_categories_list_delete(self): <NEW_LINE> <INDENT> delete_permission = Permission.objects.get(codename='delete_category') <NEW_LINE> self.user.user_permissions.add(delete_permission) <NEW_LINE> self.user.refresh_from_db() <NEW_LINE> self.browser.get(self.live_server_url + reverse('account:login')) <NEW_LINE> se... | Test categories list page with delete category permission | 625941c2de87d2750b85fd35 |
def human_move(board, human): <NEW_LINE> <INDENT> legal = legal_moves(board) <NEW_LINE> move = None <NEW_LINE> while move not in legal: <NEW_LINE> <INDENT> move = ask_number('Твой ход. Выбери одно из полей (0 - 8): ', 0, NUM_SQUARES) <NEW_LINE> if move not in legal: <NEW_LINE> <INDENT> print('\nСмешной человек! Это пол... | Получает ход человека. | 625941c2656771135c3eb811 |
def get_all_object(self): <NEW_LINE> <INDENT> return self.bucket.objects.all() | **中文文档**
返回Bucket中的所有对象。对于大型Bucket, 请慎用此方法! | 625941c2fff4ab517eb2f3df |
def getfixturemarker(obj: object) -> Optional["FixtureFunctionMarker"]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fixturemarker = getattr( obj, "_pytestfixturefunction", None ) <NEW_LINE> <DEDENT> except TEST_OUTCOME: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return fixturemarker | return fixturemarker or None if it doesn't exist or raised
exceptions. | 625941c2a8370b7717052845 |
def BLsurfacestat(filename='BL_surface_stat.dat',Uref=1.0,Tref=1.0,**kwargs): <NEW_LINE> <INDENT> if not os.path.exists(filename): <NEW_LINE> <INDENT> print('Error: '+filename+' does not exist') <NEW_LINE> return 1 <NEW_LINE> <DEDENT> if 'grid' in kwargs: <NEW_LINE> <INDENT> grid = kwargs['grid'] <NEW_LINE> Nx2 = grid.... | Load BL_surface_stat file | 625941c2f8510a7c17cf96a0 |
def print_anova(mydata, x, y): <NEW_LINE> <INDENT> anova_reA= anova_lm(ols('{}~C({})'.format(y, x), data=mydata[[y, x]]).fit()) <NEW_LINE> print("x is {}, y is {} ---".format(x, y)) <NEW_LINE> print(anova_reA) <NEW_LINE> print('\t') | 为连续型变量,x为目标变量 | 625941c26e29344779a625b9 |
def get_labels(self): <NEW_LINE> <INDENT> return " ".join([it[1] for it in self.get_value() if it]).strip() | Get the fluorescence labels (2nd column) | 625941c2566aa707497f4511 |
def get_parser(self, **kwargs): <NEW_LINE> <INDENT> parser = ConfigArgParser( ignore_unknown_config_file_keys=True, args_for_setting_config_path=['-c', '--config'], default_config_files=list( self.config_file_names(**kwargs) ), formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=self.get_description(**k... | :param kwargs:
:return: | 625941c2236d856c2ad4477c |
def __init__(self, c_list_sql_up, c_bool_verbose): <NEW_LINE> <INDENT> self.string_sql_db = r'Finance' <NEW_LINE> self.string_sql_server = r'localhost\SQLEXPRESS' <NEW_LINE> self.sql_conn = SqlMethods( [c_list_sql_up[0], self.string_sql_server, c_list_sql_up[1], self.string_sql_db]) <NEW_LINE> self.string_sym_sp500 = '... | base class construtor
Requirements:
package SqlMethods
package pandas
Inputs:
c_list_sql_up
Type: list
Desc: user and password for sql database
c_list_sql_up[0] -> type: string; user name
c_list_sql_up[1] -> type: string; password
c_bool_verbose
Type: boolean
Desc: flag if verbose output desired
Important Info:
1. ... | 625941c260cbc95b062c64e8 |
def _simulation_writeout(filename, organisms, headerData): <NEW_LINE> <INDENT> outputfile = open(filename, "w") <NEW_LINE> for header in headerData: <NEW_LINE> <INDENT> outputfile.write(header + "\n") <NEW_LINE> <DEDENT> for organism in organisms: <NEW_LINE> <INDENT> genome = ["|".join(organisms[organism]['genome'][i])... | !
Private function called by simulate_<simulation type>() functions
to write out the corresponding population files for each generation.
@param filename String: Relative or absolute path of the new
population file.
@param organisms Dictionary: Dictionary of organisms from
simulate_<simulation type>() functions to be... | 625941c2cad5886f8bd26f7f |
def allow_icmp(zone, icmp): <NEW_LINE> <INDENT> if icmp not in get_icmp_types(): <NEW_LINE> <INDENT> log.error('Invalid ICMP type') <NEW_LINE> return False <NEW_LINE> <DEDENT> if icmp not in list_icmp_block(zone): <NEW_LINE> <INDENT> log.info('ICMP Type is already permitted') <NEW_LINE> return 'success' <NEW_LINE> <DED... | Allow a specific ICMP type on a zone
.. versionadded:: Beryllium
CLI Example:
.. code-block::
salt '*' firewalld.allow_icmp zone echo-reply | 625941c2fff4ab517eb2f3e0 |
def c_lift(self, V): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> circs = self.circs[:-1] <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> V = np.asarray(V) <NEW_LINE> V_norm = np.linalg.norm(V) <NEW_LINE> circs = self.solve_circs(V) <NEW_LINE> <DEDENT> return np.sum(V_norm*circs)*2 | Calculate the lift | 625941c27d847024c06be25f |
def schedule_task(self, task, args = None, vars = None, function_name = None, start_time = None, next_run_time = None, stop_time = None, repeats = None, retry_failed = None, period = None, timeout = None, enabled = None, group_name = None, ignore_duplicate = False, sync_output = 0, user_id = True ): <NEW_LINE> <INDENT>... | Schedule a task in web2py Scheduler
@param task: name of the function/task to be scheduled
@param args: args to be passed to the scheduled task
@param vars: vars to be passed to the scheduled task
@param function_name: function name (if different from task name)
@param start_time: start_time for the scheduled task
@pa... | 625941c2711fe17d82542314 |
def unnormalise_density(c, rho): <NEW_LINE> <INDENT> return c * rho | Reverses any desnity normalisation
As a general rule this should be done using the units read in from the file,
with unit conversion done afterwards | 625941c2596a897236089a68 |
def run(self): <NEW_LINE> <INDENT> if self.opts['doc']: <NEW_LINE> <INDENT> self._print_docs() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._verify_fun() <NEW_LINE> return self.functions[self.opts['fun']](*self.opts['arg']) | Execute the runner sequence | 625941c232920d7e50b28173 |
def admin_routes(app): <NEW_LINE> <INDENT> admin = Blueprint('admin_notifications', __name__) <NEW_LINE> admin.route("/notifications", methods=['GET'])( admin.route("/notifications/<int:page>", methods=['GET'])( admin.route("/notifications/<int:page>/<int(min=1, max=100):limit>", methods=['GET'])( require_appkey( auth_... | Register admin notifications routes with the application.
:param app: Flask application
:type app: Flask | 625941c2a05bb46b383ec7c8 |
def set_pins(self): <NEW_LINE> <INDENT> for pin in self.data + [self.read]: <NEW_LINE> <INDENT> self.rduino.pin_mode(pin, OUTPUT) | Initialises the Pins on the ruggeduino for sound output | 625941c28c3a87329515835d |
def get_version(self): <NEW_LINE> <INDENT> return _lib.X509_REQ_get_version(self._req) | Get the version subfield (RFC 2459, section 4.1.2.1) of the certificate
request.
:return: an integer giving the value of the version subfield | 625941c27b25080760e393ff |
def run_app(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> (new_in, new_out) = self.get_frame_range_from_shotgun() <NEW_LINE> (current_in, current_out) = self.get_current_frame_range() <NEW_LINE> if new_in is None or new_out is None: <NEW_LINE> <INDENT> message = "Shotgun has not yet been populated with \n" <NEW_L... | Callback from when the menu is clicked.
The default callback will first query the frame range from shotgun and validate the data.
If there is missing Shotgun data it will popup a QMessageBox dialog alerting the user.
Assuming all data exists in shotgun, it will set the frame range with the newly
queried data and ... | 625941c267a9b606de4a7e60 |
def delete_group_user(group_id: Union[int, str], login: str): <NEW_LINE> <INDENT> uri = f'/groups/{group_id}/users/{login}' <NEW_LINE> method = 'DELETE' <NEW_LINE> return Request.send(method, uri) | 从 Group 中删除 User
Args:
group_id: Group 的 {login} 或 {id}
login: User 的 {login}, 不确定 {id} 是否可行
Returns:
删除的 User 的成员信息 | 625941c2091ae35668666f07 |
def designs_id_exists_get_with_http_info(self, id, **kwargs): <NEW_LINE> <INDENT> all_params = ['id'] <NEW_LINE> all_params.append('callback') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> params = locals() <NEW_LINE> for key, val in iteritems(params['kwargs']): <NEW_LINE> <INDENT> if key not in all... | Check whether a model instance exists in the data source.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.des... | 625941c263b5f9789fde708a |
def get_song_data(self, artist_name: str, track_title: str) -> dict: <NEW_LINE> <INDENT> self.total_count += 1 <NEW_LINE> result = self.MM.matcher_track_get(q_artist=artist_name, q_track=track_title) <NEW_LINE> result = result["message"] <NEW_LINE> if result["header"]["status_code"] != 200 or res... | Gets song data from musixmatch api. Using the free API means
access to only 30% of the lyrics body, so that's a no go. We
can still use the API to augment our datasets with the
album name, release date, and genres.
:param artist_name: name of track artist (str)
:param track_title: name of track title (str)
:return: di... | 625941c257b8e32f5248343f |
def getStatus(self): <NEW_LINE> <INDENT> return _CsoundAC.Event_getStatus(self) | getStatus(Event self) -> double | 625941c26aa9bd52df036d48 |
def convolve(f, weights, mode='reflect', cval=0.0, out=None, output=None): <NEW_LINE> <INDENT> if f.dtype != weights.dtype: <NEW_LINE> <INDENT> weights = weights.astype(f.dtype) <NEW_LINE> <DEDENT> if f.ndim != weights.ndim: <NEW_LINE> <INDENT> raise ValueError('mahotas.convolve: `f` and `weights` must have the same di... | convolved = convolve(f, weights, mode='reflect', cval=0.0, out={new array})
Convolution of `f` and `weights`
Convolution is performed in `doubles` to avoid over/underflow, but the
result is then cast to `f.dtype`.
Parameters
----------
f : ndarray
input. Any dimension is supported
weights : ndarray
weight fi... | 625941c2009cb60464c63358 |
def get_input_train(self, m): <NEW_LINE> <INDENT> pairs = self.train_generator(m) <NEW_LINE> pref, self.training_indices = utils.reshape_pref(self.draw_preference(pairs)) <NEW_LINE> data = self.X.iloc[self.training_indices, [i for i in range(self.d-1)] + [-1]] <NEW_LINE> return [np.array(data), pref] | Construct training data to use for modelling
:param m: int, number of preferences
:return: list, - data: np.array, n instances with their attributes
- pref: list of tuples, training preferences | 625941c2cc40096d615958f6 |
def click_benchmarks_button(self): <NEW_LINE> <INDENT> self.click_element(self.benchmarks_button_locator, True) | Implementing click benchmarks button functionality
:return: | 625941c2627d3e7fe0d68df4 |
def setRobotPosition(self, position): <NEW_LINE> <INDENT> assert isinstance(position, Position) <NEW_LINE> self.robot_position = position | Set the position of the robot to POSITION.
:param position: a Position object. | 625941c282261d6c526ab442 |
def share_group_snapshot_update(context, share_group_snapshot_id, values): <NEW_LINE> <INDENT> return IMPL.share_group_snapshot_update( context, share_group_snapshot_id, values) | Set the given properties on a share group snapshot and update it.
Raises NotFound if share group snapshot does not exist. | 625941c2cb5e8a47e48b7a52 |
def p_factor(t): <NEW_LINE> <INDENT> t[0] = t[1] | factor : VARIABLE
| NUMBER
| BOOLEAN
| STRING
| tuple
| list | 625941c263f4b57ef00010c3 |
def singleNumber_3(self, nums): <NEW_LINE> <INDENT> if len(nums) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> sum = nums[0] <NEW_LINE> for num in nums[1:]: <NEW_LINE> <INDENT> sum ^= num <NEW_LINE> <DEDENT> bit_1 = -1 <NEW_LINE> while sum: <NEW_LINE> <INDENT> bit = sum & 1 <NEW_LINE> bit_1 += 1 <NEW_LINE> ... | :type nums: List[int]
:rtype: List[int]
分组,将两个出现一次的数分到不同组 | 625941c2d164cc6175782cf3 |
def test_notify_new_review_request_with_diff(self): <NEW_LINE> <INDENT> review_request = self.create_review_request( create_repository=True, submitter=self.user, summary='Test Review Request', description='My description.', publish=False) <NEW_LINE> self.create_diffset(review_request) <NEW_LINE> self._create_config() <... | Testing MatrixIntegration notifies on new review request with diff
| 625941c2b57a9660fec33828 |
def update_last_sync_event(self): <NEW_LINE> <INDENT> self.database.update_last_sync_event(self.partner['id']) | Updates last sync event for partner. | 625941c2cc0a2c11143dce36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.