code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def set_vault_path(): <NEW_LINE> <INDENT> vault_path = get_vault_path() <NEW_LINE> global_scope['db_file'] = vault_path | Load vault path | 625941e3bde94217f36831cb |
def decision(s): <NEW_LINE> <INDENT> s1 = s**2 <NEW_LINE> s2 = sum(s1.tolist()) <NEW_LINE> s3 = sqrt(s2) <NEW_LINE> if s3 < 1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Terminate constrains | 625941e3eab8aa0e5d26df37 |
def __init__(self,model,cov=None): <NEW_LINE> <INDENT> self.model = model <NEW_LINE> current = self.model.optimizer_array <NEW_LINE> self.D = current.size <NEW_LINE> self.chains = [] <NEW_LINE> if cov is None: <NEW_LINE> <INDENT> self.cov = np.eye(self.D) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.cov = cov <NE... | Metropolis Hastings, with tunings according to Gelman et al. | 625941e34e4d5625662d47b0 |
def non_overlapping_frames(data, frame_size, time_major=False): <NEW_LINE> <INDENT> if time_major: <NEW_LINE> <INDENT> data = tf.transpose(data) <NEW_LINE> <DEDENT> num_split = data.get_shape()[1].value / frame_size <NEW_LINE> return tf.split(1, num_split, data) | Divides an input into non-overlapping frames, returning them
as a list for ease of use with tensorflow's rnns.
Will presumably have to engage in some sort of padding of the final
step, although it might make sense to just discard the final small frame
depending on the frame size. Assumes all sequences have already bee... | 625941e363b5f9789fde74c4 |
def gcd(*args): <NEW_LINE> <INDENT> def __gcd__(a, b): <NEW_LINE> <INDENT> if b == 0: <NEW_LINE> <INDENT> return a <NEW_LINE> <DEDENT> return __gcd__(b, a % b) <NEW_LINE> <DEDENT> li = [] <NEW_LINE> for a in args: <NEW_LINE> <INDENT> if isinstance(a, Iterable) is True: <NEW_LINE> <INDENT> li.extend(a) <NEW_LINE> <DEDEN... | 计算队列的最大公约数
传递的数值是整数,非整数将单取整数部分 | 625941e31f5feb6acb0c4f28 |
def rename_storage_group(self, storage_group, new_sg_name): <NEW_LINE> <INDENT> if storage_group is None: <NEW_LINE> <INDENT> error_message = 'Rename storage group {0} to new name {1}' ' failed because SG {0} does not exist ' <NEW_LINE> LOG.error(error_message.format(self.module .params['sg_n... | Rename the Storage Group | 625941e35e10d32532c5f303 |
def test_create(session, fake_lorem, fake_profile): <NEW_LINE> <INDENT> fake_org = create_organization( organization_name=fake_lorem.word(), address=fake_profile.profile()['address']) <NEW_LINE> test_model = ClientIndustry( name=fake_lorem.word(), organization_id=fake_org.id) <NEW_LINE> result = ClientIndustryRepositor... | Test creating a client industry. | 625941e33d592f4c4ed1d441 |
def __init__(self, logger, settings): <NEW_LINE> <INDENT> Score.__init__(self, logger, settings) <NEW_LINE> self.logger.debug('Initializing IrysScore...') <NEW_LINE> self.match_score = settings.match_score <NEW_LINE> self.mismatch_score = settings.mismatch_score <NEW_LINE> self.other_score = settings.other_score <NEW_L... | Constructor
In settings object (from optparse module) with:
match_score: score for matching nucleotides in subject and query
mismatch_score: score for different nucleotides in subject and query
gap_score: score for a missing nucleotide in either subject or query
other_score: s... | 625941e37c178a314d6ef843 |
def ldd_deps(exe): <NEW_LINE> <INDENT> if (exe.endswith(".jar") or exe.endswith(".pl") or exe.endswith(".py") or exe.endswith(".sh") or exe.endswith(".txt") or os.path.isdir(exe)): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if exe not in LDD_CACHE: <NEW_LINE> <INDENT> p = subprocess.Popen(["ldd", exe], stdout=su... | Runs 'ldd' on the provided 'exe' path, returning a list of
any libraries it depends on. Blacklisted libraries are
removed from this list.
If the provided 'exe' is not a binary executable, returns
an empty list. | 625941e38e7ae83300e4b3ab |
def generateTitle(pos_dict): <NEW_LINE> <INDENT> Noun = ['NNP', 'NN'] <NEW_LINE> Verb = ['VB', 'VBZ', 'VBD'] <NEW_LINE> Adjective = ['JJ'] <NEW_LINE> title = "" <NEW_LINE> if(len(pos_dict[Noun[0]]) > 0): <NEW_LINE> <INDENT> title += pos_dict[Noun[0]].pop(0) + ' ' <NEW_LINE> <DEDENT> elif(len(pos_dict[Noun[1]]) > 0): <N... | Based on the common English sentence structure Subject+Verb+Object
creat a templated sentence using POS tags for the title belong to those
categories | 625941e3796e427e537b09a7 |
def age(then, format="%a %b %d, %Y", scale="year"): <NEW_LINE> <INDENT> plural = lambda t, c : t if c == 1 else (t + "s") <NEW_LINE> fmt = lambda t, c : "%d %s" % (c, plural(t, c)) <NEW_LINE> now = time.time() <NEW_LINE> if then > now : <NEW_LINE> <INDENT> return 'in the future' <NEW_LINE> <DEDENT> threshold = dropwhil... | convert (timestamp, tzoff) tuple into an age string. both `timestamp` and
`tzoff` are expected to be integers. | 625941e3b7558d58953c52ea |
def test_post_products_409(self): <NEW_LINE> <INDENT> body = [PAYLOAD[0], PAYLOAD[0]] <NEW_LINE> headers = [('X_API_KEY', 'food')] <NEW_LINE> response = self.client.open( '/products-api/products', method='POST', data=json.dumps(body), headers=headers, content_type='application/json') <NEW_LINE> self.assertEqual(respons... | Test case for post_products with a duplicate product name
Add a new product to a factory's inventory. | 625941e3f9cc0f698b1409d6 |
@curry <NEW_LINE> def do_one(fns, x): <NEW_LINE> <INDENT> for fn in fns: <NEW_LINE> <INDENT> result = fn(x) <NEW_LINE> if result != x: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> <DEDENT> return x | Try each of the functions until one works. Then stop. | 625941e3d18da76e235328b8 |
def exists(self): <NEW_LINE> <INDENT> return os.path.exists(self.path) | Test file existence. | 625941e330bbd722463cc1a6 |
def get_user_detail_by_ids(self, user_ids): <NEW_LINE> <INDENT> method = 'POST' <NEW_LINE> url = 'https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/list' + self.get_access_token_param() <NEW_LINE> data = { 'userid_list': user_ids, 'field_filter_list': "sys00-name,sys00-email,sys00-dept,sys00-mainDept,sys00-mobile... | 通过一组UserId获取一组用户的详细信息 | 625941e3e64d504609d74c1e |
def commencements_relevant_at_expression_date(self): <NEW_LINE> <INDENT> commencements = self.work.commencements.all() <NEW_LINE> for commencement in commencements: <NEW_LINE> <INDENT> if commencement.all_provisions: <NEW_LINE> <INDENT> return [commencement] <NEW_LINE> <DEDENT> <DEDENT> commenceable_provision_ids = [p.... | Return a list of Commencement objects that have to do with the provisions that exist on this expression.
| 625941e3435de62698dfe02b |
def json(self): <NEW_LINE> <INDENT> return { "x": int(self.x), "y": int(self.y), "rotation": self.rotation, "flip_horizontal": self.flip_horizontal, "layer": self.layer, } | Return the body as JSON | 625941e35fc7496912cc3d5c |
def meta(self, sample_meta_id): <NEW_LINE> <INDENT> return self._eLABJournalObject__api.sample_meta(self.id(), sample_meta_id) | Get meta item (meta) with provided sample_meta_id for the sample. | 625941e3f8510a7c17cf9add |
def getImportance(self, employees, id): <NEW_LINE> <INDENT> emaps = {employee.id: employee for employee in employees} <NEW_LINE> def dfs(eid): <NEW_LINE> <INDENT> sum = emaps[eid].importance <NEW_LINE> for subid in emaps[eid].subordinates: <NEW_LINE> <INDENT> sum += dfs(subid) <NEW_LINE> <DEDENT> return sum <NEW_LINE> ... | :type employees: Employee
:type id: int
:rtype: int | 625941e3a4f1c619b28b040e |
def get_next_activity(self): <NEW_LINE> <INDENT> return self.next() | Gets the next ``Activity`` in this list.
return: (osid.learning.Activity) - the next ``Activity`` in this
list. The ``has_next()`` method should be used to test
that a next ``Activity`` is available before calling
this method.
raise: IllegalState - no more elements available in this list
raise... | 625941e3e5267d203edce076 |
@task(expires=60 * 60) <NEW_LINE> def updateDB_MCConfig(configPK): <NEW_LINE> <INDENT> mcp = MinecraftServerProperties.get(docid=configPK) <NEW_LINE> mcServer = MinecraftServer.objects.get(pk=mcp.nc_minecraftServerPK) <NEW_LINE> stype = getServerFromModel(mcServer=mcServer) <NEW_LINE> server = stype(mcServer=mcServer) ... | Update the given DB config with the real server.properties | 625941e33346ee7daa2b314c |
def rellenar_tabla_desechos(self): <NEW_LINE> <INDENT> parte = self.objeto <NEW_LINE> if parte is not None: <NEW_LINE> <INDENT> model = self.wids['tv_desecho'].get_model() <NEW_LINE> self.wids['tv_desecho'].set_model(None) <NEW_LINE> model.clear() <NEW_LINE> desechos = parte.descuentosDeMaterial[:] <NEW_LINE> try: <NEW... | Rellena la tabla de desechos del parte. | 625941e38c3a87329515879d |
def _get_backtrace(self, frames, inspect_packages=False, depth=0): <NEW_LINE> <INDENT> calls = [] <NEW_LINE> for index, f in enumerate(frames, 1): <NEW_LINE> <INDENT> called_module = sys.modules[f[0].f_back.f_globals["__name__"]] if f[0].f_back else None <NEW_LINE> called_func = f[3] <NEW_LINE> call = self.call_class(c... | get a nicely formatted backtrace
since -- 7-6-12
frames -- list -- the frame_tuple frames to format
inpsect_packages -- boolean -- by default, this only prints code of packages that are not
in the pythonN directories, that cuts out a lot of the noise, set this to True if you
want a full stacktrace
depth -- i... | 625941e3435de62698dfe02c |
def get_timetrace(self): <NEW_LINE> <INDENT> bin_list = self.calc_all_binnings(self, num_bins=100) <NEW_LINE> param_dict_list = [] <NEW_LINE> fidelity_list = [] <NEW_LINE> for ii in bin_list: <NEW_LINE> <INDENT> hist_y_val, hist_x_val = np.histogram(ii, bins=50) <NEW_LINE> hist_data = np.array([hist_x_val, hist_y_val])... | This function will help to find the optimal binning in the fastcomtec data,
for now under development, as we decided for now to manually pick the right binning.
Therefore the function visualize_bin_list is there to help with that task. It will make
a plot of all binnings and show which shows the best features.
@return: | 625941e3460517430c394559 |
def __init__(self): <NEW_LINE> <INDENT> self._addLevelName(logging.CRITICAL + 100, "MESSAGE") | Конструктор
@param self Ссылка на экземпляр класса | 625941e376d4e153a657ef10 |
def find_hosted_zone(self, domain_name): <NEW_LINE> <INDENT> paginator = self.client.get_paginator('list_hosted_zones') <NEW_LINE> for page in paginator.paginate(): <NEW_LINE> <INDENT> for zone in page['HostedZones']: <NEW_LINE> <INDENT> print(zone) | Find zone matching domain_name. | 625941e391f36d47f21ac8d4 |
def SetBranchness(self, *args): <NEW_LINE> <INDENT> return _itkVesselTubeSpatialObjectPointPython.itkVesselTubeSpatialObjectPoint2_SetBranchness(self, *args) | SetBranchness(self, float newBranchness) | 625941e36e29344779a629ee |
def _ensure_values_loaded(self): <NEW_LINE> <INDENT> if self._values is None: <NEW_LINE> <INDENT> vals = self._load_values() <NEW_LINE> if vals: <NEW_LINE> <INDENT> vals = self._migrate_values(vals) <NEW_LINE> self.set_values(vals) <NEW_LINE> <DEDENT> <DEDENT> return self._values | If values are not loaded and present for the current entity, read and store them.
Returns the values loaded, or None. | 625941e350485f2cf553d179 |
def add(a, b): <NEW_LINE> <INDENT> return a + b | performs addition | 625941e373bcbd0ca4b2c454 |
def update(self, id_app, template, dict_object_adaptors): <NEW_LINE> <INDENT> logger.info("****** proceding to the update of the application {}******".format(id_app)) <NEW_LINE> dry_run = self.app_list[id_app]['dry_run'] <NEW_LINE> logger.debug("list of adaptor created: {}".format(dict_object_adaptors)) <NEW_LINE> self... | Update method that will be updating the application we want to update.
:params id: id of the application we want to update
:params type: string
:params path_to_file: path to the template file
:params type: string
:params parse_params: dictionary containing the value we want to use as the value of the input section
:... | 625941e37c178a314d6ef844 |
def scan(self, path, subdir=None, excludepattern=None): <NEW_LINE> <INDENT> match = None <NEW_LINE> if excludepattern: <NEW_LINE> <INDENT> match = re.compile(excludepattern).match <NEW_LINE> <DEDENT> join = os.path.join <NEW_LINE> add = self.add <NEW_LINE> abspath = os.path.abspath(path) <NEW_LINE> if not os.path.exist... | Scans a path and adds all found files to the Resources
container.
Scans a path and adds all found files to the Resources
container. If a file is a supported (ZIP or TAR) archive, its
contents will be indexed and added automatically.
The method will consider the directory part (os.path.dirname) of
the provided path as... | 625941e391af0d3eaac9bdfb |
def titleToNumber(self, s): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> sum = 0 <NEW_LINE> for letter in reversed(s): <NEW_LINE> <INDENT> sum = 26 ** count * (ord(letter) - 64) + sum <NEW_LINE> count += 1 <NEW_LINE> <DEDENT> return sum | :type s: str
:rtype: int | 625941e3a05bb46b383ecbfd |
def test_detect(self): <NEW_LINE> <INDENT> detector = CacheDetector() <NEW_LINE> caches = detector.autodetect_caches() <NEW_LINE> self.assertNotEqual(0, len(caches), "No %s caches detected." % platform.system()) | Tests the most basic case of auto cache detection. Uses the appropriate
auto-discovery module for the OS the tests are ran on. | 625941e3377c676e91272585 |
def loadBitmap(name): <NEW_LINE> <INDENT> imgPath = 'Images/Palette/' + name+'.png' <NEW_LINE> try: <NEW_LINE> <INDENT> return IS.load(imgPath) <NEW_LINE> <DEDENT> except IS.Error: <NEW_LINE> <INDENT> return IS.load('Images/Palette/Component.png') | Loads bitmap if it exists, else loads default bitmap | 625941e3097d151d1a223236 |
def wallsAndGates(self, rooms: List[List[int]]) -> None: <NEW_LINE> <INDENT> from collections import deque <NEW_LINE> def dfs(i, j, step): <NEW_LINE> <INDENT> if i < 0 or i >= row or j < 0 or j >= col or rooms[i][j] < step: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> rooms[i][j] = min(rooms[i][j], step) <NEW_LINE> f... | Do not return anything, modify rooms in-place instead. | 625941e3379a373c97cfaf25 |
def detach(self): <NEW_LINE> <INDENT> self.disks_iface.DriveDetach(dbus.Array([], 's')) | Request the device be detached. | 625941e382261d6c526ab884 |
def drop_empty_samples(self): <NEW_LINE> <INDENT> def all_null(row): <NEW_LINE> <INDENT> return pd.isnull(row).all() <NEW_LINE> <DEDENT> empty_rows = self.reduce_rows(all_null) <NEW_LINE> non_empty_rows = -empty_rows <NEW_LINE> labels = self.labels[non_empty_rows] if self.is_labelled() else None <NEW_LINE> return DataS... | Creates a copy of the data set with any samples (rows) that had no
value for any feature removed.
Returns:
filtered: DataSet
A new DataSet with empty samples removed. The original DataSet
is unaltered. | 625941e37b25080760e39835 |
def boost_vm_cores(vm_id, cores): <NEW_LINE> <INDENT> session = VCSession(VCD.username, VCD.password, VCD.org, VCD.endpoint) <NEW_LINE> session.set_system_cpu_config(vm_id, cores) <NEW_LINE> session.kill() <NEW_LINE> return session.last_status, session.last_job_id | Boost or deboost the VM cores | 625941e35166f23b2e1a5538 |
def get_color(value): <NEW_LINE> <INDENT> if isinstance(value, int): <NEW_LINE> <INDENT> if 0 <= value < 256: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("color value not between 0 and 255") <NEW_LINE> <DEDENT> <DEDENT> val = str(value) <NEW_LINE> if val.startswith("#... | Translates `value` to a color code.
`value` may be:
- An integer color code between 0 and 255.
- An 9-bit "%XYZ" RGB triple, where each digit is between 0 and 5.
- A web-style "#XYZ" or "#XXYYZZ" RGB triple
- A grayscale name "grayX" where X is between 0 and 100.
- A color name for the sixteen standard colors. | 625941e310dbd63aa1bd2f81 |
def delete_event(self, event_id): <NEW_LINE> <INDENT> self.events[event_id]["status"] = "cancelled" | "
When we delete an event Google switch the event status to `cancelled`, but keep it the database.
We will adopt the same behaviour in the offlineclien. | 625941e324f1403a92600f41 |
def comparison(local, remote, local_path, remote_path): <NEW_LINE> <INDENT> print("File comparison for local and remote directories... (this might take a while)") <NEW_LINE> missing_list = [] <NEW_LINE> mismatch_list = [] <NEW_LINE> l, r = local, remote <NEW_LINE> l = [x for x in l if 'VLF' in x] <NEW_LINE> r = [x for ... | run comparison between lists and get a differential list | 625941e3d10714528d6000c6 |
def handle(self, *args, **options): <NEW_LINE> <INDENT> super().handle(*(tuple(settings.NINETOFIVER_APPS) + args), **options) | Test all of NINETOFIVER_APPS. | 625941e34527f215b584c831 |
def convert_valid_var_name(self, s): <NEW_LINE> <INDENT> return re.sub('\W|^(?=\d)', '_', s) | Convert a string to a valid python variable name | 625941e35fdd1c0f98dc0614 |
def is_factor(a, b): <NEW_LINE> <INDENT> return a%b == 0 | This function returns True if a is a factor of b
otherwise it returns False. | 625941e338b623060ff0b1cc |
def get_placeholders(request, template_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> temp = loader.get_template(template_name) <NEW_LINE> <DEDENT> except TemplateDoesNotExist: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> context = details(request, no404=True, only_context=True) <NEW_LINE> temp.render(Request... | Return a list of PlaceholderNode found in the given template | 625941e323849d37ff7b346b |
def single_enrollment_update(self, *args, **kwargs): <NEW_LINE> <INDENT> user_query = self.get_user_query(None, query_params=kwargs) <NEW_LINE> user = get_edxapp_user(**user_query) <NEW_LINE> course_id = kwargs.pop("course_id", None) <NEW_LINE> if not course_id: <NEW_LINE> <INDENT> raise ValidationError(detail="You hav... | Handle one update at the time | 625941e31d351010ab855efa |
@keras_export('keras.activations.deserialize') <NEW_LINE> @dispatch.add_dispatch_support <NEW_LINE> def deserialize(name, custom_objects=None): <NEW_LINE> <INDENT> return deserialize_keras_object( name, module_objects=globals(), custom_objects=custom_objects, printable_module_name='activation function') | Returns activation function given a string identifier.
Arguments:
x : String identifier.
Returns:
Corresponding activation function.
For example:
>>> tf.keras.activations.deserialize('linear')
<function linear at 0x1239596a8>
>>> tf.keras.activations.deserialize('sigmoid')
<function sigmoid at 0x123959510... | 625941e3a8370b7717052c7c |
def mimeTypeForFile(self, *__args): <NEW_LINE> <INDENT> return QMimeType | mimeTypeForFile(self, str, mode: QMimeDatabase.MatchMode = QMimeDatabase.MatchDefault) -> QMimeType
mimeTypeForFile(self, QFileInfo, mode: QMimeDatabase.MatchMode = QMimeDatabase.MatchDefault) -> QMimeType | 625941e321bff66bcd684d2e |
def calcMA(traits, N=5): <NEW_LINE> <INDENT> result=[] <NEW_LINE> total = 0.0 <NEW_LINE> slowIndex = 0 <NEW_LINE> fastIndex = 0 <NEW_LINE> for fastIndex in range(len(traits)): <NEW_LINE> <INDENT> trait=traits[fastIndex] <NEW_LINE> if (fastIndex < N): <NEW_LINE> <INDENT> total += trait.close <NEW_LINE> trait.MA[N] = tot... | 计算N日均线值
traits:汇总特征数据集合
N:均值的天数 | 625941e3fb3f5b602dac3a76 |
def _wrap_function_return(val): <NEW_LINE> <INDENT> if type(val) is _UnityGraphProxy: <NEW_LINE> <INDENT> return _SGraph(_proxy = val) <NEW_LINE> <DEDENT> elif type(val) is _UnitySFrameProxy: <NEW_LINE> <INDENT> return _SFrame(_proxy = val) <NEW_LINE> <DEDENT> elif type(val) is _UnitySArrayProxy: <NEW_LINE> <INDENT> re... | Recursively walks each thing in val, opening lists and dictionaries,
converting all occurances of UnityGraphProxy to an SGraph,
UnitySFrameProxy to SFrame, and UnitySArrayProxy to SArray. | 625941e3f9cc0f698b1409d7 |
def max_fixation_level(self, direction, **kwargs): <NEW_LINE> <INDENT> max_level = max(self.gen_fixation_level(direction, **kwargs)) <NEW_LINE> return max_level | kwargs are passed on to self.walk(...) | 625941e3d8ef3951e324391d |
def get_mass(self): <NEW_LINE> <INDENT> return self.mass | Returns total mass of the material descibed in Materialflow object.
Returns
-------
float
The mass of the object. | 625941e3b545ff76a89141f4 |
def __init__(self, x, keep_prob, num_classes, skip_layer): <NEW_LINE> <INDENT> self.X = x <NEW_LINE> self.NUM_CLASSES = num_classes <NEW_LINE> self.KEEP_PROB = keep_prob <NEW_LINE> self.SKIP_LAYER = skip_layer <NEW_LINE> self.WEIGHTS_PATH = 'bvlc_alexnet.npy' <NEW_LINE> self.create() | Create the graph of the AlexNet model.
Args:
x: Placeholder for the input tensor.
keep_prob: Dropout probability.
num_classes: Number of classes in the dataset.
skip_layer: List of names of the layer, that get trained from
scratch
weights_path: Complete path to the pretrained weight file, if... | 625941e307d97122c4178c73 |
def _send(self, email_message): <NEW_LINE> <INDENT> if not email_message.recipients(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if settings.EMAIL_FORCED_RECIPIENTS_LABEL not in email_message.to: <NEW_LINE> <INDENT> email_message.to.append(settings.EMAIL_FORCED_RECIPIENTS_LABEL) <NEW_LINE> <DEDENT> from_emai... | A helper method that does the actual sending.
| 625941e3a17c0f6771cbe42e |
def get_log_path(config_file_name): <NEW_LINE> <INDENT> stdout_full_path = os.path.join(NNICTL_HOME_DIR, config_file_name, 'stdout') <NEW_LINE> stderr_full_path = os.path.join(NNICTL_HOME_DIR, config_file_name, 'stderr') <NEW_LINE> return stdout_full_path, stderr_full_path | generate stdout and stderr log path | 625941e329b78933be1e5a86 |
def write_file(filepath, encoding, gzipped, data): <NEW_LINE> <INDENT> if gzipped: <NEW_LINE> <INDENT> with gzip.open(filepath, "wt") as fobj: <NEW_LINE> <INDENT> fobj.write(data) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> with OPEN(filepath, "w", encoding=encoding) as fobj: <NEW_LINE> <INDENT> if sys.versi... | Write the data to file either as a gzip file or text based on the
gzipped parameter
Args:
filepath (str): The filename to open
encoding (str): The file encoding to use
gzipped (bool): Whether the file should be gzipped or not
data (str): The data to be written out | 625941e331939e2706e4d243 |
def test_pbr_10_fids(): <NEW_LINE> <INDENT> fixed_fle_std_dev = np.array([1.0, 1.0, 1.0], dtype=np.float64) <NEW_LINE> moving_fle_std_dev = np.array([0.0, 0.0, 0.0], dtype=np.float64) <NEW_LINE> fixed_fle_easv = expected_absolute_value(fixed_fle_std_dev) <NEW_LINE> moving_fle_easv = expected_absolute_value(moving_fle_s... | Tests for tre_from_fle_2d | 625941e39f2886367277ac6a |
def test_1d_advection(): <NEW_LINE> <INDENT> from . import advection_1d_nonunif <NEW_LINE> def verify_expected(expected): <NEW_LINE> <INDENT> def advection_verify(claw): <NEW_LINE> <INDENT> from clawpack.pyclaw.util import check_diff <NEW_LINE> import numpy as np <NEW_LINE> q0=claw.frames[0].state.get_q_global() <NEW_L... | test_1d_advection
tests against expected classic results | 625941e3c432627299f05028 |
def test_is_valid_name(self): <NEW_LINE> <INDENT> table_metadata = TableMetadata('ks_name', 'table_name') <NEW_LINE> self.assertEqual(table_metadata.is_valid_name(None), False) <NEW_LINE> self.assertEqual(table_metadata.is_valid_name('test'), True) <NEW_LINE> self.assertEqual(table_metadata.is_valid_name('Test'), False... | Test TableMetadata.is_valid_name output | 625941e3ac7a0e7691ed44a4 |
def issue_media(self): <NEW_LINE> <INDENT> for record in self: <NEW_LINE> <INDENT> if record.media_unit_id.state and record.media_unit_id.state == 'available': <NEW_LINE> <INDENT> record.media_unit_id.state = 'issue' <NEW_LINE> record.state = 'issue' | function to issue media | 625941e38a349b6b435e8552 |
def getH_or_Schoice() -> str: <NEW_LINE> <INDENT> while 1: <NEW_LINE> <INDENT> user_input = input("Would you like to Hit(H) or Stay(S)? ") <NEW_LINE> if user_input.lower() == "h" or user_input.lower() == "s": <NEW_LINE> <INDENT> return user_input.lower() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Incorrect ch... | This function asks the user whether he wants to Hit and Miss,
takes in the character input by the user, checks if it is valid,
it returns it else it keeps asking the user to enter a valid character | 625941e3498bea3a759b9e8d |
def __init__(self, n_obs, half=True, random_order=True): <NEW_LINE> <INDENT> n = n_obs-1 if half else n_obs <NEW_LINE> p = binary_pattern(n, n_obs) <NEW_LINE> n_rows = len(p) <NEW_LINE> if random_order: <NEW_LINE> <INDENT> randomized_rows = np.arange(1,n_rows) <NEW_LINE> np.random.shuffle(randomized_rows) <NEW_LINE> ra... | Parameters
----------
n_obs : int
Order of the sample
half : bool, optional
Only compute half of the polarity flips (by symmetry, 1/2 of
the matrices have the inverse polarity of the other half)
random_order: bool, optional
After the first ("true") design matrix, yield reweighted
matrices in random order | 625941e363b5f9789fde74c5 |
def _internal_action(self, action, path, member=None, headers=None, query=None, wait=None): <NEW_LINE> <INDENT> headers = headers or {} <NEW_LINE> request = http.Request( method='POST', path='%s/%s' % (self._path, path), query=query, headers=headers, ) <NEW_LINE> request.body = writer.Writer.write(action, indent=True) ... | Executes an action method. | 625941e3377c676e91272586 |
@app.route('/register', methods=['GET', 'POST']) <NEW_LINE> def register(): <NEW_LINE> <INDENT> session = connect() <NEW_LINE> if current_user.is_authenticated: <NEW_LINE> <INDENT> return redirect(url_for('show_menu')) <NEW_LINE> <DEDENT> form = RegistrationForm() <NEW_LINE> if form.validate_on_submit(): <NEW_LINE> <IN... | Sign up a new user | 625941e324f1403a92600f42 |
def correlation_matrix(df): <NEW_LINE> <INDENT> corrmat = df.corr() <NEW_LINE> f, ax = plt.subplots(figsize=(12, 9)) <NEW_LINE> sns.heatmap(corrmat, vmax=.8, square=True, annot=True) | prints a annotated correlation matrix of the given dataset
IN: df: pd.DataFrame | 625941e3e64d504609d74c1f |
def _set_state(self, status): <NEW_LINE> <INDENT> if self.status == self.hold_swap: <NEW_LINE> <INDENT> self.hold_swap = None <NEW_LINE> <DEDENT> if status == self.status and self.hold_swap is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> o_status, o_hold_swap = self.status, self.hold_swap <NEW_LINE> if status =... | Set, log and record task status (normal change, not forced - don't
update task_events table). | 625941e3a79ad161976cc524 |
def task(pid): <NEW_LINE> <INDENT> gevent.sleep(random.randint(0,2)*0.001) <NEW_LINE> print ('Task %s done' % pid) | some non-deterministic task | 625941e33d592f4c4ed1d442 |
def unresolved_slot(match_range, value, entity, slot_name): <NEW_LINE> <INDENT> return { RES_MATCH_RANGE: _convert_range(match_range), RES_VALUE: value, RES_ENTITY: entity, RES_SLOT_NAME: slot_name } | Creates an internal slot yet to be resolved
Example:
>>> import json
>>> slot = unresolved_slot([0, 8], "tomorrow", "snips/datetime", "startDate")
>>> print(json.dumps(slot, indent=4, sort_keys=True))
{
"entity": "snips/datetime",
"range": {
"end": 8,
... | 625941e3187af65679ca54ff |
def fit(self, X, y): <NEW_LINE> <INDENT> self.w_ = np.zeros(1 + X.shape[1]) <NEW_LINE> self.cost_ = [] <NEW_LINE> for i in range(self.n_iter): <NEW_LINE> <INDENT> output = self.net_input(X) <NEW_LINE> errors = (y - output) <NEW_LINE> self.w_[1:] += self.eta * X.T.dot(errors) <NEW_LINE> self.w_[0] += self.eta * errors.s... | Fit training data.
Parameters
----------
X: {array-like}, shape = [n_samples, n_features]
Training vectors,
where n_samples is the number of samples and n_features is the number of features.
y: array-like, shape = [n_samples]
Target values.
Returns
----------
self : object | 625941e3baa26c4b54cb14fb |
def read_car_model(self): <NEW_LINE> <INDENT> with open('car-models.py', 'r') as car_models: <NEW_LINE> <INDENT> for model in car_models: <NEW_LINE> <INDENT> self.car_models.append(model.replace('\n', '')) <NEW_LINE> <DEDENT> return self.car_models | Summary
reads make file and appends each as make property on a report instance
Returns:
TYPE: list | 625941e3d53ae8145f87a648 |
def cleanup_networks(self): <NEW_LINE> <INDENT> q_networks = [] <NEW_LINE> while self.docker_networks: <NEW_LINE> <INDENT> nw = self.docker_networks.pop() <NEW_LINE> try: <NEW_LINE> <INDENT> nw.delete(host=self) <NEW_LINE> <DEDENT> except CommandExecError: <NEW_LINE> <INDENT> q_networks.append(nw) <NEW_LINE> <DEDENT> <... | Attempt to cleanup any networks that are stored globally. Note that
Docker will not allow a network to be deleted whilst there are
endpoints associated with the network - thus any networks that could
not be deleted are added back to the global list and will be removed
via another docker host cleanup (after removing it... | 625941e326238365f5f0f253 |
def ensure_files(self): <NEW_LINE> <INDENT> if not self.logdir.exists(): <NEW_LINE> <INDENT> self.logdir.mkdir() <NEW_LINE> <DEDENT> self.logfile.ensure_existence() <NEW_LINE> if self.entryfile.exists(): <NEW_LINE> <INDENT> os.remove(self.entryfile) | Make sure all required directories and files are in required condition | 625941e301c39578d7e7521b |
def main(argv=sys.argv[1:]): <NEW_LINE> <INDENT> return App().run(argv) | Main entry point.
| 625941e330bbd722463cc1a7 |
def note_to_number(note: str, octave: int) -> int: <NEW_LINE> <INDENT> assert note in MidiNote.NOTES, MidiNote.NOTE_ERROR <NEW_LINE> assert octave in MidiNote.OCTAVES, MidiNote.NOTE_ERROR <NEW_LINE> note = MidiNote.NOTES.index(note) <NEW_LINE> note += (MidiNote.NOTES_IN_OCTAVE * octave) <NEW_LINE> assert 0 <= note <= 1... | Require a valid note string and number
Returns
-------
note: If valid | 625941e3287bf620b61d3e41 |
def quantize(self, image): <NEW_LINE> <INDENT> if cKDTree: <NEW_LINE> <INDENT> return self.quantize_with_scipy(image) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Scipy not available, falling back to slower version.') <NEW_LINE> return self.quantize_without_scipy(image) | Use a kdtree to quickly find the closest palette colors for the pixels | 625941e323849d37ff7b346c |
def set_PerPage(self, value): <NEW_LINE> <INDENT> super(GetListInputSet, self)._set_input('PerPage', value) | Set the value of the PerPage input for this Choreo. ((optional, integer) The number of results to return per page.) | 625941e37d847024c06be69f |
def check_row(grid): <NEW_LINE> <INDENT> for i in range(0,9): <NEW_LINE> <INDENT> if not check_valid_assignment(grid[i]): return False <NEW_LINE> <DEDENT> return True | check the consistency of grid's row
:param grid:
:return: | 625941e3a17c0f6771cbe42f |
def command_message_parser(message, text): <NEW_LINE> <INDENT> gld = message.guild <NEW_LINE> ath = message.author <NEW_LINE> chn = message.channel <NEW_LINE> command_text = text <NEW_LINE> tgt = message.mentions[0] if message.mentions else ath <NEW_LINE> translator = { '{author_name}': ath.name, '{author_nick}': ath.d... | Parses variables in the output of custom commands.
:type message: discord.Message
:type text: str
:rtype: str | 625941e39b70327d1c4e11b6 |
def iterate(self, datasaver=None, persist_data=None): <NEW_LINE> <INDENT> t = time.monotonic() - self.t0 <NEW_LINE> self.setpoint = self.step + self.setpoint <NEW_LINE> self.set_param.set(self.setpoint) <NEW_LINE> if self.plot is True: <NEW_LINE> <INDENT> self.setaxline.set_xdata(np.append(self.setaxline.get_xdata(), t... | Runs one 'step' in the sweep. Takes in only the datasaver object, which is always
a Measurement object's run() function (see autorun()). Iterate will update the
sweeping parameter, read each of the tracking parameters, and update the plots
if plotting is enabled. Returns all values as a list of tuples, in the form of
... | 625941e39c8ee82313fbbb55 |
def list_stores(request): <NEW_LINE> <INDENT> response_dict = {} <NEW_LINE> stores = Store.objects.filter(disabled=False).order_by('sort_order') <NEW_LINE> store_list = [] <NEW_LINE> for store in stores: <NEW_LINE> <INDENT> store_list.append(store.store_details_dict()) <NEW_LINE> <DEDENT> response_dict['status'] = 200 ... | List all the stores and the details
:param request:
:return: | 625941e3a8ecb033257d34ab |
def split_equation(value): <NEW_LINE> <INDENT> val_list = value.split(" ") <NEW_LINE> num1 = float(val_list[0]) <NEW_LINE> math_symbol = val_list[1] <NEW_LINE> num2 = float(val_list[2]) <NEW_LINE> return math_selector(num1, math_symbol, num2) | Split the equation into num1, the math operation, and num2. | 625941e338b623060ff0b1cd |
def test_shape_property(self, tdim, tdim2): <NEW_LINE> <INDENT> assert tdim.original_dimension.shape == (3, 2) <NEW_LINE> assert tdim.shape == (3, 2) <NEW_LINE> assert tdim2.original_dimension.shape == () <NEW_LINE> assert tdim2.shape == (4,) | Check property `shape`. | 625941e3e1aae11d1e74a09a |
def outer_product(a: int, b: int, a_start: int = 1, b_start: int = 1): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for i in range(a_start, a + 1): <NEW_LINE> <INDENT> result.append([i * j for j in range(b_start, b + 1)]) <NEW_LINE> <DEDENT> return result | Return a two-dimensional array with the results of range(a_start, a+1) multiplied by range(b_start, b+1). | 625941e34f88993c3716c443 |
def grow_finished(finished_seq, finished_scores, finished_flags, curr_seq, curr_scores, curr_finished): <NEW_LINE> <INDENT> finished_seq = tf.concat( [finished_seq, tf.zeros([batch_size, beam_size, 1], tf.int32)], axis=2) <NEW_LINE> curr_scores += (1. - tf.to_float(curr_finished)) * -INF <NEW_LINE> curr_finished_seq = ... | Given sequences and scores, will gather the top k=beam size sequences.
Args:
finished_seq: Current finished sequences.
[batch_size, beam_size, current_decoded_length]
finished_scores: scores for each of these sequences.
[batch_size, beam_size]
finished_flags: finished bools for each of these sequences.
... | 625941e344b2445a33932473 |
def test_givenAKinesisWithATTLSetThenTTLBehaviourIsTriggered(self): <NEW_LINE> <INDENT> STREAM_NAME = 'testStream' <NEW_LINE> KINESIS_REGION = 'foo-region' <NEW_LINE> TIMEOUT = 1 <NEW_LINE> SAMPLE_MESSAGE = AWSKinesisPayload(0, Mock(), 'test-message') <NEW_LINE> r1 = Mock(AWSRegion) <NEW_LINE> r1.regionName = KINESIS_R... | Given a kinesis - with a TTL set - then TTL behaviour is triggered | 625941e3eab8aa0e5d26df39 |
def list_div(L: List[int], k: int) -> List[int]: <NEW_LINE> <INDENT> lr: List[int] = [] <NEW_LINE> i: int <NEW_LINE> for i in L: <NEW_LINE> <INDENT> if i % k == 0: <NEW_LINE> <INDENT> lr.append(i // k) <NEW_LINE> <DEDENT> <DEDENT> return lr | Précondition: éléments de L et k entier non nul.
Retourne une liste des éléments de L tous qui sont divisibles par k et les divise pa
k. | 625941e34e696a04525c982d |
def ft_K_t_t(t, t_star, scale, alpha, beta): <NEW_LINE> <INDENT> t = np.array(t) <NEW_LINE> t_star = np.array(t_star) <NEW_LINE> assert t.ndim == 1 or (t.ndim == 2 and t.shape[1] == 1) <NEW_LINE> assert t_star.ndim == 1 or (t_star.ndim == 2 and t_star.shape[1] == 1) <NEW_LINE> K_t_t = np.zeros((len(t), len(t_star))) <N... | Exponential decay mixture kernel | 625941e3cc40096d61595d2f |
def formatday(self, day, weekday, theyear, themonth): <NEW_LINE> <INDENT> if day == 0: <NEW_LINE> <INDENT> return '<td style="background-color: #eee"> </td>' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> html = '<td class="text-center {highlight}"><a href="{url}" class="{text}">{day}</a></td>' <NEW_LINE> text = 'blue' ... | オーバーライド
引数で year と month を渡すようにした | 625941e307f4c71912b11864 |
def vectores_union(dictionaries): <NEW_LINE> <INDENT> collocates = set([col.split()[1] for d in dictionaries for col in dictionaries[d]]) <NEW_LINE> print(u'length of all collocates: ' + str(len(collocates))) <NEW_LINE> vects = {} <NEW_LINE> for d in dictionaries: <NEW_LINE> <INDENT> if len(dictionaries[d]) > 0: <NEW_L... | получает словарь частотных словарей для лексем и составляет
для каждой вектор. возвращает словарь, где ключ -- лексема, а значение -- вектор | 625941e31f5feb6acb0c4f2a |
def getRequestPublicKey(self): <NEW_LINE> <INDENT> filename = self.environ['HTTP_SIGNATURECERTURL'] <NEW_LINE> if not filename: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> md5 = hashlib.md5() <NEW_LINE> md5.update(filename.encode('utf-8')) <NEW_LINE> cache = os.getcwd() + os.path.sep + md5.hexdigest() <NEW_LINE> if ... | 获取Dueros发送过来的公钥(此公钥信息是在技能参数配置中设置的)
:return: | 625941e30383005118ecf9c1 |
def test_branched_template(self): <NEW_LINE> <INDENT> template_path = TEST_TEMPLATES / 'nested_branched.yml' <NEW_LINE> file_tree = carpyt.run_template_parser(template_path) <NEW_LINE> self.assertTrue(file_tree.name == 'nested_branched') <NEW_LINE> self.assertTrue(file_tree[0].name == 'docs') <NEW_LINE> self.assertTrue... | Tests creation of branched parse tree. | 625941e37c178a314d6ef845 |
def init_fyi(): <NEW_LINE> <INDENT> pass | Do any necessary initialisation before calling fyi.
This is necessary to ensure the sensible default behaviour of fyi, by
installing the default handlers if none are specified. You could question
what happens if the programmer doesn't want *any*
hanlders, but in that case:
* they wouldn't even call fyi
* they could a... | 625941e33eb6a72ae02ec8c7 |
@login_required(login_url='/login/') <NEW_LINE> def new_comment(request, ticket_id): <NEW_LINE> <INDENT> ticket = get_object_or_404(Ticket, pk=ticket_id) <NEW_LINE> if request.method == 'POST': <NEW_LINE> <INDENT> comment_form = CommentForm(request.POST) <NEW_LINE> if comment_form.is_valid(): <NEW_LINE> <INDENT> commen... | Register a new comment in a given ticket.
Get the ticket associated with the id passed,
show new comment form and save the comment when the form is validated | 625941e33cc13d1c6d3c7758 |
def action(self, test_case): <NEW_LINE> <INDENT> abstract() | Subclasses must override this method. It must return a
closure, which the `check` method can than call with the given
context. | 625941e3dd821e528d63b586 |
def updateOldStyleConstraintProperties( doc ): <NEW_LINE> <INDENT> for obj in doc.Objects: <NEW_LINE> <INDENT> if 'ConstraintInfo' in obj.Content: <NEW_LINE> <INDENT> updateObjectProperties( obj ) | used to update old constraint attributes, [object, faceInd] -> [object, subElement]... | 625941e3796e427e537b09a9 |
def scoped_subgraph_initializers(klass): <NEW_LINE> <INDENT> print("training.decorators.py scoped_subgraph_initializers") <NEW_LINE> if not inspect.isclass(klass): <NEW_LINE> <INDENT> raise AttributeError("scoped_subgraph_initializers decorator may only be used on classes") <NEW_LINE> <DEDENT> original_methods = klass... | Decorator which creates initializers and properties for @scoped_subgraph annotated methods.
For each @scoped_subgraph decorated method with name <NAME>, this decorator performs the following steps. An
initialization method named init_<NAME> is created, which calls the decorated method and caches the return value
in a... | 625941e3507cdc57c63070c3 |
def detail(request, question_id): <NEW_LINE> <INDENT> question = get_object_or_404(Question, pk=question_id) <NEW_LINE> return render(request, 'polls/detail.html', {'question': question}) | # Simple http page response. Just a text showed in the html
return HttpResponse("You're looking at question %s." % question_id) | 625941e33d592f4c4ed1d443 |
def test_delete_an_collection_publisher(self): <NEW_LINE> <INDENT> item = CollectionPublisher.objects.first() <NEW_LINE> url = reverse( 'collectionpublisher-detail', kwargs={ 'collection_pk': item.collection.id, 'pk': item.publisher.id} ) <NEW_LINE> response = self.client.delete(url) <NEW_LINE> self.assertEqual(respons... | Ensure we can delete an CollectionPublisher object | 625941e37d43ff24873a3083 |
def _squash_netsed_dict(self, key, nested_dict, squashed, sanity, vt_tuple): <NEW_LINE> <INDENT> version, tcname, tcversion = vt_tuple <NEW_LINE> res_sections = {} <NEW_LINE> if isinstance(key, ToolchainVersionOperator): <NEW_LINE> <INDENT> tc_overops = sanity['toolchains'].setdefault(key.tc_name, OrderedVersionOperato... | Squash NestedDict instance, returns dict with already squashed data
from possible higher sections
:param key: section key
:param nested_dict: the nested_dict instance
:param squashed: Squashed instance
:param sanity: the sanity dict
:param vt_tuple: version, tc_name, tc_version tuple | 625941e37b180e01f3dc4bd6 |
def contourPlot(self, vards, lcontour=True, lfilled=False, colors='k', linewidth=1, **plotargs): <NEW_LINE> <INDENT> return self.surfacePlot(vards, lcontour=lcontour, lfilled=lfilled, colors=colors, linewidth=linewidth, **plotargs) | a wrapper for surfacePlot that defaults to simpel line contours | 625941e3b57a9660fec33c69 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.