code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def reward_from_events(self, events: List[str]) -> int: <NEW_LINE> <INDENT> game_rewards = { e.COIN_COLLECTED: 1, e.KILLED_OPPONENT: 5, PLACEHOLDER_EVENT: -.1 } <NEW_LINE> reward_sum = 0 <NEW_LINE> for event in events: <NEW_LINE> <INDENT> if event in game_rewards: <NEW_LINE> <INDENT> reward_sum += game_rewards[event] <...
*This is not a required function, but an idea to structure your code.* Here you can modify the rewards your agent get so as to en/discourage certain behavior.
625941cc293b9510aa2c3391
def _filter_prop(bundle): <NEW_LINE> <INDENT> key, value = bundle <NEW_LINE> if key.startswith('_'): return inverse <NEW_LINE> if isinstance(value, classmethod): return inverse <NEW_LINE> if inspect.isfunction(value) or inspect.ismethod(value): return inverse <NEW_LINE> return (not inverse)
Decide whether a property is kept as a data value or a class internal. See wrapping function for full description. :param bundle: Property bundle to examine. :returns: ``True`` or ``False`` according to the property ``bundle``'s status as an internal property.
625941ccec188e330fd5a89a
def __str__(self): <NEW_LINE> <INDENT> return ( "[Square] ({:s}) {:s}/{:s} - {:s}" .format( str(self.id), str(self.x), str(self.y), str(self.size) ) )
Returns an string format of the Rectangle
625941cc4f6381625f114b36
def meyeraux(x): <NEW_LINE> <INDENT> return 35*x**4-84.*x**5+70.*x**6-20.*x**7
Compute the Meyer auxiliary function The Meyer function is .. math:: y = 35 x^4-84 x^5+70 x^6-20 x^7 :param array x: :return: the waveform .. plot:: :include-source: :width: 80% from spectrum import meyeraux from pylab import linspace, plot t = linspace(0, 1, 1000) plot(t, meyeraux(t))
625941cc851cf427c661a60a
def test_basic_sensor_alert_normal(self): <NEW_LINE> <INDENT> target_cmd = os.path.join(os.path.dirname(os.path.abspath(__file__)), "executer_scripts", "exit_code_0.py") <NEW_LINE> sensor = self._create_base_sensor() <NEW_LINE> sensor.sensorDataType = SensorDataType.NONE <NEW_LINE> sensor.data= SensorDataNone() <NEW_LI...
Tests if a Sensor Alert is triggered through the given exit code.
625941cc925a0f43d2549f72
def test_resolve_symkinked_cache(self): <NEW_LINE> <INDENT> with temporary_dir() as realcachedir: <NEW_LINE> <INDENT> with temporary_dir() as symlinkdir: <NEW_LINE> <INDENT> symlink_cache_dir=os.path.join(symlinkdir, 'symlinkedcache') <NEW_LINE> os.symlink(realcachedir, symlink_cache_dir) <NEW_LINE> self.set_options_fo...
Test to make sure resolve works when --ivy-cache-dir is a symlinked path. When ivy returns the path to a resolved jar file, it might be the realpath to the jar file, not the symlink'ed path we are expecting for --ivy-cache-dir. Make sure that resolve correctly recognizes these as belonging in the cache dir and lookup...
625941cc76e4537e8c35176d
def vote_fast(self, old, new): <NEW_LINE> <INDENT> self._calc_vote_lock.acquire() <NEW_LINE> self._last_vote_status = self._last_vote_status - old + new <NEW_LINE> self._calc_vote_lock.release() <NEW_LINE> if self._new_vote: <NEW_LINE> <INDENT> self._new_vote(self._last_vote_status) <NEW_LINE> <DEDENT> return self._las...
This is function usually called by interrupt
625941cc5fc7496912cc3a79
def softmax(x): <NEW_LINE> <INDENT> orig_shape = x.shape <NEW_LINE> if len(x.shape) > 1: <NEW_LINE> <INDENT> x -= x.max(1)[...,np.newaxis] <NEW_LINE> x = np.exp(x)/np.exp(x).sum(1)[...,np.newaxis] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x -= x.max() <NEW_LINE> x = np.exp(x)/np.exp(x).sum() <NEW_LINE> <DEDENT> ass...
Compute the softmax function for each row of the input x. It is crucial that this function is optimized for speed because it will be used frequently in later code. You might find numpy functions np.exp, np.sum, np.reshape, np.max, and numpy broadcasting useful for this task. Numpy broadcasting documentation: http://d...
625941cc76e4537e8c35176e
def __init__(self, vec2d): <NEW_LINE> <INDENT> self.row, self.vec2d = 0, vec2d <NEW_LINE> self.findNext(0)
Initialize your data structure here. :type vec2d: List[List[int]]
625941cc8e7ae83300e4b0c7
@tf_export( 'random.learned_unigram_candidate_sampler', 'nn.learned_unigram_candidate_sampler') <NEW_LINE> @deprecation.deprecated_endpoints(['nn.learned_unigram_candidate_sampler']) <NEW_LINE> def learned_unigram_candidate_sampler(true_classes, num_true, num_sampled, unique, range_max, seed=None, name=None): <NEW_LINE...
Samples a set of classes from a distribution learned during training. This operation randomly samples a tensor of sampled classes (`sampled_candidates`) from the range of integers `[0, range_max)`. The elements of `sampled_candidates` are drawn without replacement (if `unique=True`) or with replacement (if `unique=Fa...
625941cc8c0ade5d55d3eab6
def category(self, category_id, country=None, locale=None): <NEW_LINE> <INDENT> return self._get( "browse/categories/" + category_id, country=country, locale=locale, )
Get info about a category Parameters: - category_id - The Spotify category ID for the category. - country - An ISO 3166-1 alpha-2 country code. - locale - The desired language, consisting of an ISO 639 language code and an ISO 3166-1 alpha-2 country code, joined by an underscore.
625941cc498bea3a759b9baa
def all_phrase_text_for_head(tokens, text, head_index): <NEW_LINE> <INDENT> results = [] <NEW_LINE> for (begin, end) in all_phrases_for_head(tokens, head_index): <NEW_LINE> <INDENT> results.append(text[begin:end]) <NEW_LINE> <DEDENT> return results
Returns the entire phrase containing the head token and its dependents.
625941ccd8ef3951e3243638
def setusage(self): <NEW_LINE> <INDENT> if self.checkusagefilter(None) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> retdict = self.restobject.overwriteparser(self.uname) <NEW_LINE> if retdict is None: <NEW_LINE> <INDENT> retdict = self.restobject.overwriteparser(self.name) <NEW_LINE> <DEDENT> self.soption = Non...
Sets the usage of the attribute parsing.
625941cccc40096d61595a4c
def test_store_settings_value(self): <NEW_LINE> <INDENT> settings['version'] = '1' <NEW_LINE> self.assertEqual(settings['version'], '1')
settings returns stored value
625941cc5510c4643540f4e0
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'jssProject.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you s...
Run administrative tasks.
625941ccaad79263cf390b3c
def put(self, key: str) -> str: <NEW_LINE> <INDENT> base: str = self.base_dir_hashed_path(key) <NEW_LINE> os.makedirs(base, exist_ok=True) <NEW_LINE> for s in subdirs(base): <NEW_LINE> <INDENT> target_key = os.path.join(s, "key") <NEW_LINE> if os.path.exists(target_key) and keyfile_matches_contents(key, target_key): <N...
Receives a key to create a cache directory for. Creates a directory by calculating the MD5 hash, returns the path to the corresponding directory. Expects the directory to only be used to store files, not directories. e.g.: First Directory For key 'something' hashlib.md5(b'something').hexdigest() '437b930db84b8079c2dd...
625941cc01c39578d7e74f36
def reset(self): <NEW_LINE> <INDENT> self.temp_array = self.original <NEW_LINE> self.original = list(self.original) <NEW_LINE> return self.temp_array
Resets the array to its original configuration and return it. :rtype: List[int]
625941cc73bcbd0ca4b2c171
def read_stored_info(target, field=None, timestamped=False): <NEW_LINE> <INDENT> info_file = get_info_filename(target) <NEW_LINE> if not os.path.exists(info_file): <NEW_LINE> <INDENT> old_filename = target + '.sha1' <NEW_LINE> if field == 'sha1' and os.path.exists(old_filename): <NEW_LINE> <INDENT> hash_file = open(old...
Read information about an image. Returns an empty dictionary if there is no info, just the field value if a field is requested, or the entire dictionary otherwise.
625941cc656771135c3eb96a
def test_json(self): <NEW_LINE> <INDENT> assert json.dumps(self.obj.__json__())
Ensure our models can return valid JSON
625941cc23849d37ff7b318a
def ensure_running(self): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> semaphore_tracker.ensure_running() <NEW_LINE> if self._forkserver_alive_fd is not None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> cmd = ('from multiprocessing.forkserver import main; ' + 'main(%d, %d, %r, **%r)') <NEW_LINE> if self....
Make sure that a fork server is running. This can be called from any process. Note that usually a child process will just reuse the forkserver started by its parent, so ensure_running() will do nothing.
625941cc442bda511e8be513
def Fixed_point(f, x): <NEW_LINE> <INDENT> for i in range(20): <NEW_LINE> <INDENT> if approx_eq(x, f(x)): <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> x = f(x) <NEW_LINE> <DEDENT> return None
check if x has a fixed point in relation to f function :param f: function to check converging point :param x: starting and improved guesses :return: the number that the function converge to(fixed point) or None if cant find
625941cc287bf620b61d3b5f
@app.route('/<string:astronaut>') <NEW_LINE> def detail_astronaut(astronaut): <NEW_LINE> <INDENT> astros.get_astros() <NEW_LINE> astro_data = astros.astro_wiki(astronaut) <NEW_LINE> return render_template("detail.html", astro_data=astro_data)
Displays wikipedia data on astronaut.
625941cc7cff6e4e81117a81
def p_horizontalbox(p): <NEW_LINE> <INDENT> p[0] = AST.BoxNode([AST.NumberNode(p[3])] + p[6], 'H')
horizontalbox : HORIZONTALBOX '(' NUMBER ')' '{' contentgroup '}'
625941ccbe8e80087fb20d3e
def _on_White_button(self) -> None: <NEW_LINE> <INDENT> self.first_player = "White" <NEW_LINE> self.white_button.configure(relief = tkinter.SUNKEN) <NEW_LINE> self.black_button.configure(relief = tkinter.RAISED)
sets the first player to the corresponding string given by button and interchanges the selected choice
625941cc30dc7b7665901a62
def search_domains(estruct_dir, proteins, Protein_class, dict_pattern): <NEW_LINE> <INDENT> for query in Protein_class.queries: <NEW_LINE> <INDENT> for protein in proteins: <NEW_LINE> <INDENT> if protein.query_id == query: <NEW_LINE> <INDENT> for pattern in list(dict_pattern.keys()): <NEW_LINE> <INDENT> ungapped_seq = ...
Recorre todas las instancias de 'Protein', y busca en su secuencia de aminoácidos coincidencias con alguna de las expresiones regulares de el diccionario de Prosite. Almacena los matches en la lista 'self.domains' de la instancia correspondiente, en forma de tuplas (accession, start, end).
625941cc462c4b4f79d1d7cc
def set_summary(self, summary_getter): <NEW_LINE> <INDENT> self.summary_getter = summary_getter <NEW_LINE> self._is_builded = False <NEW_LINE> return self
Arguments --------- summary_getter
625941cc796e427e537b06c1
def register(request): <NEW_LINE> <INDENT> if request.is_ajax(): <NEW_LINE> <INDENT> result = dict() <NEW_LINE> result['key'] = CaptchaStore.generate_key() <NEW_LINE> result['image_url'] = captcha_image_url(result['key']) <NEW_LINE> return JsonResponse(result) <NEW_LINE> <DEDENT> if request.method == "POST": <NEW_LINE>...
用户注册
625941cc4527f215b584c552
def _append_identifier(self, label_base): <NEW_LINE> <INDENT> if self.wCheckDelayMedian.value: <NEW_LINE> <INDENT> label_base += 'D[{0}:{1}]_' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> label_base += 'D[{0}]_' <NEW_LINE> <DEDENT> if self.wCheckFrameMedian.value: <NEW_LINE> <INDENT> label_base += 'F[{2}:{3}]_' <NEW_L...
Append identifier to label string for plots.
625941cc10dbd63aa1bd2c9f
def get_endblock(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> start_pt = self.offset.size_as("b") <NEW_LINE> end_pt = self.size.size_as("b") <NEW_LINE> return DiskSpace(str(start_pt + end_pt) + "b") <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise AttributeError("%s does not have valid size d...
Returns the ending 'offset' of this slice, as a DiskSpace
625941cc50812a4eaa59c41d
def getAvailableLetters(lettersGuessed): <NEW_LINE> <INDENT> avabc = list(string.ascii_lowercase) <NEW_LINE> for letter in lettersGuessed: <NEW_LINE> <INDENT> if letter in avabc: <NEW_LINE> <INDENT> avabc.remove(letter) <NEW_LINE> <DEDENT> <DEDENT> return "".join(avabc)
lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters that represents what letters have not yet been guessed.
625941cce1aae11d1e749db2
def getBcMarkerType(self, bc_marker): <NEW_LINE> <INDENT> if bc_marker == "hom_neumann": <NEW_LINE> <INDENT> pg_marker = pg.MARKER_BOUND_HOMOGEN_NEUMANN <NEW_LINE> <DEDENT> elif bc_marker == "mixed": <NEW_LINE> <INDENT> pg_marker = pg.MARKER_BOUND_MIXED <NEW_LINE> <DEDENT> elif bc_marker == "hom_dirichlet": <NEW_LINE> ...
Returns a pygimli marker.
625941cc23849d37ff7b318b
def __unicode__(self): <NEW_LINE> <INDENT> return "{0}: {1}".format(self.name, self.proposal.title)
Build the default value.
625941cc3eb6a72ae02ec5d8
def formatmonthname(self, theyear, themonth, withyear=True): <NEW_LINE> <INDENT> monthname = '%s %s' % (MONTHS[themonth].title(), theyear) <NEW_LINE> return '<tr><th colspan="7" class="month">%s</th></tr>' % monthname
Return a month name translated as a table row.
625941ccac7a0e7691ed41c8
def extract_timeseries_data(df, columns, index_col='activity_dt'): <NEW_LINE> <INDENT> if not df[index_col].is_unique: <NEW_LINE> <INDENT> print("Please pass a dataframe with unique dates (i.e. 1 row per date)") <NEW_LINE> return None <NEW_LINE> <DEDENT> if df[index_col].dtype != '<M8[ns]': <NEW_LINE> <INDENT> df[index...
INPUT: DataFrame, data columns (LIST of STRINGS), index column (STRING) OUTPUT: data (LIST of LISTS) Creates a list of timeseries data, where each index is a unix timestamp and the associated value is a datapoint from the specified column. Lists can be unpacked by indexing or by naming. The index is assumed to be name...
625941ccdd821e528d63b2a4
def _make_request(self, url: str, params: Dict[str, str], headers: Optional[Dict[str, Union[str, int]]] = None) -> Dict: <NEW_LINE> <INDENT> data = requests.get(url=url, params=params, cookies=self.cookie, headers=headers) <NEW_LINE> try: <NEW_LINE> <INDENT> data_dict = data.json() <NEW_LINE> if len(data_dict) == 0: <N...
Makes a request to the given url with the parameters, headers and cookies. :param url: URL to send. :param params: URL parameters to append to the URL. :param headers: dictionary of headers to send.
625941cc4e4d5625662d44d3
@app.after_request <NEW_LINE> def add_header(request): <NEW_LINE> <INDENT> request.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" <NEW_LINE> request.headers["Pragma"] = "no-cache" <NEW_LINE> request.headers["Expires"] = "0" <NEW_LINE> request.headers['Cache-Control'] = 'public, max-age=0' <NEW_LINE> r...
Add headers to both force latest IE rendering engine or Chrome Frame, and also to cache the rendered page for 10 minutes.
625941cc45492302aab5e3be
def supports_colour(): <NEW_LINE> <INDENT> def vt_codes_enabled_in_windows_registry(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import winreg <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> reg_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Con...
Return True if the running system's terminal supports colour, and False otherwise.
625941cccc0a2c11143dcf8c
def getstatus(self): <NEW_LINE> <INDENT> if not os.path.exists(self.statusloc): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> results = [] <NEW_LINE> with open(self.statusloc,"r") as fp: <NEW_LINE> <INDENT> for line in fp: <NEW_LINE> <INDENT> results.append(json.loads(line)) <NEW_LINE> <DEDENT> <DEDENT> return re...
Read the contents of the status file (for checking analysis status)
625941cc4e696a04525c9547
def calcModes(self, n_modes=20, zeros=False, turbo=True): <NEW_LINE> <INDENT> super(bbENM, self).calcModes(n_modes, zeros, turbo)
Calculate normal modes. This method uses :func:`scipy.linalg.eigh` function to diagonalize the Hessian matrix. When Scipy is not found, :func:`numpy.linalg.eigh` is used. :arg n_modes: number of non-zero eigenvalues/vectors to calculate. If **None** is given, all modes will be calculated. :type n_modes: int or No...
625941ccbf627c535bc132ca
def removeDuplicates(self, nums): <NEW_LINE> <INDENT> n = len(nums) <NEW_LINE> if n <= 1: <NEW_LINE> <INDENT> return n <NEW_LINE> <DEDENT> lastDistinctIndex = 0 <NEW_LINE> for i in range(len(nums)): <NEW_LINE> <INDENT> if nums[i] != nums[lastDistinctIndex]: <NEW_LINE> <INDENT> lastDistinctIndex += 1 <NEW_LINE> nums[i],...
:type nums: List[int] :rtype: int
625941cc2c8b7c6e89b358bc
def serve_file(load, fnd): <NEW_LINE> <INDENT> ret = {'data': '', 'dest': ''} <NEW_LINE> required_load_keys = set(['path', 'loc', 'saltenv']) <NEW_LINE> if not all(x in load for x in required_load_keys): <NEW_LINE> <INDENT> log.debug( 'Not all of the required keys present in payload. Missing: %s', ', '.join(required_lo...
Return a chunk from a file based on the data received
625941cc090684286d50ede1
def del_0x(self, arg_i): <NEW_LINE> <INDENT> p = re.compile('\w', flags=re.M | re.I | re.S) <NEW_LINE> w = re.findall(p, arg_i) <NEW_LINE> ww = ''.join(w).upper().split("0X") <NEW_LINE> arg_i = "" <NEW_LINE> for w in ww: <NEW_LINE> <INDENT> if len(w) == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> arg_i += w.zfi...
The fun to delete 0x. 2 bytes 有补0的选择,分隔符默认是逗号 0x12,0x34 --> 1234 0x1,0x23 --> 0123 补0 :return:
625941cc6e29344779a6270d
def get_docker_client(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> client = docker.from_env() <NEW_LINE> client.images.list() <NEW_LINE> <DEDENT> except (requests.exceptions.ConnectionError, docker.errors.DockerException) as e: <NEW_LINE> <INDENT> lastrow = "" <NEW_LINE> if "FileNotFoundError" in e.args[0]: <NEW_LIN...
Gets an authenticated docker client. Returns: docker.client.DockerClient: The docker client Raises: CriticalException: If the client cannot be created
625941cc5f7d997b87174b93
def __len__(self): <NEW_LINE> <INDENT> return self._client.dbsize()
Number of key-value pairs in dictionary/database.
625941ccdc8b845886cb5630
def is_being_redirected(self) -> bool: <NEW_LINE> <INDENT> return not self.stdout.isatty()
Checks if the output is being sent to a terminal or being redirected/piped Returns: bool: Returns true if the output is being redirected/piped
625941cc38b623060ff0aee9
def tag_(self, path: str, payload: Dict, rev: int) -> Dict: <NEW_LINE> <INDENT> p = "{}/tags".format(path) <NEW_LINE> return self._http.post(p, payload, rev=rev)
Tag a revision of a resolver (full path version). :param path: Full path of the resolver (i.e. includes its ID), URL encoded. :param payload: Payload of the tag. :param rev: Last revision of the resolver. :return: The Nexus metadata of the tagged resolver.
625941cc0fa83653e46570b7
def test_post__normal_valid(self): <NEW_LINE> <INDENT> testing_config.sign_in('user1@google.com', 1234567890) <NEW_LINE> with guide.app.test_request_context( self.request_path, data={ 'category': '2', 'name': 'Revised feature name', 'summary': 'Revised feature summary', 'shipped_milestone': '84', }): <NEW_LINE> <INDENT...
Allowed user can edit a feature.
625941cc91f36d47f21ac5ee
def getPlayerName(self,pID): <NEW_LINE> <INDENT> data={'application_id':self.key,'account_id':pID} <NEW_LINE> r = self.post_with_backoff(self.accinfoep,data) <NEW_LINE> try: <NEW_LINE> <INDENT> return json.loads(r.text)['data'][str(pID)]['nickname'] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return None
Parameters: pID: WG player ID Returns: name of player (str)
625941ccbe7bc26dc91cd6fc
def revert(self): <NEW_LINE> <INDENT> if (not QThread.currentThread() == QCoreApplication.instance( ).thread()): <NEW_LINE> <INDENT> QTimer.singleShot(0, self.revert) <NEW_LINE> return <NEW_LINE> <DEDENT> for key in self._mappings: <NEW_LINE> <INDENT> self._on_model_notification(key)
Takes the data stored in the models and displays them in the widgets.
625941cc956e5f7376d70f69
def deleteNode(self, nodeId): <NEW_LINE> <INDENT> for key in self.dicE[nodeId]: <NEW_LINE> <INDENT> del self.dicE[key][nodeId] <NEW_LINE> <DEDENT> del self.dicE[nodeId] <NEW_LINE> self.dicN.pop(nodeId) <NEW_LINE> return None
Remove the specified node. :param nodeId: the node ID (integer). :return: void.
625941cca8370b771705299b
def get_args(request): <NEW_LINE> <INDENT> return json.loads(request.REQUEST.get('djangoajax_args','[]'))
Pulls out positional arguments from a request for use with Django's url reversal mechanism.
625941cc3eb6a72ae02ec5d9
def url_bm(self): <NEW_LINE> <INDENT> quma = str(self.can).encode(self.encoding) <NEW_LINE> return urllib.parse.quote(quma)
url_bm() 将传入的中文实参转为UrlEncode编码
625941cc82261d6c526ab59b
def _first_of_quarter(self, day_of_week=None): <NEW_LINE> <INDENT> return self.with_date(self.year, self.quarter * 3 - 2, 1).first_of('month', day_of_week)
Modify to the first occurrence of a given day of the week in the current quarter. If no day_of_week is provided, modify to the first day of the quarter. Use the supplied consts to indicate the desired day_of_week, ex. Pendulum.MONDAY. :type day_of_week: int or None :rtype: Pendulum
625941cc8a349b6b435e826f
def reference_all_eeg(x_eeg_all): <NEW_LINE> <INDENT> x_eeg_all_copy = x_eeg_all.copy() <NEW_LINE> common_avg = np.mean(x_eeg_all_copy, 0) <NEW_LINE> x_eeg_all_copy = x_eeg_all_copy - common_avg <NEW_LINE> return x_eeg_all_copy
Return common average referenced EEG channels
625941ccfff4ab517eb2f538
def topic_get(self, topic_path): <NEW_LINE> <INDENT> conn = self._connection <NEW_LINE> return conn.api_request(method='GET', path='/%s' % (topic_path,))
API call: retrieve a topic See: https://cloud.google.com/pubsub/reference/rest/v1/projects.topics/get :type topic_path: string :param topic_path: the fully-qualified path of the topic, in format ``projects/<PROJECT>/topics/<TOPIC_NAME>``. :rtype: dict :returns: ``Topic`` resource returned from th...
625941cc3539df3088e2e447
def resnet18(**kwargs): <NEW_LINE> <INDENT> model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) <NEW_LINE> return model
Constructs a ResNet-18 model. Args:
625941cc236d856c2ad448d6
def report_error(error, quiet=False): <NEW_LINE> <INDENT> if not quiet: <NEW_LINE> <INDENT> sys.stderr.write('ERROR: ' + error + '\n')
Formats the error message and prints it to stderr :param error: string containing error text :param quiet: if True, don't report errors
625941cc283ffb24f3c559fd
def validate_field(s): <NEW_LINE> <INDENT> if s: <NEW_LINE> <INDENT> return bool(valid_numeric.match(s)) <NEW_LINE> <DEDENT> return True
Checks if a field is a valid numeric or progress value
625941ccd58c6744b4257d5c
def registerTimeLayer( self, timeLayer ): <NEW_LINE> <INDENT> self.timeLayerList.append( timeLayer ) <NEW_LINE> if len( self.timeLayerList ) == 1: <NEW_LINE> <INDENT> self.setProjectTimeExtents(timeLayer.getTimeExtents()) <NEW_LINE> if self.isFirstRun: <NEW_LINE> <INDENT> self.setCurrentTimePosition(self.projectTimeExt...
Register a new layer for management and update the project's temporal extent
625941ccd4950a0f3b08c44b
def _call(self, func, *args, **kwargs): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> current_state = self._check_state() <NEW_LINE> if current_state == OPEN: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> result = func(*args, **kwargs) <NEW_LINE> <DEDENT> except self._allowed_except...
Wraps decorated function and watches for successes and failures Args: func(function): decorated function *args: args passed to decorated function **kwargs: kwargs passed to decorated function
625941cc30c21e258bdfa599
def is_clause_satisfied(valuation_list, clause): <NEW_LINE> <INDENT> for literal in clause: <NEW_LINE> <INDENT> if literal < 0: <NEW_LINE> <INDENT> v = 1 - valuation_list[-literal - 1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> v = valuation_list[literal - 1] <NEW_LINE> <DEDENT> if v == 1: <NEW_LINE> <INDENT> return...
Returns True if clause is true (satisfied) or False if not satisfied.
625941cc44b2445a33932192
def process_nodal_element(elem): <NEW_LINE> <INDENT> nodal.process_nodal_element(elem) <NEW_LINE> if elem.isNonlinear: <NEW_LINE> <INDENT> create_additional_indexes(elem)
Process element for nodal analysis
625941cc63f4b57ef0001216
@cythonized("u,v") <NEW_LINE> def dmp_from_sympy(f, u, K): <NEW_LINE> <INDENT> if not u: <NEW_LINE> <INDENT> return dup_from_sympy(f, K) <NEW_LINE> <DEDENT> v = u-1 <NEW_LINE> return dmp_strip([ dmp_from_sympy(c, v, K) for c in f ], u)
Convert ground domain of ``f`` from SymPy to ``K``. Examples ======== >>> from sympy import S >>> from sympy.polys.domains import ZZ >>> from sympy.polys.densebasic import dmp_from_sympy >>> dmp_from_sympy([[S(1)], [S(2)]], 1, ZZ) == [[ZZ(1)], [ZZ(2)]] True
625941cc5166f23b2e1a5255
def scan_ports(ip: Union[str, IPvAnyAddress]) -> ScanResults: <NEW_LINE> <INDENT> if ip == 'localhost': <NEW_LINE> <INDENT> ip = '127.0.0.1' <NEW_LINE> <DEDENT> ip = str(ip) <NEW_LINE> nmap = nmap3.NmapScanTechniques() <NEW_LINE> scan_result = nmap.nmap_tcp_scan(ip, args='-p0-') <NEW_LINE> ports = scan_result[ip]['port...
Scan for listening ports on given IP address and return all WebServers found, mapped with their respective port. In order to detect web servers, listening ports are filtered by protocol: http(s). TODO: Perform a GET request to each listening ports which uses http(s) in order to make sure they return a web page?? TODO: ...
625941cce8904600ed9f2028
def index(self, name, item): <NEW_LINE> <INDENT> uid = IUIDStrategy(item).getuid() <NEW_LINE> self.catalog.index(self.signature, uid, names=(name,))
Get UID for item, then index in catalog for named subscription relationship of adapted subscriber to the item uid
625941cc1d351010ab855c18
def score(self): <NEW_LINE> <INDENT> s = list(self.successes) <NEW_LINE> return len(s)
Returns the number of successes this team has had.
625941cce8904600ed9f2029
def print(self): <NEW_LINE> <INDENT> print("Cat: {}".format(self.pet_name)) <NEW_LINE> for k in self.__dict__.keys(): <NEW_LINE> <INDENT> if k == "pet_name": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> print("-- {}: {}".format(k, getattr(self, k)))
Print method for debugging.
625941cc30c21e258bdfa59a
def tearDown(self): <NEW_LINE> <INDENT> self.db_session.close() <NEW_LINE> self.db_engine.dispose()
Discard sqlite DB
625941cc5fdd1c0f98dc032f
def __init__(self, log): <NEW_LINE> <INDENT> self.logger = log
Logger to be used for error messaging redirection :param log: logger :rtype log: Logger
625941cc2ae34c7f2600d22d
def kitty(self): <NEW_LINE> <INDENT> global kitty_ <NEW_LINE> target = self.args[0] or self.nick <NEW_LINE> self.irc.send_action(self.recipient, 'кинул кошечку в %s, та %s' % ( target, random.choice(kitty_)))
Бросание котиками
625941cc6aa9bd52df036ea1
def imageSize(self, path, pageNumber=None): <NEW_LINE> <INDENT> if isinstance(path, self._imageClass): <NEW_LINE> <INDENT> return path.size() <NEW_LINE> <DEDENT> _hasPixels = False <NEW_LINE> if isinstance(path, AppKit.NSImage): <NEW_LINE> <INDENT> rep = path <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(...
Return the `width` and `height` of an image. .. downloadcode:: imageSize.py print(imageSize("http://f.cl.ly/items/1T3x1y372J371p0v1F2Z/drawBot.jpg"))
625941ccd6c5a10208144147
def predict_av(self, Y, compgrad=False): <NEW_LINE> <INDENT> f, df = self.respsurf.predict(Y, compgrad) <NEW_LINE> return f, df
Compute the value of the response surface given values of the active variables. :param ndarray Y: M-by-n matrix containing points in the range of active variables to evaluate the response surface. :param bool compgrad: Determines if the gradient of the response surface with respect to the active variables is c...
625941cc1b99ca400220abae
def oauthclient_create(self, name, redirect_uri): <NEW_LINE> <INDENT> payload = {'name': name, 'redirect_uri': redirect_uri} <NEW_LINE> r = self._http_resource( method='POST', resource=('oauth', 'clients'), data=self._h._resource_serialize(payload) ) <NEW_LINE> r.raise_for_status() <NEW_LINE> item = self._resource_dese...
Creates an OAuthClient with the given name and redirect_uri
625941cc16aa5153ce362575
def test_correct_title_name_json(self): <NEW_LINE> <INDENT> PersonFB.create() <NEW_LINE> self.client.get(reverse('requests')) <NEW_LINE> c = self.client.get(reverse('ajax_requests'), HTTP_X_REQUESTED_WITH='XMLHttpRequest').content <NEW_LINE> title = re.match(r'.+title": "(.*Requests)",.+', c).groups()[0] <NEW_LINE> sel...
Test to check correct title name in JSON-response
625941cc8c0ade5d55d3eab7
def title_case(field_names): <NEW_LINE> <INDENT> collection_type = type(field_names) <NEW_LINE> return collection_type(n.title() for n in field_names)
Return new collection of strings converted to title case
625941cc283ffb24f3c559fe
def get_non_break_points(self) -> Set[int]: <NEW_LINE> <INDENT> non_break_points = [] <NEW_LINE> for before, after in self.non_breaks: <NEW_LINE> <INDENT> for match in re.finditer(u'({})({})'.format(before, after), self.source_text): <NEW_LINE> <INDENT> non_break_points.extend(range(match.start(1), match.end(1)+1)) <NE...
Return segment non break points
625941cc627d3e7fe0d68f4c
def clean(self): <NEW_LINE> <INDENT> self.delete_data_dir() <NEW_LINE> self.clean_triplestore() <NEW_LINE> if self.galaxy_history: <NEW_LINE> <INDENT> self.delete_galaxy_history()
Clean
625941cc57b8e32f52483597
def solution(A, target): <NEW_LINE> <INDENT> remaining = {} <NEW_LINE> combinations = [] <NEW_LINE> for count, value in enumerate(A): <NEW_LINE> <INDENT> if value in remaining: <NEW_LINE> <INDENT> combinations.append([remaining[value], count]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> remaining[target - value] = va...
Similar to src.arrays.two_sum, find all the combinations that can be added up to reach a given target. Given that all values are unique. >>> solution([1, 2, 3, 4, 5], 5) 2 >>> solution([3, 4, 5, 6], 9) 2
625941cc091ae3566866705b
def check_update(self, root, options=None): <NEW_LINE> <INDENT> root = utils.get_etree_root(root) <NEW_LINE> options = options or DEFAULT_UPDATE_OPTIONS <NEW_LINE> if options.check_versions: <NEW_LINE> <INDENT> self._check_version(root) <NEW_LINE> self._cybox_updater._check_version(root) <NEW_LINE> <DEDENT> duplicates ...
Determines if the input document can be upgraded. Args: root: The XML document. This can be a filename, a file-like object, an instance of ``etree._Element`` or an instance of ``etree._ElementTree``. options (optional): A ``ramrod.UpdateOptions`` instance. If ``None``, ``ramrod.DEFAULT_...
625941cc56b00c62f0f14756
def __init__(self, name='Unknown', model_list=[], extend_network=True): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._default_model = None <NEW_LINE> self._model_by_id = {} <NEW_LINE> self._known_ids = None <NEW_LINE> self._load_models(model_list) <NEW_LINE> self._extend_network = extend_network <NEW_LINE> ret...
Constructor
625941cc462c4b4f79d1d7cd
def get_log_melspectrogram(audio_file): <NEW_LINE> <INDENT> samples, _ = librosa.load(audio_file, cfg.SAMPLING_RATE) <NEW_LINE> mels = librosa.feature.melspectrogram(samples, cfg.SAMPLING_RATE, n_mels=cfg.N_MELS, n_fft=cfg.FFT_WINDOW_SIZE, hop_length=cfg.HOP_LENGTH) <NEW_LINE> log_mels = librosa.amplitude_to_db(mels, r...
computed from audio at `SAMPLING_RATE` Hz and 16 bits per sample, with `N_MELS` frequency values for each frame. Frames and hop sizes are `FFT_WINDOW_SIZE` and `HOP_LENGTH` samples, respectively.
625941ccf548e778e58cd67a
def get_uv_map(mesh_item): <NEW_LINE> <INDENT> uv_maps = moopy.vertex_maps.VMapCollection(mesh_item) <NEW_LINE> uv_maps.update_selected(weight=False, morph=False, other=False) <NEW_LINE> if len(uv_maps) == 0: <NEW_LINE> <INDENT> raise NotImplemented() <NEW_LINE> <DEDENT> elif len(uv_maps) > 1: <NEW_LINE> <INDENT> raise...
Get the uv map we are going to work with.
625941cc596a897236089bbd
def validate_json_dict(value): <NEW_LINE> <INDENT> val = validate_json(value, python_type=dict) <NEW_LINE> return val if val else {}
Shortcut to validate_json(value, python_type=dict) :param value: The text field value
625941ccd10714528d5ffddf
def inference(self): <NEW_LINE> <INDENT> self.embedded_words = tf.nn.embedding_lookup(self.Embedding, self.input_x) <NEW_LINE> lstm_fw_cell = rnn.BasicLSTMCell(self.hidden_size) <NEW_LINE> lstm_bw_cell = rnn.BasicLSTMCell(self.hidden_size) <NEW_LINE> if self.dropout_keep_prob is not None: <NEW_LINE> <INDENT> lstm_fw_ce...
main computation graph here: 1. embeddding layer, 2.Bi-LSTM layer, 3.concat, 4.FC layer 5.softmax
625941ccd10714528d5ffde0
def data_output_dir(self, event): <NEW_LINE> <INDENT> self.data_dir = self.view1.ask_user_for_dir( message="Choose a directory", defaultPath=self.data_dir, )
Select a different directory to save experimental results
625941cc76d4e153a657ec2e
def get_account_balances(self, address: str, **query_params) -> dict: <NEW_LINE> <INDENT> url_params = 'accounts', address, 'balances' <NEW_LINE> return self._call(url_params, query_params)
Get all balances held or owed by a specific XRP Ledger account. Reference: https://developers.ripple.com/data-api.html#get-account-balances
625941cca05bb46b383ec91e
def getWysiwygField(self, name, value): <NEW_LINE> <INDENT> class MyField: <NEW_LINE> <INDENT> __name__ = name <NEW_LINE> required = False <NEW_LINE> default = value <NEW_LINE> missing_value = None <NEW_LINE> <DEDENT> request = self.request <NEW_LINE> request.form = {} <NEW_LINE> field = WYSIWYGWidget(MyField(), reques...
generates a WYSIWYG field containing value
625941cc8da39b475bd65070
def write_roster(teams, filename): <NEW_LINE> <INDENT> with open(filename, 'w') as file: <NEW_LINE> <INDENT> for team_name, players in teams.items(): <NEW_LINE> <INDENT> file.write(team_name+"\n") <NEW_LINE> file.write("="*len(team_name)+"\n\n") <NEW_LINE> for player in players: <NEW_LINE> <INDENT> file.write("{}, {}, ...
Iterates through the list of teams generated and writes the team rosters to file in the filename provided
625941cc67a9b606de4a7fb7
def with_reset_hour(self, reset_hour): <NEW_LINE> <INDENT> self.set_reset_hour(reset_hour) <NEW_LINE> return self
期間内の取得量をリセットする時を設定 :param reset_hour: 期間内の取得量をリセットする時 :type reset_hour: int :return: this :rtype: UpdateCounterMasterRequest
625941cc293b9510aa2c3393
@app.route("/publish_walk", methods=["GET", "POST"]) <NEW_LINE> def publish_walk(): <NEW_LINE> <INDENT> if request.method == "POST": <NEW_LINE> <INDENT> if 'walk_image' in request.files: <NEW_LINE> <INDENT> walk_image = request.files['walk_image'] <NEW_LINE> mongo.save_file(walk_image.filename, walk_image) <NEW_LINE> w...
From the Walks page, a user can create their own walk. A modal will create this and push the data into the MongoDb along with an image if the user chooses one.
625941cc66656f66f7cbc2a7
def mark_region_from_array(self,*args, **kwargs): <NEW_LINE> <INDENT> self.window.mark_region_from_array(*args,**kwargs)
mark regions on the viewer with a list of tuples as input
625941cc4f6381625f114b37
def __init__(self): <NEW_LINE> <INDENT> self.files = {} <NEW_LINE> self.sub_process = None <NEW_LINE> self.pid = os.getpid()
Constructor
625941cc4f6381625f114b38
def get_linear_inequalities(self): <NEW_LINE> <INDENT> if self.Y is None: <NEW_LINE> <INDENT> self.Y = self.get_zonotope_vertices() <NEW_LINE> <DEDENT> n = self.Y.shape[1] <NEW_LINE> if n == 1: <NEW_LINE> <INDENT> A = np.array([[1],[-1]]) <NEW_LINE> b = np.array([[max(self.Y)],[min(self.Y)]]) <NEW_LINE> return A, b <N...
Returns the linear inequalities defining the zontope vertices, i.e., Ax<=b. :param Subspaces self: An instance of the Subspaces object. :return: **A**: The matrix for setting the linear inequalities. :return: **b**: The right-hand-side vector for setting the linear inequalities.
625941cc851cf427c661a60c
def claim_task(self, job_id, new_owner, min_try_time=0, claim_timeout=CLAIM_TIMEOUT): <NEW_LINE> <INDENT> claim_start = time.time() <NEW_LINE> while True: <NEW_LINE> <INDENT> tasks = self.storage.get_tasks(job_id, status="pending", max_fetch=10) <NEW_LINE> if len(tasks) == 0: <NEW_LINE> <INDENT> if time.time() - claim_...
Returns None if no unclaimed ready tasks. Otherwise returns instance of Task
625941cc66673b3332b9218e
def test_lessthan(self): <NEW_LINE> <INDENT> self.assertEqual(OpenEndedChild.sanitize_html(self.text_lessthan_noencd), self.text_lessthan_encode)
Tests that `<` in text context is handled properly
625941cc7047854f462a1507
def set_false(self, answer_id): <NEW_LINE> <INDENT> user_preferred = False <NEW_LINE> query = """UPDATE answers SET user_preferred={0}""".format( user_preferred) <NEW_LINE> con = self.db <NEW_LINE> cursor = con.cursor() <NEW_LINE> cursor.execute(query) <NEW_LINE> con.commit() <NEW_LINE> return True
method to set user prefered to false before an owner of a quiz updates any of the answer.This allows the user to change his/her prefered answer and also to only accept one answer
625941cc5fc7496912cc3a7b
def get_pose(self, wait=False): <NEW_LINE> <INDENT> return self.get_transform(wait)
get current transform from base to to tcp
625941cc76e4537e8c351770
def commit_write_group(self): <NEW_LINE> <INDENT> if self._write_group is not self.get_transaction(): <NEW_LINE> <INDENT> raise errors.BzrError('mismatched lock context %r and ' 'write group %r.' % (self.get_transaction(), self._write_group)) <NEW_LINE> <DEDENT> result = self._commit_write_group() <NEW_LINE> self._writ...
Commit the contents accrued within the current write group. :seealso: start_write_group. :return: it may return an opaque hint that can be passed to 'pack'.
625941cce64d504609d7493d
def test_no_children(base_endpoint, server_rule_factory, configured_application_client, apply_rule): <NEW_LINE> <INDENT> preparator = RuleFactoryPreparator(server_rule_factory) <NEW_LINE> preparator.prepare_composite_rule(composite_rule_class=CompositeRule) <NEW_LINE> composite_rule = CompositeRule(rule_type=RuleType.C...
Check that composite rule is not triggered without children. 1. Prepare composite rule in the rule factory. 2. Create a composite rule and set successful response for it. 3. Make a request to the base endpoint. 4. Check that the rule does not find a match.
625941cc57b8e32f52483598
@register.tag <NEW_LINE> def minify_js(parser, token): <NEW_LINE> <INDENT> nodelist = parser.parse(('endminify_js',)) <NEW_LINE> parser.delete_first_token() <NEW_LINE> return MinifyNode(nodelist)
Block tag that minifies the JavaScript it contains.
625941cd99fddb7c1c9de48e