code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def setup(self): <NEW_LINE> <INDENT> self.no_runs = 100 <NEW_LINE> self.ds_1_1_1 = dcmread(EXPL_1_1_1F) <NEW_LINE> self.ds_1_1_3 = dcmread(EXPL_1_1_3F) <NEW_LINE> self.ds_8_1_1 = dcmread(EXPL_8_1_1F) <NEW_LINE> self.ds_8_1_2 = dcmread(EXPL_8_1_2F) <NEW_LINE> self.ds_8_3_1 = dcmread(EXPL_8_3_1F) <NEW_LINE> self.ds_8_3_2... | Setup the tests. | 625941c232920d7e50b28179 |
def located_at(self, location): <NEW_LINE> <INDENT> if location.__class__ not in ( Location, ): <NEW_LINE> <INDENT> raise RelationLocatedAtError() <NEW_LINE> <DEDENT> return location in self._located_at_locations | Check `locatedAt` relation with given `location` object.
FIXME: Document locatedAt relation.
:param location: Object to validate relation `locatedAt` with.
:type location: Location
:return: True if `location` is related to `self` with `locatedAt`.
:rtype: bool | 625941c216aa5153ce362424 |
def preprocess(words_file = "../tools/word_data_unix.pkl", authors_file="../tools/email_authors.pkl"): <NEW_LINE> <INDENT> authors_file_handler = open(authors_file, "rb") <NEW_LINE> authors = pickle.load(authors_file_handler) <NEW_LINE> authors_file_handler.close() <NEW_LINE> words_file_handler = open(words_file, "rb")... | this function takes a pre-made list of email texts (by default word_data.pkl)
and the corresponding authors (by default email_authors.pkl) and performs
a number of preprocessing steps:
-- splits into training/testing sets (10% testing)
-- vectorizes into tfidf matrix
-- selects/keeps most helpful features
... | 625941c25e10d32532c5eed2 |
def delete_password(acc): <NEW_LINE> <INDENT> Password.delete_password(acc) | This is a function that will delete the password
Args:
acc - the acc of the pass the user wants to delete | 625941c2a05bb46b383ec7ce |
def validate(self): <NEW_LINE> <INDENT> self.model.eval() <NEW_LINE> val_loss = 0 <NEW_LINE> num_vis = 8 <NEW_LINE> visualizations = [] <NEW_LINE> label_trues, label_preds = [], [] <NEW_LINE> for batch_idx, (data, target) in tqdm.tqdm( enumerate(self.val_loader), total=len(self.val_loader), desc='Valid iteration=%d' % ... | Function to validate a training model on the val split. | 625941c2b545ff76a8913dc1 |
def change_permissions(self, url, path, command=None): <NEW_LINE> <INDENT> LOG.info("Changing monkey's permissions") <NEW_LINE> if 'windows' in self.host.os['type']: <NEW_LINE> <INDENT> LOG.info("Permission change not required for windows") <NEW_LINE> return True <NEW_LINE> <DEDENT> if not command: <NEW_LINE> <INDENT> ... | Method for linux hosts. Makes monkey executable
:param url: Where to send malicious packets
:param path: Path to monkey on remote host
:param command: Formatted command for permission change or None
:return: response, False if failed and True if permission change is not needed | 625941c2bf627c535bc13179 |
def is_suspicious(self, file_content): <NEW_LINE> <INDENT> last_tweet = json.loads(file_content[0]) <NEW_LINE> if self.is_multiple_of_seven(last_tweet['user']['id']): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> first_tweet = json.loads(file_content[-1]) <NEW_LINE> first_date = datetime.datetime.strptime( first_... | Method to determine wether an specific user is suspicious of being a bot
:param file_content: All the tweets from a user
:type file_content: list
:returns: True or False
:rtype: boolean | 625941c2c4546d3d9de729dd |
def parse_cli(arg_list=None, origin=os.getcwd(), arg_parser=None, key_value_delimiters=('=', ':'), comment_seperators=(), key_delimiters=(',',), section_override_delimiters=('.',)): <NEW_LINE> <INDENT> arg_parser = default_arg_parser() if arg_parser is None else arg_parser <NEW_LINE> origin += os.path.sep <NEW_LINE> se... | Parses the CLI arguments and creates sections out of it.
:param arg_list: The CLI argument list.
:param origin: Directory used to interpret relative
paths given as argument.
:param arg_parser: Instance of ArgParser that is use... | 625941c2283ffb24f3c558ae |
def userLoginAction(): <NEW_LINE> <INDENT> return auth.userLoginAction(userData) | 这里是让用户进行登录操作的提示
:return: | 625941c25510c4643540f394 |
def getpixel(self, xy): <NEW_LINE> <INDENT> self.load() <NEW_LINE> if self.pyaccess: <NEW_LINE> <INDENT> return self.pyaccess.getpixel(xy) <NEW_LINE> <DEDENT> return self.im.getpixel(xy) | Returns the pixel value at a given position.
:param xy: The coordinate, given as (x, y). See
:ref:`coordinate-system`.
:returns: The pixel value. If the image is a multi-layer image,
this method returns a tuple. | 625941c2e5267d203edcdc4a |
def main(wf): <NEW_LINE> <INDENT> name = wf.args[0] <NEW_LINE> argcache = _arg_cache(name) <NEW_LINE> if not os.path.exists(argcache): <NEW_LINE> <INDENT> log.critical('No arg cache found : {!r}'.format(argcache)) <NEW_LINE> return 1 <NEW_LINE> <DEDENT> with open(argcache, 'rb') as file: <NEW_LINE> <INDENT> data = pick... | Load cached arguments, fork into background, then call
:meth:`subprocess.call` with cached arguments | 625941c2bf627c535bc1317a |
def insert(self, word: 'str') -> 'None': <NEW_LINE> <INDENT> p=self.dicts <NEW_LINE> for c in word: <NEW_LINE> <INDENT> if c not in p: <NEW_LINE> <INDENT> p[c]={} <NEW_LINE> <DEDENT> p=p[c] <NEW_LINE> <DEDENT> p['#']=True | Inserts a word into the trie. | 625941c221a7993f00bc7c98 |
def select_commercial_trunks_tab(self): <NEW_LINE> <INDENT> self.select_static_tab(self.commercial_trunks_tab_locator, 'commercial trunks tab not found before specified time') | Implementing select commercial trunks tab functionality
:return: | 625941c296565a6dacc8f677 |
def train(self,k=10): <NEW_LINE> <INDENT> train_data = self.sentence_data <NEW_LINE> attributes = set(train_data[0].attributes.keys()) <NEW_LINE> weighted_data = WeightedData(train_data) <NEW_LINE> self.ensemble =[] <NEW_LINE> for ctr in range(k): <NEW_LINE> <INDENT> stump = makeTree(train_data,attributes,[],1) <NEW_LI... | Generate an ADA booseted ensemble and store it in a hypothesis.
:param k maximum number of stumps to be generated:
:return: | 625941c2627d3e7fe0d68dfa |
def findTheDifference(self, s, t): <NEW_LINE> <INDENT> letters = dict() <NEW_LINE> for letter in s: <NEW_LINE> <INDENT> letters[letter] = letters.get(letter, 0) + 1 <NEW_LINE> <DEDENT> for letter in t: <NEW_LINE> <INDENT> if letter not in letters or letters[letter] == 0: <NEW_LINE> <INDENT> return letter <NEW_LINE> <DE... | :type s: str
:type t: str
:rtype: str | 625941c282261d6c526ab448 |
@requires_mne <NEW_LINE> def test_average_forward_solution(): <NEW_LINE> <INDENT> fwd = read_forward_solution(fname) <NEW_LINE> assert_raises(TypeError, average_forward_solutions, 1) <NEW_LINE> assert_raises(ValueError, average_forward_solutions, []) <NEW_LINE> assert_raises(ValueError, average_forward_solutions, [fwd,... | Test averaging forward solutions
| 625941c297e22403b379cf44 |
def validate_token_ranges(tree): <NEW_LINE> <INDENT> testlevel = 1 <NEW_LINE> testclass = 'Format' <NEW_LINE> covered = set() <NEW_LINE> for cols in tree: <NEW_LINE> <INDENT> if not is_multiword_token(cols): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> m = interval_re.match(cols[ID]) <NEW_LINE> if not m: <NEW_LINE>... | Checks that the word ranges for multiword tokens are valid. | 625941c23c8af77a43ae374a |
def validate(self): <NEW_LINE> <INDENT> return None | Validate request before rendering it.
This hook gives a chance for all view classes to validate request
before starting to render it.
If validation passes, this function must return None.
If there is validation erros, this function must return response object
with error message.
Currently this functionality is only... | 625941c20a50d4780f666e3c |
def build_seq_from_file(self, f, size_lim=None): <NEW_LINE> <INDENT> off = f.tell() <NEW_LINE> rv = [] <NEW_LINE> if (size_lim is None): <NEW_LINE> <INDENT> off_lim = f.seek(0,2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> off_lim = off + size_lim <NEW_LINE> <DEDENT> while (off < off_lim): <NEW_LINE> <INDENT> f.seek(... | Deserialize sequence of EBML elements from filelike, up to size_lim (or EOF if not specified). | 625941c210dbd63aa1bd2b4f |
def test_get_monday_present(self): <NEW_LINE> <INDENT> week = test.create_week() <NEW_LINE> week.populate() <NEW_LINE> monday = funct.get_monday(week=week) <NEW_LINE> current_mon = date(2017,7,10) <NEW_LINE> self.assertEqual(monday, current_mon) | Returns most recent Monday. To test, uncomment and change current_mon date.
Tested and works. | 625941c2cb5e8a47e48b7a58 |
def _get_completion_model(self, completion, pos_args): <NEW_LINE> <INDENT> if completion == usertypes.Completion.option: <NEW_LINE> <INDENT> section = pos_args[0] <NEW_LINE> model = instances.get(completion).get(section) <NEW_LINE> <DEDENT> elif completion == usertypes.Completion.value: <NEW_LINE> <INDENT> section = po... | Get a completion model based on an enum member.
Args:
completion: A usertypes.Completion member.
pos_args: The positional args entered before the cursor.
Return:
A completion model or None. | 625941c20c0af96317bb8193 |
def get_root_path(self): <NEW_LINE> <INDENT> return realpath(os.getcwd()) | Return the root file path | 625941c20c0af96317bb8194 |
def white(s = ""): <NEW_LINE> <INDENT> return _put_color(WHITE) + _convert_value(s); | white(s) -> str
Put the white foreground escape sequence in front of the 's'.
This function is affected by the values of:
ColorMode.mode and ConvertMode.mode. | 625941c2ff9c53063f47c1a0 |
def file_dict(*packages): <NEW_LINE> <INDENT> errors = [] <NEW_LINE> ret = {} <NEW_LINE> pkgs = {} <NEW_LINE> if not packages: <NEW_LINE> <INDENT> cmd = 'rpm -qa --qf \'%{NAME} %{VERSION}\\n\'' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd = 'rpm -q --qf \'%{{NAME}} %{{VERSION}}\\n\' {0}'.format( ' '.join(packages)... | List the files that belong to a package, sorted by group. Not specifying
any packages will return a list of _every_ file on the system's rpm
database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.file_dict httpd
salt '*' lowpkg.file_dict httpd postfix
salt '*' lowpkg.fil... | 625941c24d74a7450ccd416f |
def open_parent(self): <NEW_LINE> <INDENT> self.ensure_one() <NEW_LINE> address_form_id = self.env.ref("base.view_partner_address_form").id <NEW_LINE> return { "type": "ir.actions.act_window", "res_model": "res.partner", "view_mode": "form", "views": [(address_form_id, "form")], "res_id": self.parent_id.id, "target": "... | Utility method used to add an "Open Parent" button in partner
views | 625941c2dd821e528d63b156 |
def get_jump_epoch_designmatrix(self, cand, fitpatch=None): <NEW_LINE> <INDENT> Umat = self.Umat(cand) <NEW_LINE> Uinv = self.Umat_i(Umat=Umat) <NEW_LINE> Mj = self.get_jump_designmatrix(cand, fitpatch=fitpatch) <NEW_LINE> return np.dot(Uinv, Mj) | Obtain the epoch-domain design matrix of inter-coherence-patch jumps
Obtain the design matrix of jumps that disconnect all the coherence
patches that are not phase connected. This version is carried out in the
epoch-domain (so it's Ui Mj)
:param cand:
CandidateSolution candidate
:param fitpatch:
If not None,... | 625941c256b00c62f0f14604 |
def hash1(self, file=None): <NEW_LINE> <INDENT> if verbose > 3: <NEW_LINE> <INDENT> print("Calculating hash1:") <NEW_LINE> <DEDENT> if file is None: <NEW_LINE> <INDENT> file = self.fp <NEW_LINE> <DEDENT> oldpos = file.tell() <NEW_LINE> file.seek(-21, 2) <NEW_LINE> end = file.tell() <NEW_LINE> file.seek(0) <NEW_LINE> ha... | Calculate first hash value. | 625941c2009cb60464c6335f |
@contextlib.contextmanager <NEW_LINE> def immutable_object_cache(ctx, config): <NEW_LINE> <INDENT> log.info("start immutable object cache daemon") <NEW_LINE> for client, client_config in config.items(): <NEW_LINE> <INDENT> (remote,) = ctx.cluster.only(client).remotes.keys() <NEW_LINE> remote.run( args=[ 'sudo', 'killal... | setup and cleanup immutable object cache | 625941c226238365f5f0ee17 |
def softmax(predictions): <NEW_LINE> <INDENT> shape = predictions.shape <NEW_LINE> if len(shape) == 1: <NEW_LINE> <INDENT> p = predictions.copy()[None] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p = predictions.copy() <NEW_LINE> <DEDENT> p -= np.max(p) <NEW_LINE> probs = np.zeros_like(p, dtype=np.float) <NEW_LINE> n... | Computes probabilities from scores
Arguments:
predictions, np array, shape is either (N) or (batch_size, N) -
classifier output
Returns:
probs, np array of the same shape as predictions -
probability for every class, 0..1 | 625941c2e1aae11d1e749c61 |
def capital_recovery_factor(ir, t): <NEW_LINE> <INDENT> return ir/(1-(1+ir)**-t) | The capital recovery factor is a coefficient applied to a loan to
determine annual payments. This function needs an interest rate ir
and the number of compounding periods that payments are split
across.
Example: Calculate annual loan payments for a 20-year loan with a 7
percent interest rate on $100.
>>> crf = capita... | 625941c27047854f462a13b8 |
@ensure_csrf_cookie <NEW_LINE> def delete_employees(request): <NEW_LINE> <INDENT> deleteids= request.POST['rowids'] <NEW_LINE> for id in deleteids.split(",") : <NEW_LINE> <INDENT> aservc=get_object_or_404(AppschedulerEmployees, pk=int(id) ) <NEW_LINE> aservc.delete() <NEW_LINE> <DEDENT> return HttpResponse(status=204) | Delete all selected employees | 625941c23346ee7daa2b2d16 |
def processPublish(self, session, publish): <NEW_LINE> <INDENT> assert(session in self._session_to_subscriptions) <NEW_LINE> if (not self._option_uri_strict and not _URI_PAT_LOOSE_NON_EMPTY.match(publish.topic)) or ( self._option_uri_strict and not _URI_PAT_STRICT_NON_EMPTY.match(publish.topic)): <NEW_LINE>... | Implements :func:`autobahn.wamp.interfaces.IBroker.processPublish` | 625941c2cc40096d615958fd |
def test_right_bounds_with_next(self): <NEW_LINE> <INDENT> self.testInst.prev() <NEW_LINE> with pytest.raises(StopIteration): <NEW_LINE> <INDENT> self.testInst.next() | Test if passing bounds raises StopIteration. | 625941c292d797404e304135 |
def get_W(self): <NEW_LINE> <INDENT> m = self._model.m <NEW_LINE> n = self._model.n <NEW_LINE> k = self._model.k <NEW_LINE> k_aligned = _lib.ffm_get_k_aligned(k) <NEW_LINE> kALIGN = _lib.ffm_get_kALIGN() <NEW_LINE> align0 = 2*k_aligned <NEW_LINE> align1 = m*align0 <NEW_LINE> W = np.ctypeslib.as_array(self._model.W,(1,n... | Returns the model vectors W of shape n x m x k, where n is the number of feature indexes
and m is the number of fields.
Given input X, the computation of probabilites can then be done in python as follows:
import itertools
i = 0 #the sample index for which we want to compute probabilities
sig = lambda x: 1/(1+np.exp(... | 625941c22c8b7c6e89b3576e |
def setStyle(self, *args): <NEW_LINE> <INDENT> return _osgText.TextBase_setStyle(self, *args) | setStyle(TextBase self, Style style) | 625941c2e8904600ed9f1ed6 |
def callable_virtualenv(): <NEW_LINE> <INDENT> from time import sleep <NEW_LINE> from colorama import Back, Fore, Style <NEW_LINE> print(Fore.RED + 'some red text') <NEW_LINE> print(Back.GREEN + 'and with a green background') <NEW_LINE> print(Style.DIM + 'and in dim text') <NEW_LINE> print(Style.RESET_ALL) <NEW_LINE> f... | Example function that will be performed in a virtual environment.
Importing at the module level ensures that it will not attempt to import the
library before it is installed. | 625941c266673b3332b9203d |
def find_similar_word(self, word): <NEW_LINE> <INDENT> return self.w2v_model.most_similar(word) | 通过w2v向量计算词条相似度 | 625941c23617ad0b5ed67ea5 |
def load_file_list(path=None, regx='.*.png', printable=False, keep_prefix=False): <NEW_LINE> <INDENT> if path is None: <NEW_LINE> <INDENT> path = os.getcwd() <NEW_LINE> <DEDENT> file_list = os.listdir(path) <NEW_LINE> return_list = [] <NEW_LINE> for _, f in enumerate(file_list): <NEW_LINE> <INDENT> if re.search(regx, f... | Return a file list in a folder by given a path and regular expression.
Parameters
----------
path : str or None
A folder path, if `None`, use the current directory.
regx : str
The regx of file name.
printable : boolean
Whether to print the files infomation.
keep_prefix : boolean
Whether to keep path in... | 625941c276d4e153a657eadc |
def test_action_case_2(self): <NEW_LINE> <INDENT> pc = DotDict() <NEW_LINE> f2jd = copy.deepcopy(cannonical_json_dump) <NEW_LINE> pc.upload_file_minidump_flash2 = DotDict() <NEW_LINE> pc.upload_file_minidump_flash2.json_dump = f2jd <NEW_LINE> pc.upload_file_minidump_flash2.json_dump['crashing_thread']['frames'][1] ... | success - only 1st target found in top 5 frames of stack | 625941c2fb3f5b602dac363d |
def _find_thread_stack(thread_id): <NEW_LINE> <INDENT> for tid, stack in sys._current_frames().items(): <NEW_LINE> <INDENT> if tid == thread_id: <NEW_LINE> <INDENT> return stack <NEW_LINE> <DEDENT> <DEDENT> return None | Returns a stack object that can be used to dump a stack trace for
the given thread id (or None if the id is not found). | 625941c24f6381625f1149e8 |
def __init__(self): <NEW_LINE> <INDENT> self.Id = None <NEW_LINE> self.Name = None <NEW_LINE> self.Protocol = None | :param Id: Channel ID.
:type Id: str
:param Name: The channel name after modification.
:type Name: str
:param Protocol: The channel protocol after modification. Valid values: HLS, DASH.
:type Protocol: str | 625941c24e696a04525c93f8 |
def __init__(self, importeur, parser_cmd, nom, m_type="inconnu"): <NEW_LINE> <INDENT> self.importeur = importeur <NEW_LINE> self.parser_cmd = parser_cmd <NEW_LINE> self.nom = nom <NEW_LINE> self.type = m_type <NEW_LINE> self.statut = INSTANCIE | Constructeur d'un module.
Par défaut, on lui attribue surtout un nom IDENTIFIANT, sans accents
ni espaces, qui sera le nom du package même.
Le type du module est soit primaire soit secondaire. | 625941c2b7558d58953c4ec4 |
def GetResources(self, args): <NEW_LINE> <INDENT> group_ref = self.CreateInstanceGroupReference( name=args.name, region=args.region, zone=args.zone, zonal_resource_type='instanceGroups', regional_resource_type='regionInstanceGroups') <NEW_LINE> if group_ref.Collection() == 'compute.instanceGroups': <NEW_LINE> <INDENT> ... | Retrieves response with named ports. | 625941c2be383301e01b5435 |
def modify_env(old, new, verbose=True): <NEW_LINE> <INDENT> old_keys = list(old.keys()) <NEW_LINE> new_keys = list(new.keys()) <NEW_LINE> for key in new_keys: <NEW_LINE> <INDENT> if key in old_keys: <NEW_LINE> <INDENT> if not new[key] == old[key]: <NEW_LINE> <INDENT> _log.debug("Key in new environment found that is dif... | Compares two os.environ dumps. Adapts final environment. | 625941c2293b9510aa2c3244 |
def draw_terrain(self, panel, level_id, terrain, coverage, revealed, visible): <NEW_LINE> <INDENT> walls_mask = self.walls_bitmask(level_id, coverage, revealed, self.walls_terrain_type) <NEW_LINE> mask_offset = Position( max(0, self.x*-1), max(0, self.y*-1) ) <NEW_LINE> revealed_not_visible = revealed ^ visible <NEW_LI... | Draw TERRAIN tiles. | 625941c285dfad0860c3ae06 |
def compute_global_error(g): <NEW_LINE> <INDENT> Fx = 0 <NEW_LINE> for edge in g['edges']: <NEW_LINE> <INDENT> if edge['type'] == 'P': <NEW_LINE> <INDENT> x1 = main.v2t(g['x'][edge['fromIdx']:edge['fromIdx']+3]) <NEW_LINE> x2 = main.v2t(g['x'][edge['toIdx']:edge['toIdx']+3]) <NEW_LINE> <DEDENT> elif edge['type'] == 'L'... | Computes the total error of the graph | 625941c255399d3f0558865f |
def test_reverse_string(self): <NEW_LINE> <INDENT> self.assertEqual('ataD gnirtS yM', 'My String Data') | 5 points
Test with value My String Data return value should be ataD gnirtS yM | 625941c2d6c5a10208143ff5 |
def __query_gen(self, url, variables, entity_name, query, end_cursor=''): <NEW_LINE> <INDENT> dst = self.get_dst_dir(query) <NEW_LINE> if end_cursor==True: <NEW_LINE> <INDENT> end_cursor = self.load_end_cursor(dst) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> end_cursor = '' <NEW_LINE> <DEDENT> nodes, end_cursor = sel... | Generator for hashtag and location. | 625941c2287bf620b61d3a11 |
def plot_train_val_losses(training_loss: list, validation_loss: list, save_dir: str = None, display: bool = False, debug: bool = False, interval: str = 'Epochs', title: str = "Training Loss Curves") -> None: <NEW_LINE> <INDENT> x_values = list(np.arange(1, len(training_loss)+1)) <NEW_LINE> train_trace = go.Scatter(x=x_... | Creates a one off train val plot.
Args:
training_loss (list): list of floats
val_loss (list): list of floats
save_dir (str): path to a location to save an exported image of the plot (or an interactive graph)
debug (bool): default False
** kwargs (keyword arguments): checked for title, xlabel, ylabe... | 625941c2a4f1c619b28affea |
def simple_bind(self): <NEW_LINE> <INDENT> total_bound = 0.0 <NEW_LINE> mol_id = self.active_molecules[0] <NEW_LINE> mol_concentration = self.get_concentration(mol_id) <NEW_LINE> if mol_concentration <= 0.0: <NEW_LINE> <INDENT> for dendrite in self.dendrites: dendrite.set_bound(0.0) <NEW_LINE> return <NEW_LINE> <DEDENT... | Bound/Unbound fraction
f = [L] / ( [L] + K_d )
f is the fraction of molecules that are bound to receptors.
L is the molecule concentration
K_d is the dissociation constant
This simpler version is less computationally expensive, but only works
if the synaptic cleft contains only one molecule. | 625941c24527f215b584c405 |
def test_sanity(self): <NEW_LINE> <INDENT> assert self.dim == len(self.Ls) <NEW_LINE> assert self.shape == self.Ls + (len(self.unit_cell), ) <NEW_LINE> assert self.N_cells == np.prod(self.Ls) <NEW_LINE> assert self.N_sites == np.prod(self.shape) <NEW_LINE> if self.bc.shape != (self.dim, ): <NEW_LINE> <INDENT> raise Val... | Sanity check. Raises ValueErrors, if something is wrong. | 625941c2187af65679ca50ca |
def test_reform_with_scalar_vector_errors(): <NEW_LINE> <INDENT> policy1 = Policy() <NEW_LINE> reform1 = {'SS_thd85': {2020: 30000}} <NEW_LINE> with pytest.raises(pt.ValidationError): <NEW_LINE> <INDENT> policy1.implement_reform(reform1) <NEW_LINE> <DEDENT> policy2 = Policy() <NEW_LINE> reform2 = {'ID_Medical_frt': {20... | Test catching scalar-vector confusion. | 625941c2796e427e537b0570 |
def outstanding_teams(self): <NEW_LINE> <INDENT> return filter(lambda t: not t.finished(), self.teams) | Returns all teams that have not finished yet. | 625941c2f548e778e58cd529 |
def __getitem__(self, n): <NEW_LINE> <INDENT> if self.access=="disk": <NEW_LINE> <INDENT> path=self.targets.keys()[n] <NEW_LINE> <DEDENT> elif self.access=="firstFat": <NEW_LINE> <INDENT> path=self.firstFats[n] <NEW_LINE> <DEDENT> return self.targets[path] | Renvoye le nième disque. Le fonctionnement dépend du paramètre
self.access
@param n un numéro
@return le nième disque USB connecté sous forme d'instance de uDisk2 | 625941c224f1403a92600b14 |
def GetMatch(self, start): <NEW_LINE> <INDENT> start_time = start <NEW_LINE> if self.timezone and pytz is not None: <NEW_LINE> <INDENT> if not start_time.tzinfo: <NEW_LINE> <INDENT> start_time = pytz.utc.localize(start_time) <NEW_LINE> <DEDENT> start_time = start_time.astimezone(self.timezone) <NEW_LINE> start_time = s... | Returns the next time that matches the schedule after time start.
Arguments:
start: a UTC datetime to start from. Matches will start after this time
Returns:
a datetime object | 625941c230dc7b7665901915 |
def delete_queue(self, queue_name, fail_not_exist=False): <NEW_LINE> <INDENT> _validate_not_none('queue_name', queue_name) <NEW_LINE> request = HTTPRequest() <NEW_LINE> request.method = 'DELETE' <NEW_LINE> request.host = self._get_host() <NEW_LINE> request.path = '/' + str(queue_name) + '' <NEW_LINE> request.path, requ... | Permanently deletes the specified queue.
queue_name: name of the queue.
fail_not_exist: specify whether throw exception when queue doesn't exist. | 625941c2627d3e7fe0d68dfb |
@transact_ro <NEW_LINE> def get_stats(store, week_delta): <NEW_LINE> <INDENT> now = datetime_now() <NEW_LINE> week_delta = abs(week_delta) <NEW_LINE> if week_delta > 0: <NEW_LINE> <INDENT> target_week = utc_past_date(hours=(week_delta * 24 * 7)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> target_week = datetime_now()... | :param week_delta: commonly is 0, mean that you're taking this
week. -1 is the previous week.
At the moment do not support negative number and change of the year. | 625941c215baa723493c3f20 |
def matches(self, message: str) -> bool: <NEW_LINE> <INDENT> return re.match(self.regex, message) != None | :param message: The message to check
:return: True if the taunt is matched in the message, false if not | 625941c2091ae35668666f0e |
def open(self, path, flag="r"): <NEW_LINE> <INDENT> return self._client.open(six.text_type(path), flag) | Used to get a python filehandler object
:param path:
the name of the file to be opened
:param flag:
which mode should the file be opened in
:return:
a _io.TextIOWrapper object with utf-8 encoding | 625941c26fb2d068a760f048 |
def swap_possible(board): <NEW_LINE> <INDENT> print("Not implemented yet!") <NEW_LINE> return False | Optional Challenge: helper function for swap
Returns True if a swap is possible on the given board and False otherwise | 625941c28c0ade5d55d3e966 |
def to_encdict(self): <NEW_LINE> <INDENT> d = {} <NEW_LINE> d['user'] = self._username <NEW_LINE> d['password'] = self._password <NEW_LINE> d['notes'] = self._notes <NEW_LINE> d['url'] = self._url <NEW_LINE> d['tags'] = self._tags <NEW_LINE> return d | Return a dictionary of encrypted records | 625941c2fb3f5b602dac363e |
def set_use_tcp(self, use_tcp=True): <NEW_LINE> <INDENT> self.use_tcp = use_tcp | Set TCP/UDP usage (by default will be used UDP) | 625941c28a349b6b435e8120 |
def setup_training(self, session): <NEW_LINE> <INDENT> self.predictions = [] <NEW_LINE> self.loss = 0 <NEW_LINE> self.io.print_warning('Deep supervision application set to {}'.format(self.cfgs['deep_supervision'])) <NEW_LINE> for idx, b in enumerate(self.side_outputs): <NEW_LINE> <INDENT> output = tf.nn.sigmoid(b, name... | Apply sigmoid non-linearity to side layer ouputs + fuse layer outputs
Compute total loss := side_layer_loss + fuse_layer_loss
Compute predicted edge maps from fuse layer as pseudo performance metric to track | 625941c2498bea3a759b9a5c |
def __init__(self, grid_size=GRID_SIZE, prob_2=PROB_2): <NEW_LINE> <INDENT> self.grid = np.ones(grid_size) <NEW_LINE> self.prob_2 = prob_2 <NEW_LINE> self.game_over = False <NEW_LINE> self.score = 0 <NEW_LINE> self.add_random_tile() <NEW_LINE> self.add_random_tile() | Initialize board by creating an array of shape grid_size.
grid_size is assumed to be the same in both dimensions | 625941c2379a373c97cfaaf1 |
def reloadVirtualMachineFromPath_Task(self, configurationPath): <NEW_LINE> <INDENT> return self.delegate("reloadVirtualMachineFromPath_Task")(configurationPath) | Reloads the configuration for this virtual machine from a given datastore path.
This is equivalent to unregistering and registering the virtual machine from a
different path. The virtual machine's hardware configuration, snapshots,
guestinfo variables etc. will be replaced based on the new configuration file.
Other inf... | 625941c28a43f66fc4b54014 |
def add_object(self, draw_object, position="top"): <NEW_LINE> <INDENT> if position == "top": <NEW_LINE> <INDENT> self.draw_objects.append(draw_object) <NEW_LINE> <DEDENT> elif position == "bottom": <NEW_LINE> <INDENT> self.draw_objects.insert(0, draw_object) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.draw_objec... | Add a new object to the canvas.
:param: draw_object -- DrawObject to add
:param position="top": Position to add the object. "top" puts
the object on top of teh other objects.
"bottom" puts them on the bottom of the stack.
A integer puts it in that p... | 625941c2cb5e8a47e48b7a59 |
def forward(self, indices): <NEW_LINE> <INDENT> if indices.dim() == 2: <NEW_LINE> <INDENT> batch_size, seq_size = indices.size() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> batch_size, seq_size = indices.size(0), 1 <NEW_LINE> <DEDENT> if not indices.is_contiguous(): <NEW_LINE> <INDENT> indices = indices.contiguous() ... | Retrieve embeddings corresponding to indices.
See documentation on PyTorch ``nn.Embedding`` for details. | 625941c2fff4ab517eb2f3e7 |
def relative_entropy(args): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument("-i", "--file", required=True, help="") <NEW_LINE> parser.add_argument("-k", "--ksize", required=True, type=int) <NEW_LINE> parser.add_argument("-o", "--output") <NEW_LINE> args = parser.parse_args(args) <N... | Calculate relative entropy of genome.
Args:
args (TODO): TODO
Returns: TODO | 625941c22ae34c7f2600d0de |
def values(self): <NEW_LINE> <INDENT> return self.map(filter_values) | Iterates only values from the stream (last element from the
:py:class:`tuple`). If element is single then it will be used.
:return: new processed :py:class:`Stream` instance.
>>> stream = Stream.range(5)
>>> stream = stream.key_map(lambda item: item ** 3)
>>> stream = stream.values()
>>> list(stream)
... [0, 1, 2, 3,... | 625941c21f5feb6acb0c4b00 |
def _titlecase_handler(self, word, **kwargs): <NEW_LINE> <INDENT> articles = ['a','an','and','as','at','but','by','en','for','if','in', 'of','on','or','the','to','v','v.','via','vs','vs.'] <NEW_LINE> if self.titlecase_articles and word.lower() in articles: <NEW_LINE> <INDENT> return word.title() | This function gets called for every word that is being titlecased.
We will titlecase articles if the user adds the flag.
If we don't return anything then it will be titlecased by the
"titlecase" module itself.
:param word: the word to check on
:rtype: none/string | 625941c260cbc95b062c64ef |
def __init__(self, grid, title): <NEW_LINE> <INDENT> self.grid = grid <NEW_LINE> self.title = title <NEW_LINE> self.map_data = [] <NEW_LINE> self.map_mult_data = [] <NEW_LINE> resources = Ngl.Resources() <NEW_LINE> resources.sfXArray = self.grid.lon_sequence() <NEW_LINE> resources.sfYArray = self.grid.lat_sequence() <N... | Initialize an instance of MapPlots.
Plotting of maps is powered by PyNGL.
:type grid: :class:`.Grid`
:arg grid: The Grid object describing the map data to be plotted.
:arg str title: The title describing the map data. | 625941c215baa723493c3f21 |
def perform(url, data): <NEW_LINE> <INDENT> handle = urlopen(url, urlencode(data)) <NEW_LINE> response = handle.read() <NEW_LINE> decoded = json.loads(response) <NEW_LINE> if decoded['status'] != 'ok': <NEW_LINE> <INDENT> if 'errors' in decoded: <NEW_LINE> <INDENT> raise Exception(decoded['errors']) <NEW_LINE> <DEDENT>... | Perform CDN POST request | 625941c207f4c71912b1142e |
def _handle_reverse(string): <NEW_LINE> <INDENT> logging.info("Reversing string: {}".format(string)) <NEW_LINE> return reverse_success(string[::-1]) | Reverse string | 625941c282261d6c526ab449 |
def station_getinfo(self, id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.station_getinfo_with_http_info(id, **kwargs) | Gets a the info to display in the sign-in station by it's ID. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.station_getinfo(id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request as... | 625941c2187af65679ca50cb |
def decimal_to_hex_dict_string_comp(): <NEW_LINE> <INDENT> dec_list = [str(dec) for dec in range(0, 16)] <NEW_LINE> dec_hex_dict = {digit: hex(int(digit)) for digit in dec_list} <NEW_LINE> return dec_hex_dict | Use a list comprehension to make a dictionary that maps
decimal, 0 - 15, to hex. | 625941c27d847024c06be267 |
def alias(self): <NEW_LINE> <INDENT> return _filter_swig.pfb_arb_resampler_ccf_sptr_alias(self) | alias(pfb_arb_resampler_ccf_sptr self) -> std::string | 625941c28da39b475bd64f1e |
def update(self): <NEW_LINE> <INDENT> self.reset() <NEW_LINE> agent = self.simulation.agent <NEW_LINE> mask = agent.active & self.room.contains_points(agent.position) <NEW_LINE> indices = np.arange(agent.size)[mask] <NEW_LINE> self.strategy[mask ^ True] = 1 <NEW_LINE> self.t_aset = self.t_aset_0 - self.simulation.time_... | Update strategies for all agents. | 625941c2aad79263cf3909eb |
def displayBoard(self, board, tile_w, tile_h, num_rows, num_cols): <NEW_LINE> <INDENT> w = tile_w <NEW_LINE> h = tile_h <NEW_LINE> for row in range(num_rows): <NEW_LINE> <INDENT> for col in range(num_cols): <NEW_LINE> <INDENT> x = col * w + self.game_board_x <NEW_LINE> y = row * h + self.game_board_y <NEW_LINE> if (boa... | - GUI display of the back end 2D array of the game board from the GameBoard class | 625941c2d18da76e23532481 |
def __init__(self, krb5=None): <NEW_LINE> <INDENT> self._krb5 = None <NEW_LINE> self.discriminator = None <NEW_LINE> if krb5 is not None: <NEW_LINE> <INDENT> self.krb5 = krb5 | ProvidersKrb5 - a model defined in Swagger | 625941c28c3a873295158365 |
def test_get_and_set(self): <NEW_LINE> <INDENT> old = SOCO.treble() <NEW_LINE> self.assertIn(old, self.valid_values, NOT_IN_RANGE) <NEW_LINE> for value in [self.valid_values[0], self.valid_values[-1]]: <NEW_LINE> <INDENT> SOCO.treble(value) <NEW_LINE> wait() <NEW_LINE> self.assertEqual(SOCO.treble(), value, NOT_EXP) <N... | Tests if the set functionlity works when given valid arguments | 625941c276d4e153a657eadd |
def testSegmentsOfSizeZero(self): <NEW_LINE> <INDENT> self._runTest(starts=[10,20], ends=[20,30], expStarts=[0, 30], expEnds=[10,len(self.chr1)], expTrackFormatType="Segments", debug=True) | Test that two ajasoned segments do not create a new segment of size 0
:return: | 625941c2ad47b63b2c509f2d |
def requires_https(self, host): <NEW_LINE> <INDENT> return host == "mtred.com" | Return True if the specified host requires HTTPs for balance update. | 625941c2004d5f362079a2e1 |
def __init__(self, pvName, triggerValue, function, display, status, owner, doneValue=0, time=1, iterations=1): <NEW_LINE> <INDENT> PVTrigger.__init__(self, pvName, triggerValue, function, display) <NEW_LINE> self._numIterations = iterations <NEW_LINE> self._triggerTime = time <NEW_LINE> self._period = (self._triggerTim... | Constructor | 625941c24e4d5625662d4387 |
def sample_indep_edges(logits, is_edgesymmetric=False, tau=1.0, hard=False, hard_with_grad=False): <NEW_LINE> <INDENT> if is_edgesymmetric: <NEW_LINE> <INDENT> edge_types = logits.size(2) <NEW_LINE> n = int(0.5 * (1 + np.sqrt(4 * logits.size(1) + 1))) <NEW_LINE> reshaped_logits = logits.view(-1, n, n - 1, edge_types) ... | Sample independent edges given logits.
Args:
logits: Logits of shape (batch_size, n * (n - 1), edge_types).
They correspond to a flattened and transposed adjacency matrix
with the diagonals removed.
We assume the logits are edge-symmetric.
is_edgesymmetric: Whether or not e_ij == e_ji. ... | 625941c2d58c6744b4257c0d |
def peaking(Wn, dBgain, Q=None, BW=None, type='half', analog=False, output='ba'): <NEW_LINE> <INDENT> if Q is None and BW is None: <NEW_LINE> <INDENT> BW = 1 <NEW_LINE> <DEDENT> if Q is None: <NEW_LINE> <INDENT> Q = 1/(2*sinh(ln(2)/2*BW)) <NEW_LINE> <DEDENT> if type in ('half'): <NEW_LINE> <INDENT> A = 10.0**(dBgain/40... | Biquad peaking filter design
Design a 2nd-order analog or digital peaking filter with variable Q and
return the filter coefficients. Used in graphic or parametric EQs.
Transfer function: H(s) = (s**2 + s*(Az/Q) + 1) / (s**2 + s/(Ap*Q) + 1)
Parameters
----------
Wn : float
Center frequency of the filter.
For... | 625941c267a9b606de4a7e68 |
def pre_process(self): <NEW_LINE> <INDENT> start_time = time() <NEW_LINE> to_clean = list(self.data_frame.columns) <NEW_LINE> if self.location in to_clean: <NEW_LINE> <INDENT> self.data_frame = self.clean_locations() <NEW_LINE> <DEDENT> if self.person in to_clean: <NEW_LINE> <INDENT> self.data_frame = self.clean_person... | A wrapper functions that does all the pre-processig. (Except - flattening)
**Returns :**
pandas.DataFrame
A clean and processed pandas DataFrame | 625941c2b830903b967e98ba |
def __init__( self, output_dir=None, output_fname='statistics.tsv', exp_name=None, log_freq=1, ): <NEW_LINE> <INDENT> self.output_dir = output_dir or '/tmp/experiments/%i' % int(time.time()) <NEW_LINE> if not os.path.exists(self.output_dir): <NEW_LINE> <INDENT> os.makedirs(self.output_dir) <NEW_LINE> <DEDENT> output_fi... | Initialize a new Logger.
Args:
output_dir (str): The output directory. If `None`, defaults to a
directory of the form `/tmp/experiments/some-random-number`.
output_fname (str): The output file name.
exp_name (str): The name of the experiment.
log_freq (int): The log frequency. If non-positive, ... | 625941c21f037a2d8b9461ab |
def set_params(self,pars): <NEW_LINE> <INDENT> pass | Set any parameters from a dictionary.
Args:
pars: {string} | 625941c257b8e32f52483447 |
def __repr__(self): <NEW_LINE> <INDENT> return '%s%s' % (self.__class__.__name__, { column: value for column, value in self._to_dict().items() }) | Define a base way to print models | 625941c26aa9bd52df036d50 |
def update(self, time): <NEW_LINE> <INDENT> self.power_up() <NEW_LINE> self.targetting() | Стандартный апдейт (см docs.txt)
:param time: текущее время | 625941c2b57a9660fec3382f |
def __init__(self, templates, database, emitters, auxiliary_dir, dom_implementation_classes, output_dir): <NEW_LINE> <INDENT> super(HtmlDartiumSystem, self).__init__( templates, database, emitters, output_dir) <NEW_LINE> self._auxiliary_dir = auxiliary_dir <NEW_LINE> self._dom_implementation_classes = dom_implementatio... | Prepared for generating wrapping implementation.
- Creates emitter for Dart code. | 625941c2009cb60464c63360 |
def __generate_icasadi_c_interface(self): <NEW_LINE> <INDENT> self.__logger.info("Generating intercafe.c (C interface)") <NEW_LINE> cint_template = OpEnOptimizerBuilder.__get_template('interface.c', 'icasadi') <NEW_LINE> cint_output_template = cint_template.render( meta=self.__meta, problem=self.__problem, build_config... | Generates the C interface file interface.c | 625941c2627d3e7fe0d68dfc |
def __len__(self): <NEW_LINE> <INDENT> return len(self.keys) | :func:`len` of the DataKeySet = :func:`len` of its :attr:`keys`. | 625941c25fdd1c0f98dc01e0 |
@app.route('/states/<state_id>/cities', methods=['GET', 'POST']) <NEW_LINE> def city(state_id): <NEW_LINE> <INDENT> if request.method == 'GET': <NEW_LINE> <INDENT> list = [] <NEW_LINE> for record in City.select().where(City.state == state_id): <NEW_LINE> <INDENT> hash = record.to_hash() <NEW_LINE> list.append(hash) <NE... | Handle GET and POST requests to /states/<state_id>/cities route.
Return a list of all cities in state (according to database) in the case of
a GET request.
Create a new city record in the given state in the database in the case of
a POST request. | 625941c238b623060ff0ad9b |
def lengthOfLongestSubstring(self, s): <NEW_LINE> <INDENT> if s == '': <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> slist = list(s) <NEW_LINE> sameflag = 0 <NEW_LINE> clist =set() <NEW_LINE> cont =0 <NEW_LINE> mxcont =0 <NEW_LINE> mxindex =len(s)-1 <NEW_LINE> for i in range(len(slist)): <NEW_LINE> <INDENT> j =i <NE... | :type s: str
:rtype: int | 625941c2cc0a2c11143dce3d |
def response_ok(file_type, body): <NEW_LINE> <INDENT> headers = { "Date": email.utils.formatdate(usegmt=True), "Connection": "close", "Content-Length": str(len(body)) } <NEW_LINE> if file_type: <NEW_LINE> <INDENT> headers["Content-Type"] = file_type <NEW_LINE> <DEDENT> response = "HTTP/1.1 200 OK\r\n" <NEW_LINE> for ke... | Set up and return 200 response. | 625941c294891a1f4081ba56 |
def _test_forward_logical_and(data): <NEW_LINE> <INDENT> return _test_logical_binary(math_ops.logical_and, data) | One iteration of logical and | 625941c2f8510a7c17cf96a9 |
def __iter__(self): <NEW_LINE> <INDENT> return self | Define the iterator interface.
| 625941c25fc7496912cc392b |
def addcylindrical(self,pos,name = "1", csys = "Global", mergeOff = False, mergeNumber = 0): <NEW_LINE> <INDENT> r, theta ,z = pos <NEW_LINE> return_value, name = self._obj.AddCylindrical(x,theta,z,name,name,csys, mergeOff, mergeNumber) <NEW_LINE> assert return_value == 0 <NEW_LINE> return name | Same as addcartesian but in Cylindrical Coordinates instead. Therefore pos
should be in theform (r, theta, z) | 625941c2507cdc57c6306c84 |
def groupAnagrams(self, strs): <NEW_LINE> <INDENT> ans=[] <NEW_LINE> dic={} <NEW_LINE> for i in strs: <NEW_LINE> <INDENT> s=''.join(sorted(i)) <NEW_LINE> if s not in dic: <NEW_LINE> <INDENT> dic[s]=[i] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dic[s].append(i) <NEW_LINE> <DEDENT> <DEDENT> for i in dic.values(): <NE... | :type strs: List[str]
:rtype: List[List[str]] | 625941c2167d2b6e31218b44 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.