code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def ensure_vector(data, size=None): <NEW_LINE> <INDENT> if isinstance(data, (list, tuple)): <NEW_LINE> <INDENT> data = np.array(data) <NEW_LINE> <DEDENT> elif not isinstance(data, np.ndarray): <NEW_LINE> <INDENT> data = np.array([data]) <NEW_LINE> <DEDENT> assert data.ndim == 1 <NEW_LINE> if len(data) == 1 and size is ... | Ensure data is a 1D vector. | 625941f382261d6c526aba9b |
@register.inclusion_tag('ooyala/tags/thumbnail_list.html') <NEW_LINE> def ooyala_channel_more(video): <NEW_LINE> <INDENT> if video.content_type == 'Channel': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> channel = OoyalaChannelList.objects.get(channel=video) <NEW_LINE> similiar_list = channel.videos.all() <NEW_LINE> <DE... | Returns more OoyalaItems which are in the same channel
as our current video. Takes the first channel it finds for now.
If we get a channel as an item then return all its videos. | 625941f37d847024c06be8b3 |
@tf_export('rpc') <NEW_LINE> def rpc(address, method, request, protocol="", fail_fast=True, timeout_in_ms=0, name=None): <NEW_LINE> <INDENT> _ctx = _context._context <NEW_LINE> if _ctx is None or not _ctx._eager_context.is_eager: <NEW_LINE> <INDENT> if protocol is None: <NEW_LINE> <INDENT> protocol = "" <NEW_LINE> <DED... | TODO: add doc.
Args:
address: A `Tensor` of type `string`.
method: A `Tensor` of type `string`.
request: A `Tensor` of type `string`.
protocol: An optional `string`. Defaults to `""`.
fail_fast: An optional `bool`. Defaults to `True`.
timeout_in_ms: An optional `int`. Defaults to `0`.
name: A name for th... | 625941f3379a373c97cfb139 |
def _parse_reference_loci( ref_align ): <NEW_LINE> <INDENT> loci = {} <NEW_LINE> for record in BlasrReader( ref_align ): <NEW_LINE> <INDENT> typing = HlaType.from_string( record.tname ) <NEW_LINE> loci[record.qname] = typing.gene <NEW_LINE> <DEDENT> return loci | Identify the loci associated with each reference sequence | 625941f38c3a8732951589b4 |
def get_raw_data(url, *args, **kwargs): <NEW_LINE> <INDENT> res = requests.get(url, headers=_prepare_headers(**kwargs)) <NEW_LINE> if res.status_code == 200: <NEW_LINE> <INDENT> return res.content <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Gets data from url as bytes
Returns content under the provided url as bytes
ie. for binary data
Args:
**url**: address of the wanted data
.. versionadded:: 0.3.2
**additional_headers**: (optional) Additional headers
to be used with request
Returns:
bytes | 625941f3507cdc57c63072dc |
def handle_sources(data, site_yaml_abspath, _ctx): <NEW_LINE> <INDENT> hosts_abspath = os.path.join(os.path.dirname(site_yaml_abspath), HOSTS) <NEW_LINE> if isinstance(data, dict): <NEW_LINE> <INDENT> data = handle_key_data( data, get_instance(_ctx).runtime_properties[WORKSPACE]) <NEW_LINE> if os.path.exists(hosts_absp... | Allow users to provide a path to a hosts file
or to generate hosts dynamically,
which is more comfortable for Cloudify users.
:param data: Either a dict (from YAML)
or a path to a conventional Ansible file.
:param site_yaml_abspath: This is the path to the site yaml folder.
:param _ctx: The Cloudify context.
:retu... | 625941f38c0ade5d55d3efb2 |
def clear_history(self): <NEW_LINE> <INDENT> if self._history is None: <NEW_LINE> <INDENT> raise HistoryIsNone("You must set history if you need to use historic methods") <NEW_LINE> <DEDENT> self._history.clear_history() | Re initialise the history
| 625941f34527f215b584ca43 |
def check_duplicate(data, name): <NEW_LINE> <INDENT> key_cols = ['Agency_Code', 'Respondent_ID', 'As_of_Year'] if name == 'institutions' else ['Agency_Code', 'Respondent_ID', 'As_of_Year', 'Sequence_Number'] <NEW_LINE> data_unique_count = data[key_cols].count().reset_index() <NEW_LINE> columns = data_unique_coun... | Checks for duplicate records in the passed DataFrame
:param df:
:return: | 625941f3f548e778e58cdb72 |
def performGameCycle(self): <NEW_LINE> <INDENT> if not self.displayedMessage: <NEW_LINE> <INDENT> controller = MessageBoxController(self.message, self.lastScreen, autoClose=True) <NEW_LINE> self.screen.messageBox = controller.screen.messageBox <NEW_LINE> self.runController(controller) <NEW_LINE> self.displayedMessage =... | Perform the learn attack loop | 625941f350812a4eaa59c90d |
def __init__(self): <NEW_LINE> <INDENT> DB.__init__(self, "ComponentMonitoringDB", "Framework/ComponentMonitoringDB") <NEW_LINE> retVal = self.__initializeDB() <NEW_LINE> if not retVal["OK"]: <NEW_LINE> <INDENT> raise Exception("Can't create tables: %s" % retVal["Message"]) <NEW_LINE> <DEDENT> self.__optionalFields = (... | c'tor
Initialize the DB | 625941f3627d3e7fe0d69444 |
def make_album(artist, album, track = "unknown"): <NEW_LINE> <INDENT> info = {'musician':artist, 'work':album} <NEW_LINE> if tracks: <NEW_LINE> <INDENT> info = {'musician':artist, 'work':album, 'number_of_tracks':track} <NEW_LINE> <DEDENT> return info | make a dictionary of artists and their albums | 625941f34d74a7450ccd47b7 |
def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('post_list') | After recreating an instance of the comment, the
user should be redirected to the post_list page. | 625941f326238365f5f0f468 |
def do_all(self, line): <NEW_LINE> <INDENT> args = split(line) <NEW_LINE> data = storage.all() <NEW_LINE> list_instances = [] <NEW_LINE> if len(line) < 1: <NEW_LINE> <INDENT> for key, value in data.items(): <NEW_LINE> <INDENT> list_instances.append(str(value)) <NEW_LINE> <DEDENT> print(list_instances) <NEW_LINE> <DEDEN... | Prints all string representation instances
if you type "all" without arguments print all instances
if you type "all" + class name, print all instances of the class
| 625941f3b5575c28eb68e5f8 |
def add_task(self, task, priority): <NEW_LINE> <INDENT> if isinstance(priority, str): <NEW_LINE> <INDENT> raise DataTypeException( "Priority must be a number - string entered.") <NEW_LINE> <DEDENT> if task in self.entry_finder: <NEW_LINE> <INDENT> raise PriorityQueueDuplicateTaskException( "Duplicate task entered into ... | Adds a task to existing priority queue. | 625941f3a4f1c619b28b061c |
def add_node(self, node_name, graph=None): <NEW_LINE> <INDENT> if not graph: <NEW_LINE> <INDENT> graph = self.graph <NEW_LINE> <DEDENT> if node_name in graph: <NEW_LINE> <INDENT> raise KeyError('node %s already exists' % node_name) <NEW_LINE> <DEDENT> graph[node_name] = set() <NEW_LINE> self.__cached_graph = None | Add a node if it does not exist yet, or error out. | 625941f385dfad0860c3b44f |
def post(self, airlog_id): <NEW_LINE> <INDENT> airlog = models.AirLog.query.get(airlog_id) <NEW_LINE> if not airlog: <NEW_LINE> <INDENT> abort(404, success=False, message="AirLog entry not found") <NEW_LINE> <DEDENT> form = AirLogEditForm(meta={'csrf': False}) <NEW_LINE> airtime = form.airtime.data <NEW_LINE> if len(ai... | Modify an existing logged AirLog entry
---
operationId: modifyAirLog
tags:
- trackman
- airlog
parameters:
- in: path
name: airlog_id
type: integer
required: true
description: AirLog ID
- in: form
name: airtime
type: string
description: Air time
- in: form
name: logtype
type: integer
description: Lo... | 625941f36e29344779a62c03 |
def execute_query(query, data, get_results=True): <NEW_LINE> <INDENT> cursor, connection = open_db_connection() <NEW_LINE> cursor.execute(sql.SQL(query), data) <NEW_LINE> if get_results: <NEW_LINE> <INDENT> results = cursor.fetchall() <NEW_LINE> close_db_connection(cursor, connection) <NEW_LINE> return results <NEW_LIN... | execute query and return results. This is a compact version of the built in SQL function.
This is also accessible through imports from other files. | 625941f3ab23a570cc25077a |
def __init__(self, private_key=None, public_key=None, data=None, serializer=pickle, AES_bytes=32): <NEW_LINE> <INDENT> self.private_key = private_key <NEW_LINE> self.public_key = public_key <NEW_LINE> private_crypto = PKCS1_OAEP.new(private_key) <NEW_LINE> public_crypto = PKCS1_OAEP.new(public_key) <NEW_LINE> self.seri... | Create a dictionary-like object with RSA+AES encryption of it's data
(NOTE: keys are in plaintext, data is serialized using the provided
serializer). In order to fill the object with data, a `public_key`
must be provided. In order to read from the object, a `private_key`
must be provided. | 625941f3a219f33f34628f53 |
def time_evaluator(self, func_name, ctx, number=10, repeat=1, min_repeat_ms=0): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> feval = _RPCTimeEvaluator( self, func_name, ctx.device_type, ctx.device_id, number, repeat, min_repeat_ms) <NEW_LINE> def evaluator(*args): <NEW_LINE> <INDENT> blob = feval(*args) <NEW_LINE> fmt ... | Get an evaluator that measures time cost of running function.
Parameters
----------
func_name: str
The name of the function in the module.
ctx: TVMContext
The context we should run this function on.
number: int
The number of times to run this function for taking average.
We call these runs as one `re... | 625941f3fff4ab517eb2fa32 |
def pacmanSuccessorStateAxioms(x, y, t, walls_grid): <NEW_LINE> <INDENT> listlit = [] <NEW_LINE> actions = ['South', 'North', 'West', 'East'] <NEW_LINE> xs = [x, x, x + 1, x - 1] <NEW_LINE> ys = [y + 1, y - 1, y, y] <NEW_LINE> for i in range(len(actions)): <NEW_LINE> <INDENT> if not walls_grid[xs[i]][ys[i]]: <NEW_LINE>... | Successor state axiom for state (x,y,t) (from t-1), given the board (as a
grid representing the wall locations).
Current <==> (previous position at time t-1) & (took action to move to x, y) | 625941f35e10d32532c5f517 |
def client(ip,port,message): <NEW_LINE> <INDENT> s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) <NEW_LINE> s.connect((ip,port)) <NEW_LINE> try: <NEW_LINE> <INDENT> s.sendall(message.encode()) <NEW_LINE> response = s.recv(1024).decode() <NEW_LINE> print(response) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> s.... | 设备接入函数 | 625941f315fb5d323cde110b |
def __init__(self, path, exts, fields, load_dataset=False, save_dataset=False, prefix='', **kwargs): <NEW_LINE> <INDENT> if not isinstance(fields[0], (tuple, list)): <NEW_LINE> <INDENT> fields = [('src', fields[0]), ('trg', fields[1])] <NEW_LINE> <DEDENT> src_path, trg_path = tuple(os.path.expanduser(path + x) for x in... | Create a TranslationDataset given paths and fields.
Arguments:
path: Common prefix of paths to the data files for both languages.
exts: A tuple containing the extension to path for each language.
fields: A tuple containing the fields that will be used for data
in each language.
Remaining keywor... | 625941f3fff4ab517eb2fa33 |
def check(self, key: KeyT) -> int: <NEW_LINE> <INDENT> idx_1, idx_2, fingerprint = self._generate_fingerprint_info(key) <NEW_LINE> is_present = self._check_if_present(idx_1, idx_2, fingerprint) <NEW_LINE> val = 0 <NEW_LINE> if is_present is not None: <NEW_LINE> <INDENT> for bucket in self.buckets[is_present]: <NEW_LINE... | Check if an element is in the filter
Args:
key (str): Element to check
Returns:
int: The number of times inserted into the filter | 625941f399cbb53fe67931d7 |
def add_data_files(*include_dirs): <NEW_LINE> <INDENT> data_files = [] <NEW_LINE> for include_dir in include_dirs: <NEW_LINE> <INDENT> for root, directories, filenames in os.walk(include_dir): <NEW_LINE> <INDENT> include_files = [] <NEW_LINE> for filename in filenames: <NEW_LINE> <INDENT> include_files.append(os.path.j... | called from setup.py to include auxillary files for installation | 625941f3cc0a2c11143dd484 |
def failure_key(self): <NEW_LINE> <INDENT> timestamp = datetime.utcnow() <NEW_LINE> failure_id = uuid4().get_hex() <NEW_LINE> timestamp = timestamp.isoformat().split('.')[0] <NEW_LINE> return self.r_key(".".join(("failure", timestamp, failure_id))) | Construct a failure key. | 625941f32eb69b55b151ceab |
def optimize(self,x): <NEW_LINE> <INDENT> raise NotImplementedError | optimizes a sequence of actions starting from state x
stores the optimal sequence internally | 625941f3a17c0f6771cbe641 |
def p_TypeDeclaration(p): <NEW_LINE> <INDENT> p[0] = p[1:] | TypeDeclaration : ClassHeader '{' FieldDeclarations '}'
| ClassHeader '{' '}' | 625941f3d53ae8145f87a856 |
def process_request(self, make_request: Callable, method: str, params: List) -> Dict: <NEW_LINE> <INDENT> result = make_request(method, params) <NEW_LINE> if method in ("eth_call", "eth_estimateGas"): <NEW_LINE> <INDENT> if "error" in result: <NEW_LINE> <INDENT> raise ValueError(result["error"]) <NEW_LINE> <DEDENT> <DE... | Raise a ValueError when RPC.eth_call or RPC.eth_estimateGas errors. | 625941f3cdde0d52a9e5362b |
def jsonify(obj, status=200, headers=None): <NEW_LINE> <INDENT> jsondata = json.dumps(obj, cls=JSONEncoder) <NEW_LINE> if 'callback' in request.args: <NEW_LINE> <INDENT> jsondata = '%s(%s)' % (request.args.get('callback'), jsondata) <NEW_LINE> <DEDENT> return Response(jsondata, headers=headers, status=status, mimetype=... | Custom JSONificaton to support obj.to_dict protocol. | 625941f3a8ecb033257d36bd |
def _to_bits(self): <NEW_LINE> <INDENT> if self._last_bits: <NEW_LINE> <INDENT> bits = [b for b in self._last_bits] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bits = ['0']*self._length <NEW_LINE> <DEDENT> for name in self: <NEW_LINE> <INDENT> pos = self[name].positions <NEW_LINE> n = self[name].size <NEW_LINE> value... | Generate bit string from configuration. | 625941f38a349b6b435e8765 |
def get_mutation_covariate(coefs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return ('log10_mut' in list(zip(*coefs))[0]) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return False | Check if the mutation covariate is nonzero | 625941f376e4537e8c351c6b |
def _installVBoxOnLinux(self): <NEW_LINE> <INDENT> sRun = self._findFile('^VirtualBox-.*\\.run$'); <NEW_LINE> if sRun is None: <NEW_LINE> <INDENT> return False; <NEW_LINE> <DEDENT> utils.chmodPlusX(sRun); <NEW_LINE> fRc, _ = self._sudoExecuteSync([sRun,]); <NEW_LINE> return fRc; | Installs VBox on Linux. | 625941f34c3428357757c916 |
def getCounty_surveys(FIP): <NEW_LINE> <INDENT> SSA = "{}{}".format(FIP_2_abbr(FIP), FIP[2:5]) <NEW_LINE> tblA = "legend" <NEW_LINE> tblB = "laoverlap" <NEW_LINE> aSymbol = "areasymbol" <NEW_LINE> cond1 = "{}.lkey = {}.lkey".format(tblA, tblB) <NEW_LINE> cond2 = "{}.{} = '{}'".format(tblB, aSymbol, SSA) <NEW_LINE> sJoi... | Create SQL query for survey areasymbol (SSA) based on formated FIP | 625941f3435de62698dfe240 |
def _get_vertex_formats(vertex_formats_data, bufs): <NEW_LINE> <INDENT> def get_gl_type_size(gl_type): <NEW_LINE> <INDENT> return hienoi._numeric.get_type_size(hienoi._numeric.from_gl(gl_type)) <NEW_LINE> <DEDENT> def gl_to_numpy_type(gl_type): <NEW_LINE> <INDENT> return hienoi._numeric.to_numpy(hienoi._numeric.from_gl... | Retrieve the OpenGL vertex formats. | 625941f3a8370b7717052e90 |
def __init__(self): <NEW_LINE> <INDENT> self.ApplicationId = None <NEW_LINE> self.UserName = None <NEW_LINE> self.NickName = None <NEW_LINE> self.CreateTime = None <NEW_LINE> self.UpdateTime = None | :param ApplicationId: 应用Id
:type ApplicationId: str
:param UserName: 用户名
:type UserName: str
:param NickName: 昵称
:type NickName: str
:param CreateTime: 创建时间
:type CreateTime: str
:param UpdateTime: 修改时间
:type UpdateTime: str | 625941f34e4d5625662d49c1 |
def test_advection_1d(): <NEW_LINE> <INDENT> u = np.array([1, 2, 3]) * units('m/s') <NEW_LINE> s = np.array([1, 2, 3]) * units('Pa') <NEW_LINE> a = advection(s, u, (1 * units.meter,), dim_order='xy') <NEW_LINE> truth = np.array([-1, -2, -3]) * units('Pa/sec') <NEW_LINE> assert_array_equal(a, truth) | Test advection calculation with varying wind and field. | 625941f3e76e3b2f99f3adf4 |
def test_create_create(self): <NEW_LINE> <INDENT> result = self.handler.create_or_update_site() | run the create -c command
| 625941f34a966d76dd551609 |
def get_code(self): <NEW_LINE> <INDENT> if not self.loaded: <NEW_LINE> <INDENT> self.load() <NEW_LINE> <DEDENT> return self.code | Return the code object associated to the method
:rtype: :class:`DalvikCode` object | 625941f31d351010ab85610d |
def loop0_agriculture(self, alone=False): <NEW_LINE> <INDENT> self.al[0] = self.ali <NEW_LINE> self.pal[0] = self.pali <NEW_LINE> self.uil[0] = self.uili <NEW_LINE> self.lfert[0] = self.lferti <NEW_LINE> self.ai[0] = 5e9 <NEW_LINE> self.pfr[0] = 1 <NEW_LINE> if alone: <NEW_LINE> <INDENT> self.loop0_exogenous() <NEW_LIN... | Run a sequence to initialize the population sector (loop with k=0).
Parameters
----------
alone : boolean, optional
if True, run the sector alone with exogenous inputs. The default
is False. | 625941f3498bea3a759ba0a0 |
def _stride_size(node, name_to_node): <NEW_LINE> <INDENT> if node.op == "MaxPoolV2": <NEW_LINE> <INDENT> strides_input_name = node.input[2] <NEW_LINE> if not strides_input_name.endswith("/strides"): <NEW_LINE> <INDENT> raise ValueError("Strides name does not end with '/strides'") <NEW_LINE> <DEDENT> strides_node = name... | Computes stride size given a TF node.
Args:
node: Tensorflow node (NodeDef proto).
name_to_node: For MaxPoolV2, mapping from variable name Tensorflow node.
Returns:
stride_x: Stride size for horizontal direction (integer).
stride_y: Stride size for vertical direction (integer).
Raises:
ValueError: If strid... | 625941f3d164cc6175783341 |
def setLicenseUrl(license): <NEW_LINE> <INDENT> pass | Set the URL of the license under which this file is released. | 625941f3009cb60464c6399f |
def _set_default_options(self): <NEW_LINE> <INDENT> self.module_names = self._set_option(self.config.module_names) <NEW_LINE> all_ancestors = self._set_option(self.config.all_ancestors) <NEW_LINE> all_associated = self._set_option(self.config.all_associated) <NEW_LINE> anc_level, association_level = (0, 0) <NEW_LINE> i... | set different default options with _default dictionary | 625941f3cad5886f8bd275cb |
def get_dataset_ids_by_task(task): <NEW_LINE> <INDENT> if task not in SUPPORTED_TASKS: <NEW_LINE> <INDENT> raise ValueError('Unsupported task: {}\nSupported tasks: {}' .format(task, SUPPORTED_TASKS)) <NEW_LINE> <DEDENT> tasks = openml.tasks.list_tasks() <NEW_LINE> tasks_df = pd.DataFrame.from_dict(tasks, orient='index'... | Get the ids of all openml datasets that have the specified task type | 625941f315baa723493c456d |
def configure_training(opt, lr, clip_grad, lr_decay, batch_size): <NEW_LINE> <INDENT> assert opt in ['adam'] <NEW_LINE> opt_kwargs = {} <NEW_LINE> opt_kwargs['lr'] = lr <NEW_LINE> train_params = {} <NEW_LINE> train_params['optimizer'] = (opt, opt_kwargs) <NEW_LINE> train_params['clip_grad_norm'] = clip_grad <NEW_L... | supports Adam optimizer only | 625941f37d847024c06be8b4 |
def refresh_lists(self, migration): <NEW_LINE> <INDENT> self._migration, base_lineno = migration, -1 <NEW_LINE> self.current_list.clear() <NEW_LINE> for lineno in sorted(migration.keys()): <NEW_LINE> <INDENT> linenostr = 'L{line_number}\n'.format(line_number=str(lineno + 1)) <NEW_LINE> data = migration[lineno] <NEW_LIN... | Refresh the list of code suggestions. | 625941f3f7d966606f6aa5fe |
def __init__( self, size, fmt="{dire}{debug}Result-{date}{second}-{ctr:03}.pkl", log=print, ): <NEW_LINE> <INDENT> self.size = size <NEW_LINE> self.fmt = fmt <NEW_LINE> self.log = log <NEW_LINE> self.name = utils.name_function <NEW_LINE> self.content = [[] for i in range(size)] <NEW_LINE> self.update() | Initialize a result handler. | 625941f36e29344779a62c04 |
def testGenerateSamplesRuntimeAndTimestamps(self): <NEW_LINE> <INDENT> timer = timing_util.IntervalTimer() <NEW_LINE> with timer.Measure('First'): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> with timer.Measure('Second'): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> start0 = timer.intervals[0][1] <NEW_LINE> stop0 = tim... | Test generating both runtime and timestamp samples. | 625941f36fece00bbac2dd39 |
def lower_bound(self, *args): <NEW_LINE> <INDENT> return _pyBasePython.mapUCUC_lower_bound(self, *args) | lower_bound(self, key_type x) -> iterator | 625941f3f548e778e58cdb73 |
def filter_files(files: Iterable[str], file_patterns: Patterns) -> Iterable[str]: <NEW_LINE> <INDENT> if VERBOSE: <NEW_LINE> <INDENT> print("Filtering with these file patterns: {}".format(file_patterns)) <NEW_LINE> <DEDENT> for file in files: <NEW_LINE> <INDENT> if not any(n.match(file) for n in file_patterns.negative)... | Returns all files that match any of the patterns. | 625941f3be383301e01b5a6c |
def business_donate(user_pk, business_pk, charity_pk, amount_bigint, txid_hash): <NEW_LINE> <INDENT> ctx = GetContext() <NEW_LINE> info = Get(ctx, txid_hash) <NEW_LINE> if info is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> promised = info[4] <NEW_LINE> if promised > 0: <NEW_LINE> <INDENT> return True <N... | :param business_pk: business's public key
:param amount_bigint:
:param txid_hash: transaction identifier (byte array)
:return: true on success, false otherwise | 625941f38da39b475bd6556f |
def get_platform(self): <NEW_LINE> <INDENT> return self.social_id.split('_')[0] | get user social platform
:return: string platfrom | 625941f326238365f5f0f469 |
def onHelpAbout(self, evt): <NEW_LINE> <INDENT> about = panelAbout(self) <NEW_LINE> about.Centre() <NEW_LINE> about.Show() <NEW_LINE> about.SetFocus() | Show About mMass panel. | 625941f3cb5e8a47e48b8092 |
def forward(self, x): <NEW_LINE> <INDENT> batchsize, C, height, width = x.size() <NEW_LINE> proj_query = self.query_conv(x).view(batchsize, -1, height * width).permute(0, 2, 1) <NEW_LINE> proj_key = self.key_conv(x).view(batchsize, -1, height * width) <NEW_LINE> energy = torch.bmm(proj_key, proj_query) <NEW_LINE> at... | inputs :
x : input feature maps(B X C X H X W)
returns :
out : self attention value + input feature
attention: B X c X c | 625941f30c0af96317bb87da |
def job(): <NEW_LINE> <INDENT> print('[+] PUT UPDATER INTO THREADPOOL AT [%s]' % (now())) <NEW_LINE> pool = ThreadPool(POOL_COUNT) <NEW_LINE> pool.add_task(populate, None) <NEW_LINE> pool.wait_completion() <NEW_LINE> print('[+] COMPLETE POPULATE AT [%s]' % (now())) <NEW_LINE> pool.add_task(update, None) <NEW_LINE> pool... | Updater job for periodic repetitions. | 625941f33eb6a72ae02ecae1 |
def testNotActive__execute(self): <NEW_LINE> <INDENT> args = self.ParsedArgs() <NEW_LINE> args.task_name = None <NEW_LINE> self.assertFalse(self.env.task.active) <NEW_LINE> with self.assertRaises(errors.NoActiveTask): <NEW_LINE> <INDENT> self.plugin.execute(self.env, args) | TaskList.execute: prints error if not active, no task provided.
| 625941f3aad79263cf39103d |
def predict(self, input_fn, checkpoint_version="", log_format=PREDICT_LOG_FMT, log_interval=100, max_step=sys.maxint, user_hooks=None): <NEW_LINE> <INDENT> from xdl.python.training.saver import Saver <NEW_LINE> if get_task_index() == 0: <NEW_LINE> <INDENT> saver = Saver() <NEW_LINE> saver.restore(checkpoint_version) <N... | Args:
input_fn:
checkpoint_version:
log_format:
log_interval:
max_step:
user_hooks: | 625941f310dbd63aa1bd3195 |
def encode_multipart_formdata(fields): <NEW_LINE> <INDENT> BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' <NEW_LINE> CRLF = '\r\n'.encode('utf-8') <NEW_LINE> L = [] <NEW_LINE> for (key, value) in fields: <NEW_LINE> <INDENT> if not isinstance(value, types.InputFile): <NEW_LINE> <INDENT> _append_bytes(L, '--' + BOUNDARY) ... | fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be
uploaded as files.
Return (content_type, body) ready for httplib.HTTP instance | 625941f3a4f1c619b28b061d |
def autocast(value, typestring): <NEW_LINE> <INDENT> if typestring == 's': <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> elif typestring == 'i': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return int(float(value)) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise WrongType(cast='i', value=value) ... | Cast a value to the type specified by a typestring.
Typestrings can be 's': str, 'i': int, 'f': float, or 'b': bool.
Lists of one type can be specified as '[i]'. Dicts contain a type for both
key and value as '{s-i}'.
Raises WrongType on impossible casts and BadTypePrefix when the given
typestring doesn't match anyth... | 625941f3dc8b845886cb5b2a |
def update_TypeTree(token, ruleList, tree): <NEW_LINE> <INDENT> if token == 'TypeDef': <NEW_LINE> <INDENT> markbrack1 = ruleList.index('[') <NEW_LINE> new_type = ruleList[:markbrack1] <NEW_LINE> new_type = string.join(new_type) <NEW_LINE> markbrack2 = ruleList.index(']') <NEW_LINE> if markbrack2 == markbrack1 + 1: <NEW... | updates the global "typetree", listing each entry as
subtype: [T/F, head]. All items are initially are set to
false except ROOTs, and then will be checked later with
tracePath, confirming that the subtype hierarchy does indeed work.
Also, checks for Multiple Inheritance, which we are not allowing | 625941f33539df3088e2e93f |
def GetListener(self): <NEW_LINE> <INDENT> return _lldb.SBDebugger_GetListener(self) | GetListener(self) -> SBListener | 625941f36fb2d068a760f69a |
def _distinct(l): <NEW_LINE> <INDENT> return list(set(l)) | Given an iterable will return a list of all distinct values. | 625941f3377c676e9127279a |
def __init__(self, position, text): <NEW_LINE> <INDENT> self.position = position <NEW_LINE> self.text = text | position is the point at which to insert text, in the unmodified
coordinates of the parent node (other insertions and deletions
to that node do not affect these coordinates)
text is the string to insert | 625941f338b623060ff0b3e0 |
def get_standard_error_ci_corrected(values, zscore, pen_val_diff): <NEW_LINE> <INDENT> mean = np.mean(values) <NEW_LINE> var = np.var(values) <NEW_LINE> if var < 1e-10: <NEW_LINE> <INDENT> return 0, mean, mean, -1 <NEW_LINE> <DEDENT> result = np.correlate(values - mean, values - mean, mode='full') <NEW_LINE> result = r... | @param values: the values that are correlated
@param zscore: the zscore to form the confidence interval
@param pen_val_diff: difference of the total penalized values (the negative log likelihood plus some penalty)
@returns
the standard error of the values correcting for auto-correlation between the values
the ... | 625941f34c3428357757c917 |
def calc_unfairness(A, X_prime, y_g, FP_p): <NEW_LINE> <INDENT> unfairness = [] <NEW_LINE> n = X_prime.shape[1] <NEW_LINE> sens_means = np.mean(X_prime, 0) <NEW_LINE> for q in range(n): <NEW_LINE> <INDENT> group_members = [X_prime.iloc[i, q] > sens_means[q] for i in range(X_prime.shape[0])] <NEW_LINE> fp_g = [a for t, ... | Calculate unfairness in marginal sensitive subgroups (thresholded). | 625941f3c432627299f0523e |
def test_delete_event_log_entry(self): <NEW_LINE> <INDENT> pass | Test case for delete_event_log_entry
Delete a log entry # noqa: E501 | 625941f323e79379d52eeb4f |
def testQUser(self): <NEW_LINE> <INDENT> pass | Test QUser | 625941f3046cf37aa974d334 |
def getSensors(self): <NEW_LINE> <INDENT> return list(self._sensors.values()) | Get list of sensors
| 625941f3283ffb24f3c55eee |
def random_card(self): <NEW_LINE> <INDENT> return self.cards[random.randrange(len(self.cards))] | Just return a random card from this list | 625941f363b5f9789fde76d9 |
def calc_average_congestion(self, start_time, end_time): <NEW_LINE> <INDENT> discr_time = 3600.0 <NEW_LINE> events = [] <NEW_LINE> for task in self._tasks: <NEW_LINE> <INDENT> if task.time_start >= start_time and task.time_end <= end_time: <NEW_LINE> <INDENT> events.append((task.time_start, task.required_nodes)) <NEW_L... | Returns average congestion during time [start_time, end_time].
See detailed explanation in help.txt. | 625941f307d97122c4178e8d |
def parse_yaml(yaml_file): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with io.open(yaml_file, encoding="utf-8") as fname: <NEW_LINE> <INDENT> return yaml.safe_load(fname) <NEW_LINE> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <INDENT> sys.exit("Unable to open YAML file: {}".format(yaml_file)) | Read yaml file. | 625941f367a9b606de4a84a9 |
def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, VehicleStatsFaultCodesValueJ1939VendorSpecificFields): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | Returns true if both objects are not equal | 625941f3099cdd3c635f124b |
def is_locked(self, key: KeyType) -> Future[bool]: <NEW_LINE> <INDENT> check_not_none(key, "key can't be None") <NEW_LINE> key_data = self._to_data(key) <NEW_LINE> request = multi_map_is_locked_codec.encode_request(self.name, key_data) <NEW_LINE> return self._invoke_on_key(request, key_data, multi_map_is_locked_codec.d... | Checks the lock for the specified key.
Warning:
This method uses ``__hash__`` and ``__eq__`` methods of binary form
of the key, not the actual implementations of ``__hash__`` and
``__eq__`` defined in key's class.
Args:
key: The key that is checked for lock.
Returns:
Future[bool]: ``True`` if loc... | 625941f315baa723493c456e |
def begin_transaction(self): <NEW_LINE> <INDENT> key = str(uuid.uuid4()) <NEW_LINE> self._sequences[key] = self._client.makeSequence() <NEW_LINE> return key | Creates a transaction (wrapper around Arakoon sequences) | 625941f3ad47b63b2c50a573 |
def make_robust_p_bern(self): <NEW_LINE> <INDENT> isRobustBern = True <NEW_LINE> if isRobustBern: <NEW_LINE> <INDENT> if self.p_bern == 1.0: <NEW_LINE> <INDENT> self.p_bern = 1.0 - 0.0001 <NEW_LINE> <DEDENT> if self.p_bern == 0.0: <NEW_LINE> <INDENT> self.p_bern = 0.0001 | make the probability of bernoulli robust, 1 or 0 will get -inf
:return: robust version of p_bern | 625941f301c39578d7e7542f |
def push(self, item): <NEW_LINE> <INDENT> self.list.insert(0, item) <NEW_LINE> self.list_size += 1 | Insert the given item on the top of this stack.
Running time: O(???) – Why? The whole array has to be moved over,
or a new array has to be created | 625941f3627d3e7fe0d69445 |
def setup_fake_uwsgi(): <NEW_LINE> <INDENT> global opt <NEW_LINE> global numproc <NEW_LINE> global LOGVAR <NEW_LINE> global IMPORT_TIME <NEW_LINE> os.environ["INSTALL_PATH"] = os.path.abspath(os.path.join(__file__, os.pardir)) <NEW_LINE> os.environ["APP_RUN_MODE"] = "development" <NEW_LINE> opt = {"mode": b"development... | Setup the fake uWSGI. This function is called upon import by the module itself. | 625941f37b180e01f3dc4de3 |
def valid(self): <NEW_LINE> <INDENT> if self.low > self.high: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True | The function to check whether this kline is valid
:return: True or False | 625941f3e8904600ed9f252b |
def _generate_batch( self, x: "tf.Tensor", targets: "tf.Tensor", mask: "tf.Tensor", eps: Union[int, float, np.ndarray], eps_step: Union[int, float, np.ndarray], ) -> "tf.Tensor": <NEW_LINE> <INDENT> import tensorflow as tf <NEW_LINE> adv_x = tf.identity(x) <NEW_LINE> for i_max_iter in range(self.max_iter): <NEW_LINE> <... | Generate a batch of adversarial samples and return them in an array.
:param x: An array with the original inputs.
:param targets: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)`.
:param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be
... | 625941f382261d6c526aba9c |
def evaluate_activeVolBuy(np_close, vol): <NEW_LINE> <INDENT> diff_a1 = np.diff(np_close) <NEW_LINE> comp_vol = vol[1:] <NEW_LINE> activeVolBuy = [] <NEW_LINE> activeVolSell = [] <NEW_LINE> swingVol = [] <NEW_LINE> accumulateNetVol = 0 <NEW_LINE> netVol_buySell = [] <NEW_LINE> for i in range(len(diff_a1)): <NEW_LINE> <... | 主动性买盘成交量
:return: | 625941f3cc0a2c11143dd485 |
def download_url_content(url, referer=None, timeout=10): <NEW_LINE> <INDENT> if referer: <NEW_LINE> <INDENT> request_headers['Referer'] = referer <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> request_headers['Referer'] = url <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> x = requests.get(url, headers=request_headers, tim... | Downloads and returns the contents of the given url. | 625941f367a9b606de4a84aa |
def setZeroes(self, matrix: List[List[int]]) -> None: <NEW_LINE> <INDENT> if not matrix or not matrix[0]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> n = len(matrix) <NEW_LINE> m = len(matrix[0]) <NEW_LINE> rows = {} <NEW_LINE> cols = {} <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> for j in range(m): <NEW_LINE>... | 类似于之前的数独
很空易想到时的就是在置 0 的过程中会有重复项
最简单的方法就是循环一遍收集信息
解答中的 O(1) 的空间复杂度 | 625941f37d847024c06be8b5 |
def loss(self, x, t): <NEW_LINE> <INDENT> y = self.predict(x) <NEW_LINE> loss = self.lastLayer.forward(y, t) <NEW_LINE> return loss | Loss function using cross entropy error
Args:
x (numpy.ndarray): image data which mean input to NN
t (numpy.ndarray): labels
Returns:
float: result of cross entropy error | 625941f3e64d504609d74e33 |
def expand_testhome_region(self): <NEW_LINE> <INDENT> self.click_element(self.testhome_expand_button_locator, legacy_screen_loader=True) | Implementing expand testhome region functionality
:return: | 625941f3507cdc57c63072de |
def process_family(family_id): <NEW_LINE> <INDENT> clear_directory(settings.FACE_RECOG_TRAIN_TEMP_DIR) <NEW_LINE> face_model = FaceModel(family_id=family_id) <NEW_LINE> people = Person.objects.filter(family_id=family_id) <NEW_LINE> X = [] <NEW_LINE> y = [] <NEW_LINE> for person in people: <NEW_LINE> <INDENT> process_pe... | Creates a K Nearest neighbour model for a family
using tagged photos and profile picture | 625941f38c3a8732951589b6 |
def get_world_size(self): <NEW_LINE> <INDENT> return self.__mabm_world_size | Returns the MPI world size (the number of processes+1) | 625941f3379a373c97cfb13b |
def start_proc_steal_data_over_sockets(participant, kwargs): <NEW_LINE> <INDENT> def target(): <NEW_LINE> <INDENT> server = participant(**kwargs) <NEW_LINE> private_data = torch.tensor([1, 1, 1, 1, 1]) <NEW_LINE> private_data.private = True <NEW_LINE> server._objects[1] = private_data <NEW_LINE> server.start() <NEW_LIN... | helper function for spinning up a websocket participant | 625941f3b830903b967e9ef8 |
def xpath_direct_adjacent_combinator(self, left, right): <NEW_LINE> <INDENT> xpath = left.join('/following-sibling::', right) <NEW_LINE> xpath.add_name_test() <NEW_LINE> return xpath.add_condition('position() = 1') | right is a sibling immediately after left | 625941f3ec188e330fd5ad86 |
def praf_metric(prediction, truth): <NEW_LINE> <INDENT> confusion_vector = prediction / truth <NEW_LINE> true_positives = torch.sum(confusion_vector == 1).item() <NEW_LINE> false_positives = torch.sum(confusion_vector == float('inf')).item() <NEW_LINE> true_negatives = torch.sum(torch.isnan(confusion_vector)).item() <N... | Returns the confusion matrix for the values in the `prediction` and `truth`
tensors, i.e. the amount of positions where the values of `prediction`
and `truth` are
- 1 and 1 (True Positive)
- 1 and 0 (False Positive)
- 0 and 0 (True Negative)
- 0 and 1 (False Negative) | 625941f355399d3f05588cac |
def get_products_list(self, search_filter): <NEW_LINE> <INDENT> logger.debug("(Datasource get_products_list)") <NEW_LINE> products_list = self.abm.get_products_list(search_filter) <NEW_LINE> logger.debug("(Datasrouce get_products_list) list of products:") <NEW_LINE> for product_name in products_list: <NEW_LINE> <INDENT... | This method generates the product list from query filters defined in the config file
by the user.
:param searchFilter: Search parameters to filter the available files in the bucket
:type searchFilter: SearchFilter
:returns: The list of available products.
:rtype: List | 625941f3ad47b63b2c50a574 |
def move_to(self, e): <NEW_LINE> <INDENT> if e.buttons() == QtCore.Qt.MouseButton.NoButton: <NEW_LINE> <INDENT> x = self.parent().mapFromGlobal(e.globalPos()).x() <NEW_LINE> y = self.parent().mapFromGlobal(e.globalPos()).y() <NEW_LINE> self.setGeometry(x + 5, y + 5, self.width(), self.height()) <NEW_LINE> self.draw_arr... | ..
:param PySide.QtCore.QEvent e:
:rtype: *void*
This re-implemented event makes sure this :class:`BSArrowCarrier` stays with the mouse pointer. | 625941f3baa26c4b54cb170d |
def determine_node_version_int(self, node: Prv_or_PubKeyNode, key_type: Key) -> Version: <NEW_LINE> <INDENT> bip = Bip32Path.parse(str(node)) <NEW_LINE> version = Version( key_type=key_type.value, testnet=self.testnet, bip=bip.bip() ) <NEW_LINE> return version | Determines node version.
:param node: key node
:param key_type: type of key private/public
:return: version object | 625941f35fdd1c0f98dc082a |
def look_crontab(self): <NEW_LINE> <INDENT> self.AppLogging.info('lookcrontab') <NEW_LINE> if self.crontab: <NEW_LINE> <INDENT> self.AppLogging.info(self.crontab) <NEW_LINE> return self.crontab <NEW_LINE> <DEDENT> return 1 | 查看所有cron任务
:return: 任务列表 | 625941f3d486a94d0b98e73b |
def grouping_hook(ctx: FunctionContext) -> Type: <NEW_LINE> <INDENT> assert isinstance(ctx.default_return_type, Instance) <NEW_LINE> element_arg_type = get_proper_type(get_argtype_by_name(ctx, 'element')) <NEW_LINE> if element_arg_type is not None and isinstance(element_arg_type, Instance): <NEW_LINE> <INDENT> if (elem... | Infer better types for Grouping calls.
Examples:
Grouping(text('asdf')) -> Grouping[None]
Grouping(Column(String), nullable=False) -> Grouping[str]
Grouping(Column(String)) -> Grouping[Optional[str]] | 625941f371ff763f4b549c8b |
@__numpymatrix <NEW_LINE> def laplacian_matrix(A): <NEW_LINE> <INDENT> deg = np.diag(degree(A)) <NEW_LINE> return deg - A | Returns Laplacian matrix of a graph G.
Requrements
-----------
**numpy**
Parameters
----------
A : numpy matrix or list of lists
This is n x n adjacency matrix of a graph.
Returns
-------
lapl : numpy matrix
This is n x n Laplacian matrix of a graph.
Examples
--------
>>> a = [
[0, 1, 0, 0, ... | 625941f399cbb53fe67931d8 |
def select_isFarmer(self, isfarmer): <NEW_LINE> <INDENT> self.select_widget(isfarmer, *self.isFarmer_loc) | 选择是否向固定农户采购 | 625941f355399d3f05588cad |
def drawInputQuestion(self,title="",question="",callback=None): <NEW_LINE> <INDENT> text, ok = QtGui.QInputDialog.getText(self, title, question) <NEW_LINE> if ok: <NEW_LINE> <INDENT> if callback is not None : <NEW_LINE> <INDENT> callback(text) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return text | Draw an Input Question message dialog, requiring a string answer
@type title: string
@param title: the windows title
@type question: string
@param question: the question to display
@rtype: string
@return: the answer | 625941f399fddb7c1c9de982 |
def main_menu(self): <NEW_LINE> <INDENT> clr_screen() <NEW_LINE> print (misc.TITLE_MENU) <NEW_LINE> for key in sorted(misc.menu): <NEW_LINE> <INDENT> print (misc.menu[key]) <NEW_LINE> <DEDENT> choice = input("Please select from options:") <NEW_LINE> if choice == '1': <NEW_LINE> <INDENT> print(choice) <NEW_LINE> clr_scr... | Give the user a menu to select from | 625941f332920d7e50b287ca |
def common_send_email(subject, text_template_path, html_template_path, context_data, recipients, from_email=None): <NEW_LINE> <INDENT> coupon_obj = context_data['coupon_obj'] <NEW_LINE> if not from_email: <NEW_LINE> <INDENT> from_email = DEFAULT_FROM_EMAIL <NEW_LINE> <DEDENT> text_raw_content = get_template(text_templa... | This method is a common method to send email via the bhane system. | 625941f376e4537e8c351c6c |
def get_partition_by_index(self, start, end): <NEW_LINE> <INDENT> if start < 0: <NEW_LINE> <INDENT> raise ValueError("Start index must be >= 0") <NEW_LINE> <DEDENT> if end > self.ranges.shape[1]: <NEW_LINE> <INDENT> raise ValueError("End index must be <= len(scan)") <NEW_LINE> <DEDENT> if start >= end: <NEW_LINE> <INDE... | Get a new Scan object of [start:end] (inclusive) indicies | 625941f39f2886367277ae7c |
@receiver(post_save, sender=OrderLineItem) <NEW_LINE> def update_on_save(sender, instance, created, **kwargs): <NEW_LINE> <INDENT> instance.order.update_total() | Update order total on line item update/create | 625941f38da39b475bd65570 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.