code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def user_enter_state_change_response(): <NEW_LINE> <INDENT> return input('>> ') | Prompts the user to enter a key event response.
nothing -> str | 625941ed5fdd1c0f98dc0769 |
def initialize_model_from_cfg(weights_file, gpu_id=0): <NEW_LINE> <INDENT> return initialize_mixed_model_from_cfg([weights_file], [""], gpu_id) | Initialize a model from the global cfg. Loads test-time weights and
creates the networks in the Caffe2 workspace. | 625941edfff4ab517eb2f974 |
def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.word2index = {} <NEW_LINE> self.index2word = {0: 'SOS', 1: 'EOS'} <NEW_LINE> self.n_words = 2 | 初始化函数中参数name代表传入某种语言的名字 | 625941ed462c4b4f79d1dc03 |
def _update_iot_hub_header(self, request): <NEW_LINE> <INDENT> if request.method in ['PUT', 'POST', 'MERGE', 'DELETE']: <NEW_LINE> <INDENT> request.headers.append(('Content-Length', str(len(request.body)))) <NEW_LINE> <DEDENT> if not request.method in ['GET', 'HEAD']: <NEW_LINE> <INDENT> for name, _ in request.headers:... | Add additional headers for IoT Hub. | 625941eddc8b845886cb5a6b |
def tag(self, terms): <NEW_LINE> <INDENT> tagged_terms = [] <NEW_LINE> for term in terms: <NEW_LINE> <INDENT> tagged_terms.append( [term, self.tags_by_term.get(term, 'NND'), term]) <NEW_LINE> <DEDENT> for idx, tagged_term in enumerate(tagged_terms): <NEW_LINE> <INDENT> for rule in self.rules: <NEW_LINE> <INDENT> rule(i... | See interfaces.ITagger | 625941ed0fa83653e46574ec |
def create_colliders(self): <NEW_LINE> <INDENT> size = self.scaled_size <NEW_LINE> colliders = [] <NEW_LINE> for i in range(0, len(self.tiled_map.layers) - 2): <NEW_LINE> <INDENT> for x, y, image in self.tiled_map.layers[i].tiles(): <NEW_LINE> <INDENT> p = self.tiled_map.get_tile_properties(x, y, i) <NEW_LINE> if p['wa... | Create rectangles to be used as colliders for collision check
:return: list of pygame rect objects | 625941ed851cf427c661aa3e |
def chiffre(chaineIn, cle): <NEW_LINE> <INDENT> listIndiceChaineOut = [] <NEW_LINE> i = 0 <NEW_LINE> chaineOut = "" <NEW_LINE> for char in chaineIn: <NEW_LINE> <INDENT> listIndiceChaineOut.append(alpha.find(char)+alpha.find(cle[i%len(cle)])) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> for indice in listIndiceChaineOut: <NEW_... | Fonction chiffrant une chaîne de caractère donnée à l'aide d'une clé de chiffrement donnée
Chiffrement de Vigenère | 625941edcc0a2c11143dd3c6 |
def main(): <NEW_LINE> <INDENT> n_photons = int(1e5) <NEW_LINE> output_freq = int(1e4) <NEW_LINE> n_bins = 20 <NEW_LINE> tau_max = 7 <NEW_LINE> albedo = 1.0 <NEW_LINE> print("Beginning MCRT simulation...\n") <NEW_LINE> start = timeit.default_timer() <NEW_LINE> hist, theta = transport_photons(n_photons, tau_max, n_bins,... | Main function of the script | 625941ed4c3428357757c859 |
def itkBMPImageIO_cast(*args): <NEW_LINE> <INDENT> return _ITKIOBasePython.itkBMPImageIO_cast(*args) | itkBMPImageIO_cast(itkLightObject obj) -> itkBMPImageIO | 625941ed6fece00bbac2dc79 |
def __init__(self, ann, n, memory_size=None): <NEW_LINE> <INDENT> super().__init__(list(range(n))) <NEW_LINE> self.ann = ann <NEW_LINE> self.memory = Memory(1 if memory_size is None else memory_size) | This class implements a nonlinear Q function approximation using an artificial neural network. The ANN is
trained on the environment state and the Q-Value signals to be able to predict Q-Values given a specific state.
States are provided to the ANN as a list of lists, i.e.:
``[[0, 0], [0, 1], [0, 1]]``
Signals are pro... | 625941ed99cbb53fe6793119 |
def p_for_iter(p): <NEW_LINE> <INDENT> pass | for_iter : FOR expr itervar GIVEN DO statements end | 625941ed1f5feb6acb0c507e |
def create_coa_ack(self, alias=None): <NEW_LINE> <INDENT> return self._create_response(alias,packet.CoAACK) | Creates a coa ack response.
- ``alias:`` alias to identify the session to use. | 625941ed4f88993c3716c596 |
def dump_data(cls_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fp=open("library.json",'r+') <NEW_LINE> json.dump(cls_name.library,fp) <NEW_LINE> fp.close() <NEW_LINE> f=open("library_issue.json",'r+') <NEW_LINE> json.dump(cls_name.library_issue,f) <NEW_LINE> f.close() <NEW_LINE> <DEDENT> except Exception as msg:... | This is to dump data | 625941ed009cb60464c638e1 |
def check_all(properties, count=100, printer=print_result_in_group): <NEW_LINE> <INDENT> checker = PropChecker(count=count) <NEW_LINE> group_name = properties.group_name <NEW_LINE> ps = properties.properties() <NEW_LINE> for prop_name, prop in ps: <NEW_LINE> <INDENT> result = checker.check(prop) <NEW_LINE> printer(resu... | Check all the properties.
:param properties: Properties
The properties that has a bunch of properties to check.
:param count: int
The number of times to check. Default value is 100.
:param printer: function
The function to print the checking result. Default value is print_result. | 625941ed462c4b4f79d1dc04 |
def _metaclass(self): <NEW_LINE> <INDENT> self.__files__[0] = [ ] <NEW_LINE> self.__reldata__[0] = { } <NEW_LINE> return generate_metaclass(self) | Generate base metaclass. The base metaclass is an abstraction of
document model defined by base structures. | 625941ed4e696a04525c9982 |
def _build_log_list(folder, prefix): <NEW_LINE> <INDENT> total_size = 0 <NEW_LINE> binlogs = [] <NEW_LINE> if prefix is not None: <NEW_LINE> <INDENT> for item in os.listdir(folder): <NEW_LINE> <INDENT> name, _ = os.path.splitext(item) <NEW_LINE> if name.upper() == prefix.upper(): <NEW_LINE> <INDENT> itempath = os.path.... | Build a list of all binary log files based on the prefix for the name.
Return total size of all files found.
folder[in] Folder to search
prefix[in] Prefix of log name (e.g. mysql-bin)
return (tuple) (binlogfiles[], total size) | 625941edf7d966606f6aa53f |
def effet(self,robot): <NEW_LINE> <INDENT> if robot.orientation + self.__angle <= 3: <NEW_LINE> <INDENT> estimate = robot.orientation + self.__angle <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for i in range(1,4): <NEW_LINE> <INDENT> if robot.orientation == 4-i and self.__angle >= i: <NEW_LINE> <INDENT> estimate = se... | Le robot pivote
Paramètres
----------
robot: Robot
| 625941ed8c0ade5d55d3eef4 |
def get(self, include_abs, maxauthor, authorcutoff, journalformat=adsJournalFormat.macro): <NEW_LINE> <INDENT> num_docs = 0 <NEW_LINE> ref_BibTex = [] <NEW_LINE> if (self.status == 0): <NEW_LINE> <INDENT> num_docs = self.get_num_docs() <NEW_LINE> if self.enumeration: <NEW_LINE> <INDENT> self.__enumerate_keys() <NEW_LIN... | :param include_abs: if ture include abstract
:param maxauthor:
:param authorcutoff:
:param journalformat:
:return: result of formatted records in a dict | 625941ed1f037a2d8b946731 |
def get_field_type(self, connection, table_name, row): <NEW_LINE> <INDENT> field_params = OrderedDict() <NEW_LINE> field_notes = [] <NEW_LINE> try: <NEW_LINE> <INDENT> field_type = connection.introspection.get_field_type(row.type_code, row) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> field_type = 'TextFiel... | Given the database connection, the table name, and the cursor row
description, this routine will return the given field type name, as
well as any additional keyword parameters and notes for the field. | 625941ede1aae11d1e74a1f1 |
def sampler_finder(DNAs: list, pat_len: int) -> list: <NEW_LINE> <INDENT> ensure_validity(DNAs, pat_len) <NEW_LINE> best_motifs, best_score = one_sampler_finder(DNAs, pat_len) <NEW_LINE> for i in range(19): <NEW_LINE> <INDENT> cur_motifs, cur_score = one_sampler_finder(DNAs, pat_len) <NEW_LINE> if cur_score < best_scor... | Use a randomized sampler algorithm to find good motifs
Runs one_sampler_finder 10000 times, returning best result
:param DNAs: DNA strings to search for shared motifs
:type DNAs: list (of strs)
:param pat_len: the length of motifs to search for
:type pat_len: int
:returns: each string's version of a motif
:rtype: lis... | 625941edf548e778e58cdab4 |
def default_position(self): <NEW_LINE> <INDENT> return self.__default_position | Return the default position (as an integer) of the slider.
OUTPUT:
- an integer 2-tuple
EXAMPLES::
sage: sagenb.notebook.interact.RangeSlider('x', [1..5], (2,3), 'alpha').default_position()
(2, 3) | 625941ed9c8ee82313fbbcac |
def evaluate(string): <NEW_LINE> <INDENT> t = tokenizer(string) <NEW_LINE> if expression(t): <NEW_LINE> <INDENT> print(expression(t)) | >>> from context_free_grammar import *
>>> evaluate('100')
100
>>> evaluate('(100)')
100
>>> evaluate('1 - 20 + 300')
281
>>> evaluate('(((((1))-((20))+((300)))))')
281
>>> evaluate('20 * 4 / 5')
16.0
>>> evaluate('(((((20))*((4))/((5)))))')
16.0
>>> evaluate('1 + 20 * 30 - 400 / 500')
600.2
>>> evaluate('1 + (20*30-40... | 625941eda219f33f34628e96 |
def test_good_update(self): <NEW_LINE> <INDENT> data = json.dumps({ "username" : "user1", "email" : "user1@gmail.com", "password" : "topsecret1", "confirm_password" : "topsecret1"}) <NEW_LINE> response = self.app.put( '/api/v3/users/1', data=data, content_type='application/json', headers=self.admin_header) <NEW_LINE> s... | Test a successful user update | 625941ed3346ee7daa2b32a5 |
def setNodeTextFromHtmlID(html_id, text): <NEW_LINE> <INDENT> pass | Set the text of the object identified by html_id. | 625941ed38b623060ff0b322 |
def _init_properties(self) -> None: <NEW_LINE> <INDENT> model_id = self.datamodel.get_pk_name() <NEW_LINE> if self.list_columns is None and not self.list_model_schema: <NEW_LINE> <INDENT> self.list_columns = [model_id] <NEW_LINE> <DEDENT> if self.show_columns is None and not self.show_model_schema: <NEW_LINE> <INDENT> ... | Lock down initial not configured REST API columns. We want to just expose
model ids, if something is misconfigured. By default FAB exposes all available
columns on a Model | 625941ed3cc13d1c6d3c78ac |
def long_repeat(line): <NEW_LINE> <INDENT> if len(line) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if len(line) == 1: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> max_len = 0 <NEW_LINE> for char, group in itertools.groupby(line): <NEW_LINE> <INDENT> lst = list(group) <NEW_LINE> if len(lst) > max_len: <N... | length the longest substring that consists of the same char | 625941edd58c6744b4258192 |
def setBackground(self, background): <NEW_LINE> <INDENT> self._background = background | Sets background properties | 625941ed7cff6e4e81117eba |
def get_files(img): <NEW_LINE> <INDENT> import re <NEW_LINE> import os <NEW_LINE> PROC_EXPR = re.compile( r'^(?P<path>.*/)?' r'(?P<subject_id>sub-[a-zA-Z0-9]+)' r'(_(?P<session_id>ses-[a-zA-Z0-9]+))?' r'(_(?P<task_id>task-[a-zA-Z0-9]+))?' r'(_(?P<acq_id>acq-[a-zA-Z0-9]+))?' r'(_(?P<rec_id>rec-[a-zA-Z0-9]+))?' r'(_(?P<r... | Find the brainmask and confound files given the bold file.
Parameters
----------
img : str
full path and name of the bold file
Returns
-------
confound : str
full path and name of the confounds file
brainmask : str
full path and name of the brainmask file | 625941ed7b180e01f3dc4d26 |
@app.route('/', methods=['GET', 'POST']) <NEW_LINE> @app.route('/home') <NEW_LINE> def home(): <NEW_LINE> <INDENT> cities = ['London'] <NEW_LINE> if request.method == 'POST': <NEW_LINE> <INDENT> city = request.form.get('city') <NEW_LINE> cities.append(city) <NEW_LINE> <DEDENT> url = 'http://api.openweathermap.org/data/... | Renders the home page. | 625941ed15baa723493c44ae |
def cam(self, old_pos, new_pos, ignore=None): <NEW_LINE> <INDENT> if self.hasParent: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> last_cnx, = (cnx for cnx in self.last_branch_item.connections() if cnx.child == self.parentItem()) <NEW_LINE> last_cnx.setParentItem(None) <NEW_LINE> <DEDENT> except (AttributeError, ValueEr... | Collision avoidance manoeuvre for parallel branches
(for SDL: input, decision answers) | 625941ed498bea3a759b9fe2 |
def test_get_compressor_error(): <NEW_LINE> <INDENT> with pytest.raises(UnsupportedFiletypeError): <NEW_LINE> <INDENT> get_compressor("zip") | Test getting a compressor which is not registered. | 625941ed2ae34c7f2600d665 |
def has_delete_permission(self, request, obj=None): <NEW_LINE> <INDENT> if settings.CMS_PERMISSION and obj is not None: <NEW_LINE> <INDENT> return obj.has_delete_permission(request) <NEW_LINE> <DEDENT> return super(PageAdmin, self).has_delete_permission(request, obj) | Returns True if the given request has permission to change the given
Django model instance. If CMS_PERMISSION are in use also takes look to
object permissions. | 625941edf9cc0f698b140b2b |
def test_get_item_receipt_activity_tags(self): <NEW_LINE> <INDENT> pass | Test case for get_item_receipt_activity_tags
Get the tags for an itemReceiptActivity. # noqa: E501 | 625941ed7047854f462a1938 |
def decode_responsible_party(xml, nsmap): <NEW_LINE> <INDENT> decodings = [ ('abbreviation', False, 'str', 'child::cim:abbreviation'), ('contact_info', False, decode_responsible_party_contact_info, 'child::gmd:contactInfo/gmd:CI_Contact'), ('individual_name', False, 'str', 'child::gmd:individualName/gco:CharacterString... | Decodes an instance of the following type: responsible party.
:param xml: XML from which type is to be decoded.
:type xml: lxml.etree
:param nsmap: XML namespace mappings.
:type nsmap: dict
:returns: A decoded type instance.
:rtype: cim.v1.typeset.shared.ResponsibleParty | 625941ed091ae3566866748a |
def getStats(): <NEW_LINE> <INDENT> size = getCount() <NEW_LINE> topics = list(getTopics()) <NEW_LINE> topics = sorted(topics, key=lambda topic: topic["cat"]) <NEW_LINE> for topic in topics: <NEW_LINE> <INDENT> query = "-d 7 " + topic["query"] <NEW_LINE> err, cursor = websearch(query) <NEW_LINE> if not err: <NEW_LINE> ... | :returns: dictionary {"size": total num statuses,
"cats": dict of stats} where
a stat is a dictionary {"query": str descriptor of topic, "stat":
is slug describing no of entries on topic and % of total} | 625941ed0c0af96317bb871c |
def _read_pct_data_used(host=DOCKER_HOST): <NEW_LINE> <INDENT> info = json.load( urllib.urlopen('{}/info'.format(host.replace('tcp://', 'http://'))) ) <NEW_LINE> driver_status = dict(info['DriverStatus']) <NEW_LINE> for key, value in driver_status.items(): <NEW_LINE> <INDENT> driver_status[key.lower().replace(' ', '_')... | NOTE: This is a fairly naive implementation, as it assumes:
* the docker daemon is not using certificate auth
* the data space unit for the total is in GB
* the possible units for data space used are KB, MB, or GB | 625941ed85dfad0860c3b391 |
def winner(board): <NEW_LINE> <INDENT> for i in range(3): <NEW_LINE> <INDENT> aantalX = 0 <NEW_LINE> aantalO = 0 <NEW_LINE> for j in range(3): <NEW_LINE> <INDENT> if board[i][j] == X: <NEW_LINE> <INDENT> aantalX += 1 <NEW_LINE> <DEDENT> elif board[i][j] == O: <NEW_LINE> <INDENT> aantalO += 1 <NEW_LINE> <DEDENT> <DEDENT... | Returns the winner of the game, if there is one. | 625941ed21bff66bcd684e82 |
def __init__(self, problem, optimized=True): <NEW_LINE> <INDENT> self.defenders = [] <NEW_LINE> self.opponents = [] <NEW_LINE> self.shots = [] <NEW_LINE> self.edges = [] <NEW_LINE> self.dominant_value = 0 <NEW_LINE> self.max_deg_index = 0 <NEW_LINE> self.max_deg = 0 <NEW_LINE> self.deg = [] <NEW_LINE> self.triangles = ... | Construct a new 'Graph' object.
:param problem: The problem to use to construct the graph.
:param optimized (opt): If set to true, a defender will be considered interesting iff it is on at least one edge of the triangles (see below for explanations on those). True by default. Note that this optimizat... | 625941ed099cdd3c635f118d |
def notify_user(object, action, site): <NEW_LINE> <INDENT> if action == 'rejection': <NEW_LINE> <INDENT> user = object.sender <NEW_LINE> label = 'postman_rejection' <NEW_LINE> <DEDENT> elif action == 'acceptance': <NEW_LINE> <INDENT> user = object.recipient <NEW_LINE> parent = object.parent <NEW_LINE> label = 'postman_... | Notify a user. | 625941ed2c8b7c6e89b35cf1 |
def test_scripts(directory: str) -> None: <NEW_LINE> <INDENT> if directory[-1] != '\\' and directory[-1] != '/': <NEW_LINE> <INDENT> directory = ''.join([directory, '/']) <NEW_LINE> <DEDENT> for file in glob.glob(''.join([directory, '*.py'])): <NEW_LINE> <INDENT> if os.path.realpath(file) != os.path.realpath(__file__) ... | This function tests all python scripts in the specfied directory.
Inputs:
==========
directory: string
path to the directory | 625941ed26068e7796caf21c |
def data_to_xls(self, data): <NEW_LINE> <INDENT> out = BytesIO() <NEW_LINE> workbook = xlsxwriter.Workbook(out, {'in_memory': True}) <NEW_LINE> worksheet = workbook.add_worksheet('Data') <NEW_LINE> headers = data.keys() <NEW_LINE> for i, label in enumerate(headers): <NEW_LINE> <INDENT> worksheet.write(0, i, label) <NEW... | convert data to xls | 625941ed4527f215b584c987 |
def set_provider_setting(self, provider, setting_name, setting_value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> provider_settings = getattr(provider, 'settings') <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> setattr(provider, 'settings', {}) <NEW_LINE> provider.settings[setting_name] = setting_valu... | Set a provider specific setting.
Note: This is probably only be used by the test suite to test override settings
post registration so we can assure setting overriding works | 625941ed293b9510aa2c37c6 |
def dispose(self): <NEW_LINE> <INDENT> if self.ui is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> name = self.extended_name <NEW_LINE> if name != "None": <NEW_LINE> <INDENT> self.context_object.on_trait_change( self._update_editor, name, remove=True ) <NEW_LINE> <DEDENT> for name, handler in self._user_from: <N... | Disposes of the contents of an editor.
This disconnects any synchronised values and resets references
to other objects.
Subclasses may chose to override this method to perform additional
clean-up. | 625941ed29b78933be1e5bda |
def eft_history_date_all(self,date): <NEW_LINE> <INDENT> df=self.ts_pro.fund_daily(trade_date=DT(date).tushare()) <NEW_LINE> df['datetime']=pd.to_datetime(df['trade_date'],format='%Y%m%d') <NEW_LINE> df['code']=self.jq.normalize_code(df['ts_code'].tolist()) <NEW_LINE> df['volume']=df['vol']*100 <NEW_LINE> df['money']=d... | 单日ETF所有K线 | 625941ed046cf37aa974d277 |
def ErrHis4(self): <NEW_LINE> <INDENT> return self.query(363) | Error code history, pos. 4. | 625941edeab8aa0e5d26e08f |
def getDate(url): <NEW_LINE> <INDENT> res = urllib.request.urlopen(url).read().decode() <NEW_LINE> return res | 两个获取页面到方法
urllib.request.urlopen()
request.get() 该方法可以应对反爬虫 | 625941edadb09d7d5db6ccc1 |
def clean_redundant(sequence, char): <NEW_LINE> <INDENT> sequence = sequence + ' ' <NEW_LINE> sequence = sequence.split(char) <NEW_LINE> while '' in sequence: <NEW_LINE> <INDENT> sequence.remove('') <NEW_LINE> <DEDENT> sequence = char.join(sequence) <NEW_LINE> return sequence[:-1] | 去除重复的标点 | 625941eda17c0f6771cbe584 |
def isValidWord(word, hand, wordList): <NEW_LINE> <INDENT> if word == '' or word not in wordList: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> new_hand = hand.copy() <NEW_LINE> for letter in word: <NEW_LINE> <INDENT> if new_hand.get(letter, 0) == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> new_hand[... | Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings | 625941edb7558d58953c543e |
def on_toggle_pause(self, type, player, object): <NEW_LINE> <INDENT> if player.is_paused(): <NEW_LINE> <INDENT> image = gtk.image_new_from_stock(gtk.STOCK_MEDIA_PLAY, gtk.ICON_SIZE_SMALL_TOOLBAR) <NEW_LINE> tooltip = _('Continue Playback') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> image = gtk.image_new_from_stock(g... | Called when the user clicks the play button after playback has
already begun | 625941ed29b78933be1e5bdb |
def coil_stretch_transition(): <NEW_LINE> <INDENT> fig = plt.figure(0, figsize=(5, 4)) <NEW_LINE> plt.rc('text', usetex=True) <NEW_LINE> font = {'family' : 'sans-serif', 'serif' : 'Helvetica', 'weight' : 'normal', 'size' : 14} <NEW_LINE> plt.rc('lines', lw=2) <NEW_LINE> plt.rc('font', **font) <NEW_LINE> ax = fig.add... | Plot the figure of coil-stretch transition
:returns: TODO | 625941ed8e05c05ec3eea8ae |
def _sat(lex, varname): <NEW_LINE> <INDENT> _expect_token(lex, {KW_p}) <NEW_LINE> fmt = _expect_token(lex, {KW_sat, KW_satx, KW_sate, KW_satex}).value <NEW_LINE> nvars = _expect_token(lex, {IntegerToken}).value <NEW_LINE> return _sat_formula(lex, varname, fmt, nvars) | Return a DIMACS SAT. | 625941eda79ad161976cc67b |
def update_lecturer_teaching_info(lecturer, subject): <NEW_LINE> <INDENT> try : <NEW_LINE> <INDENT> current_lecturer = Lecturer_teaching_info.objects.get(lecturer__in = [lecturer,]) <NEW_LINE> current_lecturer.update(subject) <NEW_LINE> <DEDENT> except Lecturer_teaching_info.DoesNotExist : <NEW_LINE> <INDENT> new_lectu... | add lecturer_teaching_info to database:
lecturer: a lecturer object
subject: a subject object | 625941ed99fddb7c1c9de8c3 |
@qgsfunction(args='auto', group='FontConversion') <NEW_LINE> def win2uni(value1, feature, parent): <NEW_LINE> <INDENT> return mc(value1, 'wininnwa', 'unicode') | Convert from Win font to Unicode
<h2>Example usage:</h2>
<ul>
<li>win2uni(string)</li>
<li>win2uni(text_field)</li>
</ul> | 625941edac7a0e7691ed45f7 |
def get_BST_Sequenecs(now): <NEW_LINE> <INDENT> wait = [] <NEW_LINE> temple = copy.deepcopy(now) <NEW_LINE> for item in temple: <NEW_LINE> <INDENT> if item.left: <NEW_LINE> <INDENT> if item.left not in wait and item.left not in temple: <NEW_LINE> <INDENT> wait.append(item.left) <NEW_LINE> <DEDENT> <DEDENT> if item.righ... | Take O(n2) time and O(n2) space
:param now: Selected Tree Node
:return: None | 625941ed23849d37ff7b35c0 |
def get_client_login_token(http_body): <NEW_LINE> <INDENT> return gdata.gauth.get_client_login_token_string(http_body) | Returns the token value for a ClientLoginToken.
Reads the token from the server's response to a Client Login request and
creates the token value string to use in requests.
Args:
http_body: str The body of the server's HTTP response to a Client Login
request
Returns:
The token value string for a ClientLogin... | 625941edf7d966606f6aa540 |
def __todict__(self): <NEW_LINE> <INDENT> def convert_datetime(value): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> return value.strftime('%Y-%m-%d') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> <DEDENT> for col in self.__table__.columns: <NEW_LINE> <INDENT> if isinstance(col.type, s... | Method to turn an SA instance into a dict
so we can output to json | 625941ed07f4c71912b119ba |
def load_cookies(self, req, schema): <NEW_LINE> <INDENT> return MultiDictProxy(req.cookies, schema) | Return cookies from the request as a MultiDictProxy. | 625941edb545ff76a891434b |
def _fallback_object_url_to_object_name_and_bucket_name( object_url_keyword_arg_name='object_url', bucket_name_keyword_arg_name='bucket_name', object_name_keyword_arg_name='object_name', ): <NEW_LINE> <INDENT> def _wrapper(func): <NEW_LINE> <INDENT> @functools.wraps(func) <NEW_LINE> def _inner_wrapper(self: "GCSHook", ... | Decorator factory that convert object URL parameter to object name and bucket name parameter.
:param object_url_keyword_arg_name: Name of the object URL parameter
:type object_url_keyword_arg_name: str
:param bucket_name_keyword_arg_name: Name of the bucket name parameter
:type bucket_name_keyword_arg_name: str
:param... | 625941ed2c8b7c6e89b35cf2 |
def sign(self, sk, index, hashflag=SIGHASH_ALL, compressed=True, orphan=False, deterministic=True, network='test'): <NEW_LINE> <INDENT> if isinstance(sk, list) and isinstance(index, int): <NEW_LINE> <INDENT> sk = [sk] <NEW_LINE> <DEDENT> if isinstance(sk, SigningKey): <NEW_LINE> <INDENT> sk = [sk] <NEW_LINE> <DEDENT> i... | Signs a transaction using the provided private key(s), index(es) and hash type. If more than one key and index
is provides, key i will sign the ith input of the transaction.
:param sk: Private key(s) used to sign the ith transaction input (defined by index).
:type sk: SigningKey or list of SigningKey.
:param index: Ind... | 625941ed23849d37ff7b35c1 |
def linear_activation_backward(dA, cache, activation): <NEW_LINE> <INDENT> linear_cache, activation_cache = cache <NEW_LINE> if activation == "relu": <NEW_LINE> <INDENT> dZ = relu_backward(dA, activation_cache) <NEW_LINE> dA_prev, dW, db = linear_backward(dZ, linear_cache) <NEW_LINE> <DEDENT> if activation == "sigmoid"... | Implement the backward propagation for the LINEAR->ACTIVATION layer
Arguments:
dA {np.array} -- post-activation gradient for current layer l
cache {tuple} -- tuple of values
activation {str} -- activation name
Returns:
dA_prev {np.array} -- gradient of the cost with respect to the activation
dW {n... | 625941ed91af0d3eaac9bf53 |
def get_dom_cap_xml(self, arch, machine): <NEW_LINE> <INDENT> emulatorbin = self.get_emulator(arch) <NEW_LINE> virttype = "kvm" if "kvm" in self.get_hypervisors_domain_types()[arch] else "qemu" <NEW_LINE> machine_types = self.get_machine_types(arch) <NEW_LINE> if not machine or machine not in machine_types: <NEW_LINE> ... | Return domain capabilities xml | 625941edb57a9660fec33dc1 |
def _gregorian_to_ssweek(date_value): <NEW_LINE> <INDENT> nextYear = date_value.year + 1 <NEW_LINE> nextYearStart = _ssweek_year_start(nextYear) <NEW_LINE> if date_value >= nextYearStart: <NEW_LINE> <INDENT> year = nextYear <NEW_LINE> yearStart = nextYearStart <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yearStart = _... | Sundaystarting-week year, week and day for the given Gregorian calendar date | 625941edd58c6744b4258193 |
def make_permissions(self, *args, **kwargs): <NEW_LINE> <INDENT> ModelPermissions = collections.namedtuple( 'ModelPermissions', 'model_name groups permissions') <NEW_LINE> groups = [settings.GROUPS] <NEW_LINE> models_with_permissions = [ ModelPermissions('fazenda', groups, ['add', 'change']), ModelPermissions('gado', g... | Tupla nomeada é possivel assim passar o model_name os grupos
Grupos Validos ['GESTORES_FAZENDAS'] ... | 625941ed656771135c3ebdab |
def batch_dataset_eager_fallback(input_dataset, batch_size, output_types, output_shapes, name=None): <NEW_LINE> <INDENT> _ctx = _context.context() <NEW_LINE> if not isinstance(output_types, (list, tuple)): <NEW_LINE> <INDENT> raise TypeError( "Expected list for 'output_types' argument to " "'batch_dataset' Op, not %r."... | This is the slowpath function for Eager mode.
This is for function batch_dataset | 625941ed3617ad0b5ed6842c |
def set_state(self, enabled): <NEW_LINE> <INDENT> api = db_api.get_instance() <NEW_LINE> module_db = api.get_module_info() <NEW_LINE> client = rpc.get_client().prepare(namespace='rating', fanout=True) <NEW_LINE> if enabled: <NEW_LINE> <INDENT> operation = 'enable_module' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> op... | Enable or disable a module.
:param enabled: (bool) The state to put the module in.
:return: bool | 625941ed091ae3566866748b |
def fetch(self): <NEW_LINE> <INDENT> timestamps = [] <NEW_LINE> headers = {'Authorization': 'ApiKey ' + self.api_key} <NEW_LINE> offset = 0 <NEW_LINE> limit = 100 <NEW_LINE> while True: <NEW_LINE> <INDENT> payload = {'imo': self.imo, 'offset': offset, 'limit': limit} <NEW_LINE> request = requests.get(self.url, params=p... | Fetch timestamps from Port Activity App API | 625941ed1d351010ab856050 |
def pop(self): <NEW_LINE> <INDENT> if not self.reversed: <NEW_LINE> <INDENT> while self.stack: <NEW_LINE> <INDENT> self.reversed.append(self.stack.pop()) <NEW_LINE> <DEDENT> <DEDENT> return self.reversed.pop() | Removes the element from in front of queue and returns that element.
:rtype: int | 625941ed76d4e153a657f069 |
def run_migrations_offline(): <NEW_LINE> <INDENT> url = app_config.sqlalchemy_db_url <NEW_LINE> context.configure( url=url, target_metadata=target_metadata, literal_binds=True ) <NEW_LINE> with context.begin_transaction(): <NEW_LINE> <INDENT> context.run_migrations() | Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output. | 625941ed2ae34c7f2600d666 |
def archives(): <NEW_LINE> <INDENT> stories = Story.objects.all() <NEW_LINE> galleries = Gallery.objects.all() <NEW_LINE> articles = Article.objects.all() <NEW_LINE> created = datetime.datetime(2000, 1, 1) <NEW_LINE> year_range = [] <NEW_LINE> for x in stories.datetimes('created', 'year'): <NEW_LINE> <INDENT> if x not ... | Creating Archives navigation for the side bar. We start by grabbing all
the content, which needs to be made more effecient. Then we parse out
the year date times, then the month date times. | 625941ed01c39578d7e75371 |
def main(): <NEW_LINE> <INDENT> args = parse_args() <NEW_LINE> if not os.path.isdir(args.submission_directory): <NEW_LINE> <INDENT> raise SystemExit("Specified submission_directory does not exist or is not a directory") <NEW_LINE> <DEDENT> if not os.path.isfile(args.remote_id_file): <NEW_LINE> <INDENT> raise SystemExit... | Main execution function | 625941edf8510a7c17cf9c36 |
def stop_handling_includes(self, t=None): <NEW_LINE> <INDENT> d = self.dispatch_table <NEW_LINE> d['import'] = self.do_nothing <NEW_LINE> d['include'] = self.do_nothing <NEW_LINE> d['include_next'] = self.do_nothing <NEW_LINE> d['define'] = self.do_nothing <NEW_LINE> d['undef'] = self.do_nothing | Causes the PreProcessor object to stop processing #import,
#include and #include_next lines.
This method will be called when a #if, #ifdef, #ifndef or #elif
evaluates False, or when we reach the #else in a #if, #ifdef,
#ifndef or #elif block where a condition already evaluated True. | 625941eddd821e528d63b6da |
def spherical(self,angles=None): <NEW_LINE> <INDENT> return 0.5 | spherical leaf angle distribution G function | 625941edac7a0e7691ed45f8 |
def break_down_invocation(method_descriptions): <NEW_LINE> <INDENT> cardinalities = {} <NEW_LINE> implementations = {} <NEW_LINE> request_serializers = {} <NEW_LINE> response_deserializers = {} <NEW_LINE> for name, method_description in method_descriptions.iteritems(): <NEW_LINE> <INDENT> cardinality = method_descripti... | Derives an InvocationBreakdown from several RPC method descriptions.
Args:
method_descriptions: A dictionary from RPC method name to
interfaces.RpcMethodInvocationDescription describing the RPCs.
Returns:
An InvocationBreakdown corresponding to the given method descriptions. | 625941ed5fcc89381b1e1bf9 |
def send_email_verify_code(self, receiver, code=None, expire=None): <NEW_LINE> <INDENT> with self.get_client_ctx() as client: <NEW_LINE> <INDENT> param = _thrift_file.EmailVerifyCodeCreationParameter( sender_key=self.sender_key, receiver=receiver, code=code, expire=expire, ) <NEW_LINE> result = client.email_verify_code... | send verify code
:param receiver: email address
:param code: (String) code to send, if None 6-digit number will be used
:param expire: (Int) expire in minutes, if None then no expire
:return: (hash_value, code) | 625941ed097d151d1a22338c |
def read_variables(): <NEW_LINE> <INDENT> global AIRS <NEW_LINE> global RAINS <NEW_LINE> AIRS = TEMP.variables['air'][:] <NEW_LINE> RAINS = RAIN.variables['prate'][:] * 100000 | **Titel: Variablen definieren**
*Beschreibung: Funktion zum Definieren der Variablen*
:variable AIRS: Temperatur
:variable RAINS: Niederschlagsrate | 625941ed67a9b606de4a83ed |
def test_no_unapproved(self): <NEW_LINE> <INDENT> response = self.client.get(reverse('latest')) <NEW_LINE> bad_quote = Quote.objects.get(votes=-4) <NEW_LINE> self.assertNotIn(bad_quote, response.context[-1]['quote_list']) | Tests that unapproved quotes are not shown in listings | 625941ed5e10d32532c5f45b |
def apply_ramp_filter(sinogram, ramp_win=None, filter_name=None, pad=None, pad_mode="edge"): <NEW_LINE> <INDENT> (nrow, ncol) = sinogram.shape <NEW_LINE> if pad is None: <NEW_LINE> <INDENT> pad = int(0.1 * ncol) <NEW_LINE> <DEDENT> sino_pad = np.pad(sinogram, ((0, 0), (pad, pad)), mode=pad_mode) <NEW_LINE> if (ramp_win... | Apply the ramp filter to a sinogram with the option of adding a smoothing
filter.
Parameters
----------
sinogram : array_like
2D rray. Sinogram image.
ramp_win : complex ndarray or None
Ramp window in the Fourier space.
filter_name : {None, "hann", "bartlett", "blackman", "hamming", "nuttall",\
"... | 625941ed2eb69b55b151cded |
def get_all_images(url): <NEW_LINE> <INDENT> soup = bs(requests.get(url).content, "html.parser") <NEW_LINE> urls = [] <NEW_LINE> for img in tqdm(soup.find_all("img"), "Extracting images"): <NEW_LINE> <INDENT> img_url = img.attrs.get("src") <NEW_LINE> if not img_url: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if i... | Returns all image URLs on a single `url` | 625941ed442bda511e8be947 |
def configure_user(self, request, user): <NEW_LINE> <INDENT> logger.warning('Configure user %s', user) <NEW_LINE> user = update_user_profile(request, user) <NEW_LINE> user = call_setup_user(user=user) <NEW_LINE> return user | Configure a new user after creation and return the updated user. | 625941ede64d504609d74d76 |
def get_album_data_by_artist(artist_id, oauth, country="US", limit=50): <NEW_LINE> <INDENT> search_url = ( f"https://api.spotify.com/v1/artists/{artist_id}" f"/albums?include_groups=album,single&country={country}&limit={str(limit)}" ) <NEW_LINE> return [album["name"] for album in get_json_response_dict(oauth, search_ur... | Gets a list of artist's albums
Parameters
----------
artist_id: str
Artist's name / title
oauth: str
OAuth Token retrieved from Spotify
country: str (default is "US")
Country code from within search should be executed
limit: int (default is 50)
Limit of albums to search; current max is 50
Returns
----... | 625941ed0fa83653e46574ee |
def isEnabled(self): <NEW_LINE> <INDENT> return bool() | static bool KWallet.Wallet.isEnabled() | 625941ed1b99ca400220afea |
def __edge_distance_lut(graph : Graph) -> (np.ndarray, list): <NEW_LINE> <INDENT> adj_matr, vertex_keys = create_adjacency_matrix(graph) <NEW_LINE> dists = floyd_warshall(adj_matr) <NEW_LINE> return dists, vertex_keys | Calculate look-up table for edge distances between all vertices. | 625941ed1f5feb6acb0c5080 |
def load_villages_list(self): <NEW_LINE> <INDENT> self.browser.open(self.settings['server_url'] + LINK_CAMPI) <NEW_LINE> page = self.browser.get_current_page() <NEW_LINE> li_elems = page.find('div', {'id': 'sidebarBoxVillagelist'}).find_all('li') <NEW_LINE> for idx,li in enumerate(li_elems): <NEW_LINE> <INDENT> village... | Parse village list | 625941ed94891a1f4081bfe2 |
def test_update_month_category(self): <NEW_LINE> <INDENT> pass | Test case for update_month_category
Update an existing month category # noqa: E501 | 625941ed956e5f7376d713a2 |
def prettify(elem): <NEW_LINE> <INDENT> rough_string = ElementTree.tostring(elem, 'utf-8') <NEW_LINE> reparsed = minidom.parseString(rough_string) <NEW_LINE> return reparsed.toprettyxml(indent=" ") | Return a pretty-printed XML string for the Element. | 625941edf7d966606f6aa541 |
def twitter(request, account_inactive_template='socialregistration/account_inactive.html', extra_context=dict()): <NEW_LINE> <INDENT> client = OAuthTwitter( request, settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET_KEY, settings.TWITTER_REQUEST_TOKEN_URL, ) <NEW_LINE> user_info = client.get_user_info() <... | Actually setup/login an account relating to a twitter user after the oauth
process is finished successfully | 625941ed3539df3088e2e882 |
def __get_random_user(self): <NEW_LINE> <INDENT> users = User.objects.all() <NEW_LINE> x = randint(0, users.count() - 1) <NEW_LINE> return users[x] | Gets a random user from django-auth User model
:return: :class: 'django.contrib.auth.models.User' | 625941ed76e4537e8c351bad |
def get_10x_lr_params(model): <NEW_LINE> <INDENT> b = [] <NEW_LINE> b.append(model.Scale.layer5.parameters()) <NEW_LINE> for j in range(len(b)): <NEW_LINE> <INDENT> for i in b[j]: <NEW_LINE> <INDENT> yield i | This generator returns all the parameters for the last layer of the net,
which does the classification of pixel into classes | 625941ed4d74a7450ccd46fb |
def estimate(self, data, data_against=None): <NEW_LINE> <INDENT> n_rois, n_samples = np.shape(data) <NEW_LINE> ts = np.zeros((n_rois, n_rois, n_samples), dtype=np.complex) <NEW_LINE> avg = np.zeros((n_rois, n_rois)) <NEW_LINE> super().prepare_pairs(n_rois) <NEW_LINE> for pair in self.pairs: <NEW_LINE> <INDENT> u_phases... | Returns
-------
ts : complex array-like, shape(n_channels, n_channels, n_samples)
Estimated PLV time series (complex valued).
avg : array-like, shape(n_channels, n_channels)
Average PLV.
Notes
-----
Called from :mod:`dyconnmap.tvfcgs.tvfcg`. | 625941ed3317a56b8693a181 |
def get_details(self, entity_name, widget_names=None): <NEW_LINE> <INDENT> view = self.navigate_to(self, 'NewDetails', entity_name=entity_name) <NEW_LINE> return view.read(widget_names=widget_names) | Read host values from Host Details page, optionally only the widgets in widget_names
will be read. | 625941ed91f36d47f21aca2f |
def system_exec(cmd, block=True): <NEW_LINE> <INDENT> proc = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) <NEW_LINE> if not block: <NEW_LINE> <INDENT> return -1, '' <NEW_LINE> <DEDENT> return proc.wait(), proc.stdout.read().decode('utf8') | This will block the caller thread until the command terminate | 625941edb7558d58953c543f |
def virtemp(p, t, td): <NEW_LINE> <INDENT> tk = t + ZEROCNK <NEW_LINE> w = 0.001 * mixratio(p, td) <NEW_LINE> vt = (tk * (1. + w / eps) / (1. + w)) - ZEROCNK <NEW_LINE> if not QC(vt): <NEW_LINE> <INDENT> return t <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return vt | Returns the virtual temperature (C) of a parcel. If
td is masked, then it returns the temperature passed to the
function.
Parameters
----------
p : number
The pressure of the parcel (hPa)
t : number
Temperature of the parcel (C)
td : number
Dew point of parcel (C)
Returns
-------
Virtual temperature (C... | 625941ed15baa723493c44b0 |
def run(self, args): <NEW_LINE> <INDENT> rows = args.rows if args.rows < self.max_rows else self.max_rows <NEW_LINE> lyrics = self.get_lyrics(rows) <NEW_LINE> self.be_poetic(lyrics) <NEW_LINE> return None | Writes lines of our lyrics into the chats of the selected worlds. | 625941ed498bea3a759b9fe4 |
def inorder_traversal(self): <NEW_LINE> <INDENT> if self.left is not None: <NEW_LINE> <INDENT> yield from self.left.inorder_traversal() <NEW_LINE> <DEDENT> yield self <NEW_LINE> if self.right is not None: <NEW_LINE> <INDENT> yield from self.right.inorder_traversal() | 中序遍历节点子树 | 625941ed0a50d4780f6673cd |
def _read_array(f, typecode, array_desc): <NEW_LINE> <INDENT> if typecode in [1, 3, 4, 5, 6, 9, 13, 14, 15]: <NEW_LINE> <INDENT> if typecode == 1: <NEW_LINE> <INDENT> nbytes = _read_int32(f) <NEW_LINE> if nbytes != array_desc['nbytes']: <NEW_LINE> <INDENT> warnings.warn("Not able to verify number of bytes from header")... | Read an array of type `typecode`, with the array descriptor given as
`array_desc`. | 625941ed627d3e7fe0d69388 |
def json_read(filename): <NEW_LINE> <INDENT> with open(filename, 'r') as thefile: <NEW_LINE> <INDENT> json_data = json.load(thefile) <NEW_LINE> <DEDENT> themeasurement = json_data["sensorData"] <NEW_LINE> thetime = [] <NEW_LINE> thevalue = [] <NEW_LINE> for mpoint in themeasurement: <NEW_LINE> <INDENT> tmptime = dateti... | Function to read in Json files and convert sensor data
returns measurement data from input file | 625941ed287bf620b61d3f97 |
def make_sklearn_features(results): <NEW_LINE> <INDENT> transforms = {} <NEW_LINE> transforms['title_tfidf'] = TfidfVectorizer() <NEW_LINE> title_tfidf = transforms['title_tfidf'].fit_transform([r['title_text'] for r in results]) <NEW_LINE> transforms['para_tfidf'] = TfidfVectorizer() <NEW_LINE> para_tfidf = transforms... | obsolete. All results don't fit in memory at once | 625941ed8a43f66fc4b54596 |
def disown_fn( job_ids: Annotated[ tp.Sequence[int], Arg(type=int, nargs="*", completer=job_id_completer) ], force_auto_continue=False, ): <NEW_LINE> <INDENT> if len(tasks) == 0: <NEW_LINE> <INDENT> return "", "There are no active jobs" <NEW_LINE> <DEDENT> messages = [] <NEW_LINE> for tid in job_ids or [tasks[0]]: <NEW... | Remove the specified jobs from the job table; the shell will no longer
report their status, and will not complain if you try to exit an
interactive shell with them running or stopped.
If the jobs are currently stopped and the $AUTO_CONTINUE option is not set
($AUTO_CONTINUE = False), a warning is printed containing in... | 625941ed30dc7b7665901e97 |
def seven_btn(): <NEW_LINE> <INDENT> return num_btn(7) | Call num_btn() with the corresponding button value. | 625941ede5267d203edce1cd |
def set_string_function(f, repr=True): <NEW_LINE> <INDENT> if f is None: <NEW_LINE> <INDENT> if repr: <NEW_LINE> <INDENT> return multiarray.set_string_function(_default_array_repr, 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return multiarray.set_string_function(_default_array_str, 0) <NEW_LINE> <DEDENT> <DEDENT> ... | Set a Python function to be used when pretty printing arrays.
Parameters
----------
f : function or None
Function to be used to pretty print arrays. The function should expect
a single array argument and return a string of the representation of
the array. If None, the function is reset to the default NumPy... | 625941ed7047854f462a193a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.