code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def init_app(app, **kwargs): <NEW_LINE> <INDENT> api_v1.add_oauth_scope( 'programming_languages:read', "Provide access to programming language details" ) <NEW_LINE> api_v1.add_oauth_scope( 'programming_languages:write', "Provide write access to programming language details" ) <NEW_LINE> from . import models, resources ... | Init programming languages module. | 625941d4a8ecb033257d32c6 |
def _read_source_lines(self, c_file, sourcefile): <NEW_LINE> <INDENT> if self._parsed_c_files is None: <NEW_LINE> <INDENT> self._parsed_c_files = {} <NEW_LINE> <DEDENT> if c_file in self._parsed_c_files: <NEW_LINE> <INDENT> code_lines = self._parsed_c_files[c_file] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> code_lin... | Parse a Cython generated C/C++ source file and find the executable
lines. Each executable line starts with a comment header that states
source file and line number, as well as the surrounding range of source
code lines. | 625941d47b180e01f3dc49f5 |
@application.route('/messages', methods=['GET', 'POST']) <NEW_LINE> def messages(): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> message = request.get_json() <NEW_LINE> application.logger.info("Posting message %s" % message.get('message')) <NEW_LINE> result = validate_message(message) <NEW_LINE>... | /messages collection allows POST of new messages and GET of all messages | 625941d456b00c62f0f14854 |
@doublewrap <NEW_LINE> def define_scope(function, scope=None, *args, **kwargs): <NEW_LINE> <INDENT> attribute = '_cache_' + function.__name__ <NEW_LINE> name = scope or function.__name__ <NEW_LINE> @property <NEW_LINE> @functools.wraps(function) <NEW_LINE> def decorator(self): <NEW_LINE> <INDENT> if not hasattr(self, a... | A decorator for functions that define TensorFlow operations. The wrapped
function will only be executed once. Subsequent calls to it will directly
return the result so that operations are added to the graph only once.
The operations added by the function live within a tf.variable_scope(). If
this decorator is used with... | 625941d423849d37ff7b3289 |
def cuboid(self, P, a, b, c): <NEW_LINE> <INDENT> return Cuboid(self, P, a, b, c) | `P` -- a tupe (x,y) that gives the lower left point.
`a,b,c` the size | 625941d401c39578d7e75036 |
def test1_sanity_nogroup(self): <NEW_LINE> <INDENT> errors, parameters, _ = clam.common.data.processparameters(self.postdata, self.nogroups) <NEW_LINE> self.assertFalse(errors) <NEW_LINE> self.assertTrue(parameters[0].id == 'teststring') <NEW_LINE> self.assertTrue(parameters[1].id == 'testchoice') <NEW_LINE> self.asser... | Parameter Processing - Sanity check (no group) | 625941d40383005118ecf7dc |
def parse(self, response): <NEW_LINE> <INDENT> sel = Selector(response) <NEW_LINE> people_sel = sel.xpath('//div[@class="row"]') <NEW_LINE> for barclay_sel in people_sel: <NEW_LINE> <INDENT> item = University() <NEW_LINE> name = barclay_sel.xpath('//div[@class="well"]/h4/strong/text()').extract() <NEW_LINE> if name: <N... | Parse profiles page | 625941d4711fe17d82542563 |
def mp_run_zygosity_probabilities(args): <NEW_LINE> <INDENT> return zygosity_probabilities(args[0], args[1], 0, args[2]) | Unpacks args when running zygosity_probabilities with multiprocessing. | 625941d4090684286d50eee1 |
def __len__(self): <NEW_LINE> <INDENT> return len(self._concepts) | Return the number of concepts in the lattice. | 625941d4e8904600ed9f2129 |
def field_booster(fieldname, factor=2.0): <NEW_LINE> <INDENT> def booster_fn(obj): <NEW_LINE> <INDENT> if obj.is_leaf() and obj.field() == fieldname: <NEW_LINE> <INDENT> obj = copy.deepcopy(obj) <NEW_LINE> obj.boost *= factor <NEW_LINE> return obj <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return obj <NEW_LINE> <DED... | Returns a function which will boost the given field in a query tree | 625941d4e5267d203edcde95 |
def assign_numbers(old_SS, new_SS, overlap_matrix, num_of_ss): <NEW_LINE> <INDENT> new_SS_accounted_for, old_SS_accounted_for = [], [] <NEW_LINE> SS_claims = [] <NEW_LINE> for icolumn, vcolumn in enumerate(overlap_matrix.T): <NEW_LINE> <INDENT> if sum(vcolumn) == 0: <NEW_LINE> <INDENT> new_SS[icolumn].number = num_of_s... | Update the numbers in a list of new sunspots, based on the overlap
Parameters
----------
old_SS = list of sunspots at some time t-1
sunspots2 = list of sunspots at some time t
overlap_matrix = matrix of overlap (in pixels)
num_of_ss = highest number sunspot yet seen
Returns
------
old_SS = list of sunspots at some ti... | 625941d44e696a04525c9646 |
def delete(self, users=None): <NEW_LINE> <INDENT> topic = Topic.query. filter_by(forum_id=self.forum_id). order_by(Topic.last_post_id.desc()).limit(2).offset(0).all() <NEW_LINE> if topic and topic[0].id == self.id: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.forum.last_post_id = topic[1].las... | Deletes a topic with the corresponding posts. If a list with
user objects is passed it will also update their post counts
:param users: A list with user objects | 625941d4377c676e912723a3 |
def Conv2D(x, filters, kernel, gain=np.sqrt(2), use_wscale=False, name=None, **unused_kwargs): <NEW_LINE> <INDENT> stddev = layer_init_stddev([kernel, kernel, x.shape[1], filters], gain=gain) <NEW_LINE> if use_wscale: <NEW_LINE> <INDENT> weight_init = tf.keras.initializers.RandomNormal() <NEW_LINE> x = tf.keras.layers.... | Build a 2D convolutional layer. | 625941d4a4f1c619b28b0230 |
def run(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._runHandler() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.log.exception( "Declining node request %s due to exception in " "NodeRequestHandler:", self.request.id) <NEW_LINE> self.decline_request() <NEW_LINE> self.unlockNodeSet(clear_allo... | Execute node request handling.
This code is designed to be re-entrant. Because we can't always
satisfy a request immediately (due to lack of provider resources), we
need to be able to call run() repeatedly until the request can be
fulfilled. The node set is saved and added to between calls. | 625941d42c8b7c6e89b359bb |
def _generate(self, feature_map_shape_list, im_height=1, im_width=1): <NEW_LINE> <INDENT> anchor_grid_list = [] <NEW_LINE> for (feat_shape, base_sizes, aspect_ratios, anchor_stride, anchor_offset ) in zip(feature_map_shape_list, self._base_sizes, self._aspect_ratios, self._anchor_strides, self._anchor_offsets): <NEW_LI... | Generates a collection of bounding boxes to be used as anchors.
Currently we require the input image shape to be statically defined. That
is, im_height and im_width should be integers rather than tensors.
Args:
feature_map_shape_list: list of pairs of convnet layer resolutions in the
format [(height_0, width_0... | 625941d466673b3332b9228c |
def get_ind_under_point(self, xdata, ydata, line): <NEW_LINE> <INDENT> xy = np.asarray(line.get_data()) <NEW_LINE> x, y = xy[0], xy[1] <NEW_LINE> d = np.sqrt((x - xdata)**2 + (y - ydata)**2) <NEW_LINE> indseq = np.nonzero(np.equal(d, np.amin(d)))[0] <NEW_LINE> ind = indseq[0] <NEW_LINE> ind = None if (d[ind] >= self._e... | get the index of the vertex under point if within epsilon tolerance | 625941d45fc7496912cc3b78 |
def catalog_images(self): <NEW_LINE> <INDENT> catalog_url = f"https://{self._hub_uri}/v2/_catalog" <NEW_LINE> try: <NEW_LINE> <INDENT> import requests <NEW_LINE> r = requests.get(catalog_url, auth=self._hub_credentials) <NEW_LINE> catalog = r.json() <NEW_LINE> <DEDENT> except BaseException: <NEW_LINE> <INDENT> return N... | check if container image is there | 625941d4046cf37aa974cf41 |
def encrypt(self, key, plaintext): <NEW_LINE> <INDENT> output = [] <NEW_LINE> padded_key = padd_key(key, plaintext) <NEW_LINE> for i in range(len(plaintext)): <NEW_LINE> <INDENT> enc_ascii = (ord(plaintext[i]) + ord(padded_key[i])) % 256 <NEW_LINE> output.append(chr(enc_ascii)) <NEW_LINE> <DEDENT> return output | This function will return ciphertext of the plain ascii Text in char
Input : Sequence of ASCII bytes
output : Encrypted sequence of ascii bytes in char | 625941d4596a897236089cb9 |
def listSpeciesNodes(self,data=False): <NEW_LINE> <INDENT> spNodes = set( n for n,b in self.nodes(data='bipartite') if b==1 ) <NEW_LINE> if data==False: <NEW_LINE> <INDENT> return [ n for n in self.nodes(data=data) if n in spNodes ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [ (n,d) for n,d in self.nodes(data... | Lists nodes from the species set.
Parameters
----------
data : string or bool, default=False
If False only nodes ids are returned.
If True nodes ids are returned with their respective attribute dicts as (n, attrDict).
If a string is passed (with an attribute name) then its value is returned in a 2-tuple (n... | 625941d45166f23b2e1a5353 |
def shrink(self): <NEW_LINE> <INDENT> if self.is_full(): <NEW_LINE> <INDENT> if len(self._buffer) > 0: <NEW_LINE> <INDENT> self._buffer = self._buffer[1:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._episode = self._episode[1:] | Shrinks the buffer by one sample if necessary. | 625941d463b5f9789fde72e0 |
def p_vartypes(p): <NEW_LINE> <INDENT> p[0] = p[1] ,p[2], p[3],p[4] | vartypes : INT test ASSIGN test
| DOUBLE test ASSIGN test
| SHORT test ASSIGN test
| LONG test ASSIGN test
| CHAR test ASSIGN test
| FLOAT test ASSIGN test | 625941d4cb5e8a47e48b7ca3 |
def join_tokens(xs): <NEW_LINE> <INDENT> xs = group_by_type(xs) <NEW_LINE> res = "" <NEW_LINE> for i in range(len(xs)): <NEW_LINE> <INDENT> if type(xs[i][0]) is str: <NEW_LINE> <INDENT> res = "%s %s" % (res, " ".join(xs[i])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res = "%s %d" % (res, calc_value(xs[i])) <NEW_LIN... | Split list of strings and ints on sequences of same type,
calculate value of each seq and join results. | 625941d43346ee7daa2b2f67 |
def get_image(self, image_id): <NEW_LINE> <INDENT> url = '/v1/images/%s' % image_id <NEW_LINE> args = {'headers': {}, 'body': ''} <NEW_LINE> resp, body_iter = self.gl_source.images.api.raw_request('GET', url, **args) <NEW_LINE> return resp | Fetch image data from glance server directly via http request.
:rtype : a httplib Response object with image data as body
:param image_id: the uuid of an image | 625941d4167d2b6e31218d90 |
def __cycles_refcode_target(self, model): <NEW_LINE> <INDENT> assert len(model.mesh.materials) == 1 <NEW_LINE> nodes = model.mesh.materials[0].node_tree.nodes <NEW_LINE> tex_nodes = [n for n in nodes if n.type=='TEX_IMAGE'] <NEW_LINE> if len(tex_nodes) == 1: <NEW_LINE> <INDENT> return tex_nodes[0].image <NEW_LINE> <DED... | 'refcode_for_model' behavior if the current rendering engine is
cycles. | 625941d407d97122c4178a89 |
def test_create_new_superuser(self): <NEW_LINE> <INDENT> user = get_user_model().objects.create_superuser( 'test@syn.com', 'test123' ) <NEW_LINE> self.assertTrue(user.is_superuser) <NEW_LINE> self.assertTrue(user.is_staff) | Test creating a new superuser | 625941d41d351010ab855d16 |
@command_wrap(pass_chat_data=True, pass_args=True) <NEW_LINE> @check_admin() <NEW_LINE> @check_run() <NEW_LINE> @run_async <NEW_LINE> def unbanword(bot, update, args, chat_data): <NEW_LINE> <INDENT> if not len(args): <NEW_LINE> <INDENT> bot.send_message(chat_id=update.message.chat_id, text=BANWORD_ERROR) <NEW_LINE> ret... | cancel banword
:param chat_data:
:type chat_data: dict
:param args:
:param bot:
:type bot: Bot
:param update:
:type update: Update
:return: | 625941d445492302aab5e4c0 |
def read_attrs_old(process, repo_file_path): <NEW_LINE> <INDENT> process.stdin.write(repo_file_path + b'\0') <NEW_LINE> process.stdin.flush() <NEW_LINE> path, attr, info = b'', b'', b'' <NEW_LINE> lines_count = 0 <NEW_LINE> lines_expected = len(attrs) <NEW_LINE> while lines_count != lines_expected: <NEW_LINE> <INDENT> ... | Compatibility with versions 1.8.5 and below that do not recognize -z for output. | 625941d4d268445f265b5069 |
def filter_subset(self, s, t, articles): <NEW_LINE> <INDENT> d = {a.title:a for a in articles} <NEW_LINE> titles = [a.title for a in articles] <NEW_LINE> data = self.query_wikidata_sitelinks(s, titles) <NEW_LINE> title_id_dict = self.parse_wikidata_sitelinks_data(s, t, data) <NEW_LINE> filtered_articles = [] <NEW_LINE... | Remove articles in s that already exist in t
using Wikidata sitelinks from the Wikidata API | 625941d4fb3f5b602dac3890 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, TextReplace): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941d40383005118ecf7dd |
def create_wrap(source, target, intermediate=None): <NEW_LINE> <INDENT> logger.debug("Creating wrap deformer for {} using {}".format(target, source)) <NEW_LINE> target_type = cmds.objectType(target) <NEW_LINE> wrap_node = cmds.deformer(target, type="wrap", name="flex_warp")[0] <NEW_LINE> cmds.setAttr("{}.exclusiveBind"... | Creates a wrap deformer on the target by using source as driver
:param source: the maya source node
:type source: str
:param target: the maya target node
:type target: str
:param intermediate: the intermediate shape to use on the warp node
:type intermediate: str
:return: wrap node
:rtype: str | 625941d4283ffb24f3c55afb |
def __init__(self, session): <NEW_LINE> <INDENT> self._session = session | Initialize a URLRequest.
Parameters
----------
session : Session
The session object for which the url is being requested. | 625941d4ff9c53063f47c3ee |
def features_from_game_info( game_info, use_feature_units=False, action_space=None, hide_specific_actions=True): <NEW_LINE> <INDENT> if game_info.options.HasField("feature_layer"): <NEW_LINE> <INDENT> fl_opts = game_info.options.feature_layer <NEW_LINE> feature_dimensions = Dimensions( screen=(fl_opts.resolution.x, fl_... | Construct a Features object using data extracted from game info.
Args:
game_info: A `sc_pb.ResponseGameInfo` from the game.
use_feature_units: Whether to include the feature unit observation.
action_space: If you pass both feature and rgb sizes, then you must also
specify which you want to use for your act... | 625941d4498bea3a759b9caa |
def findRegistry(self, rootKey, key=None, valueName=None, limit=1): <NEW_LINE> <INDENT> if key == None and valueName == None: <NEW_LINE> <INDENT> raise ValueError("either key or valueName must be provided") <NEW_LINE> <DEDENT> return self.existingConnection().evalPython( 'findRegistry(%s, key=%s, valueName=%s, limit=%s... | Search for key and/or valueName from the registry.
Returns a list of matching (fullKeyPath, valueName) pairs
found under the rootKey. The list has at most limit items, the
default is 1.
Parameters:
rootKey (string):
root key path for the search. Example:
"HKEY_LOCAL_MACHINE".
key (string, op... | 625941d47c178a314d6ef65c |
def test_selected_values(self): <NEW_LINE> <INDENT> self.assertTrue(re.search(SELECTED_OPTION_PATTERN % 'WA', str(self.form['state']))) <NEW_LINE> self.assertTrue(re.search(SELECTED_OPTION_PATTERN % 'QLD', str(self.form['state_required']))) <NEW_LINE> self.assertTrue(re.search(INPUT_VALUE_PATTERN % '1234', str(self.for... | Ensure selected states match the initial values provided. | 625941d4adb09d7d5db6c98a |
def update_tour_db(bot): <NEW_LINE> <INDENT> d = datetime.today() <NEW_LINE> if d.timetuple()[3] > 5: <NEW_LINE> <INDENT> job_queue.put( update_tour_db, 60 * 60 * (25 - d.timetuple()[3]), repeat=False ) <NEW_LINE> logger.info("рано обновлять базу турниров, ставим в ожидание") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDEN... | Регулярное обновление списка турниров
:param bot: фиктивный параметр для того, чтобы можно было использовать
очередь пакета telegram
:return: | 625941d45f7d997b87174c94 |
def zoemzin2(*args) -> str: <NEW_LINE> <INDENT> return zoemzin1(args) | Pakt een willekeurig woord uit elke woordenlijst, en voegt deze woorden
samen tot één enkele string (in de volgorde van de gegeven woordenlijsten).
:param args: Een lijst met buzz lijsten als tuple.
:return: een zoemzin als string. | 625941d4d18da76e235326d2 |
def get_image_path(self): <NEW_LINE> <INDENT> return "Images/Guard.png" | Returns image path | 625941d48e71fb1e9831d9a4 |
def __init__(self, taxon_rank=None, scientific_name=None, type_status=None, date_identified=None, default_classification=None, system_classification=None, vernacular_names=None, identification_qualifiers=None, identifiers=None, taxonomic_enrichments=None, preferred=None, verification_status=None, rock_type=None, associ... | SpecimenIdentification - a model defined in Swagger | 625941d4d18da76e235326d3 |
def person_opted_out(self, email=None, id=None, nickname=None): <NEW_LINE> <INDENT> person = self.get_person(email, id, nickname) <NEW_LINE> if not person: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return person.opt_out | Returns true if a given person has opted out of tahrir. | 625941d426068e7796caeedd |
def change_input(self, node, i, new_r, reason=None): <NEW_LINE> <INDENT> if node == 'output': <NEW_LINE> <INDENT> r = self.outputs[i] <NEW_LINE> if not r.type == new_r.type: <NEW_LINE> <INDENT> raise TypeError("The type of the replacement must be the" " same as the type of the original Variable.", r, new_r) <NEW_LINE> ... | Changes node.inputs[i] to new_r.
WRITEME
new_r.type == old_r.type must be True, where old_r is the
current value of node.inputs[i] which we want to replace.
For each feature that has a 'on_change_input' method, calls:
feature.on_change_input(function_graph, node, i, old_r, new_r, reason) | 625941d42eb69b55b151caac |
def act_single_(self, state, **kwargs): <NEW_LINE> <INDENT> exploration_off = kwargs['exploration_off'] if 'exploration_off' in kwargs else False <NEW_LINE> if state is None: <NEW_LINE> <INDENT> idx_action = randint(0, len(self.__ACTIONS)) <NEW_LINE> <DEDENT> elif not exploration_off and rand() < self.__EPSI... | Epsilon greedy action selection.
Choose greedy action with 1-epsilon probability and random action with
epsilon probability. Ties are broken randomly for greedy actions. | 625941d471ff763f4b549889 |
def main(argv): <NEW_LINE> <INDENT> token = os.environ.get('SLACK_TOKEN') <NEW_LINE> if not token: <NEW_LINE> <INDENT> print("Please configure a SLACK_TOKEN.", file=sys.stderr) <NEW_LINE> return 1 <NEW_LINE> <DEDENT> bot = Bot(token) <NEW_LINE> loop = asyncio.get_event_loop() <NEW_LINE> loop.set_debug(debug) <NEW_LINE>... | Le bot. | 625941d4d8ef3951e3243739 |
def push_config(self): <NEW_LINE> <INDENT> self.role_info = registry.get_role_metadata(self.context, self.role_id) <NEW_LINE> if not self.role_info or not self.role_info.get('config_set_id'): <NEW_LINE> <INDENT> LOG.error("<<<config_clushshell:push_config,get_role_metadata failed.>>>") <NEW_LINE> return <NEW_LINE> <DED... | Push config to remote host.
:param req: http req
:param role_id: host role id
:return: | 625941d4d58c6744b4257e5a |
def max_word_value(lst=None): <NEW_LINE> <INDENT> lst = lst or load_words() <NEW_LINE> return max(lst, key=calc_word_value) | Calculate the word with the max value, can receive a list
of words as arg, if none provided uses default DICTIONARY | 625941d4b57a9660fec33a82 |
def main(global_config, **settings): <NEW_LINE> <INDENT> engine = engine_from_config(settings, 'sqlalchemy.') <NEW_LINE> initialize_sql(engine) <NEW_LINE> unencrypt = UnencryptedCookieSessionFactoryConfig('itsaseekreet') <NEW_LINE> config = Configurator(settings=settings, session_factory=unencrypt) <NEW_LINE> config = ... | This function returns a Pyramid WSGI application.
| 625941d4046cf37aa974cf42 |
def coordselector_chosen(self): <NEW_LINE> <INDENT> if self.coordselector.currentText() == "GNSS": <NEW_LINE> <INDENT> self.GNSS_GUI_visible(True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.GNSS_GUI_visible(False) | The handler called when a target is chosen from the coordselector combobox.
Turns on the GNSS-related parts of GUI if target is 'GNSS'. | 625941d485dfad0860c3b057 |
def update_window_size_missed_ack(self): <NEW_LINE> <INDENT> if self.fast_recovery: <NEW_LINE> <INDENT> self.exit_fast_recovery() <NEW_LINE> <DEDENT> time = globals_.event_manager.get_time() <NEW_LINE> if time - self.time_of_last_window_reduction > max(0.5, self.rtte.get_estimate()): <NEW_LINE> <INDENT> self.time_of_la... | This is called when waiting to receive an ack for a sent packet times out
Set ssthresh to half of the current window size,
unless a timeout happened within the past 0.5 seconds or rtte,
then set the window size to 1 | 625941d4091ae35668667157 |
def show_message(self, message): <NEW_LINE> <INDENT> self.app.widget_focused = None <NEW_LINE> if self.gridlayout.children or not isinstance(self.gridlayout.children[0], Label): <NEW_LINE> <INDENT> self.navbar = GridLayout(rows=1) <NEW_LINE> <DEDENT> self.gridlayout.clear_widgets() <NEW_LINE> self.gridlayout... | To show a message in StatusBar
| 625941d4cdde0d52a9e53230 |
@click.group() <NEW_LINE> def metadata(): <NEW_LINE> <INDENT> pass | Metadata management | 625941d4956e5f7376d71068 |
def rand_pair(s,ny,nx): <NEW_LINE> <INDENT> return np.random.randint(s,ny), np.random.randint(s,nx) | Rand pair of numbers for a rectangle | 625941d432920d7e50b283cd |
def doAll(self): <NEW_LINE> <INDENT> self.makeFrames() <NEW_LINE> self.makeTop() <NEW_LINE> self.makeInfo() <NEW_LINE> self.makeTable() <NEW_LINE> self.makeResumen() <NEW_LINE> self.makeEnd() <NEW_LINE> temp = PageTemplate(frames=[self.frame1, self.frame2, self.last_frame], onPage=self.drawPage) <NEW_LINE> self.build(t... | Método que renderiza una cotización | 625941d48a43f66fc4b5425f |
def _check_password(self, password): <NEW_LINE> <INDENT> if self.password_regex.search(password) is not None: <NEW_LINE> <INDENT> print("Correct password") <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Password format error! Your password is {}") <NEW_LINE> return False | Check password is valid or not | 625941d4851cf427c661a709 |
def ls(path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> p = subprocess.Popen('hadoop fs -ls %s' % path, env={}, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) <NEW_LINE> out, err = p.communicate() <NEW_LINE> if p.returncode: <NEW_LINE> <INDENT> raise IOError <NEW_LINE> <DEDENT> <DEDENT> except IOError: ... | List files on HDFS.
Args:
path: A string (potentially with wildcards).
Returns:
A list of strings representing HDFS paths.
Raises:
IOError: An error occurred listing the directory (e.g., not available). | 625941d48e05c05ec3eea572 |
def test_plane4to3(self): <NEW_LINE> <INDENT> for plane4, plane3 in zip(self.plane4, self.plane3): <NEW_LINE> <INDENT> assert np.all(plane4to3(plane4) == plane3) <NEW_LINE> <DEDENT> assert np.all(plane4to3(self.plane4) == self.plane3) <NEW_LINE> with pytest.raises(ValueError): <NEW_LINE> <INDENT> plane4to3([ 1, 2, 3]) | test plane4to3 by checking that plane4 -> plane3 | 625941d41f037a2d8b9463f9 |
def __ne__(self, other): <NEW_LINE> <INDENT> return not self.__eq__(other) | Esta comparación se define como la negación del resultado obtenido por C{__eq__}.
Ver documentación del método C{__eq__} para más información.
@type other: C{TigerType}
@param other: Otro tipo de Tiger con el que efectuar la comparación.
@rtype: C{bool}
@return: Retorna C{True} si los ambos no son iguales. | 625941d4bf627c535bc133cb |
@pytest.mark.skipif(not have_mdbtools, reason='Reading the Arbin file requires MDBTools') <NEW_LINE> def test_convert_cmdline(testdata_dir, tmpdir): <NEW_LINE> <INDENT> res_file = os.path.join(testdata_dir, 'arbin1.res') <NEW_LINE> sqlite_file = os.path.join(str(tmpdir), 'arbin1.s3db') <NEW_LINE> subprocess.check_call(... | Checks that the conversion fails with an appropriate error message. | 625941d47d847024c06be4ba |
def get_http_error_response_json(error_objects): <NEW_LINE> <INDENT> http_error_resp = {} <NEW_LINE> http_error_resp["errors"] = error_objects <NEW_LINE> return json.dumps(http_error_resp) | Returns a JSON object indicating an Http Error | 625941d4a79ad161976cc342 |
def main(): <NEW_LINE> <INDENT> usersphone = input("Please input your Number.") <NEW_LINE> Message = PhoneNumber() | Main function! | 625941d43346ee7daa2b2f68 |
def newInfo(self): <NEW_LINE> <INDENT> if sys.platform.startswith('darwin') and self.lilypond.path().endswith('.app'): <NEW_LINE> <INDENT> info = lilypondinfo.LilyPondInfo( self.lilypond.path() + '/Contents/Resources/bin/lilypond') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> info = lilypondinfo.LilyPondInfo(self.lily... | Returns a new LilyPondInfo instance for our settings. | 625941d41f037a2d8b9463fa |
def to_netcdf(valid): <NEW_LINE> <INDENT> fn = ("/mesonet/ARCHIVE/data/%s/model/NARR/apcp_%s.grib") % ( valid.strftime("%Y/%m/%d"), valid.strftime("%Y%m%d%H%M"), ) <NEW_LINE> if not os.path.isfile(fn): <NEW_LINE> <INDENT> print("merge_narr: missing file %s" % (fn,)) <NEW_LINE> return False <NEW_LINE> <DEDENT> gribs = p... | Persist this 1 hour precip information to the netcdf storage
Recall that this timestep has data for the previous hour | 625941d491f36d47f21ac6f0 |
def ExtendedHata(its_elev, freq_mhz, height_tx, height_rx, region_code): <NEW_LINE> <INDENT> return ehata_its.ExtendedHata(its_elev, freq_mhz, height_tx, height_rx, region_code) | Computes the E-Hata propagation path loss.
Inputs:
its_elev : Terrain profile in ITS format from transmitter to receiver:
- pfl[0] = number of elevation points - 1
- pfl[1] = step size, in meters
- pfl[2..N] = elevation above mean sea level, in meters
freq_mhz: frequency (MH... | 625941d499cbb53fe6792de2 |
@celery.task() <NEW_LINE> def queue_analysis(collection_id_list, query_id, motif_list, motif_frequency, motif_frame_size, user): <NEW_LINE> <INDENT> for collection_id in collection_id_list: <NEW_LINE> <INDENT> sequences = Sequence.find(collection_id=ObjectId(collection_id)) <NEW_LINE> for sequence in sequences: <NEW_LI... | :param collection_id_list:
:param query_id:
:param motif_list:
:param motif_frequency:
:param motif_frame_size:
:param user:
:return: | 625941d494891a1f4081bca6 |
def put_name(self, name, ttl): <NEW_LINE> <INDENT> self.storage[name] = self.now + ttl | cache information for whole name | 625941d4167d2b6e31218d91 |
def tick(self, state: State, new_rewards: Rewards) -> (float, float): <NEW_LINE> <INDENT> errsignal, util = self._tick(state, new_rewards) <NEW_LINE> if errsignal < 0: <NEW_LINE> <INDENT> errsignal *= gv.factor_negative_util <NEW_LINE> <DEDENT> return errsignal, util | input the states and rewards for a frame and get the utility back. Returns a single reward value based on teh new rewards. Later should return utility.
:param state:
:param new_rewards: the rewards for this state
:returns reward signal and absolute utility (rating of this state) | 625941d429b78933be1e58a5 |
def _on_key_left(self) -> None: <NEW_LINE> <INDENT> self._right_ix -= 1 <NEW_LINE> self._right_ix = max(self._right_ix, self._bar_count) <NEW_LINE> self._update_x_range() <NEW_LINE> self._cursor.move_left() <NEW_LINE> self._cursor.update_info() | Move chart to left. | 625941d499cbb53fe6792de3 |
def test_start_movement(self): <NEW_LINE> <INDENT> body = StartDM() <NEW_LINE> response = self.client.open( '/start_movement/', method='POST', data=json.dumps(body), content_type='application/json') <NEW_LINE> self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) | Test case for start_movement
Communication between DMEs. Signals the other DME to prepare for movement | 625941d4eab8aa0e5d26dd54 |
def getGuessedWord(secretWord, lettersGuessed): <NEW_LINE> <INDENT> dic = {} <NEW_LINE> ans = '' <NEW_LINE> for x in range(len(secretWord)): <NEW_LINE> <INDENT> dic[x] = '_' <NEW_LINE> <DEDENT> for letter in lettersGuessed: <NEW_LINE> <INDENT> if letter in secretWord: <NEW_LINE> <INDENT> for x in range(0,len(secretWord... | secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far. | 625941d45e10d32532c5f123 |
def read_advisers(xml_dom_for_adviser): <NEW_LINE> <INDENT> adviserInfo_labels = xml_dom_for_adviser.getElementsByTagName('adviserInfo') <NEW_LINE> for adviserInfo_label in adviserInfo_labels: <NEW_LINE> <INDENT> label_id = adviserInfo_label.getAttribute('建议者ID') <NEW_LINE> an_advisers_dict[label_id] = {} <NEW_LINE> la... | 读取建议者
:param xml_dom_for_adviser:
:return: | 625941d4f9cc0f698b1407f6 |
def ask_bts_tch_ts(self): <NEW_LINE> <INDENT> return self.scpi.ask_int("CONF:CHAN:BTS:TCH:SLOT?") | 2.2.2 Configured TCH timeslot | 625941d4236d856c2ad449d7 |
def __init__(self): <NEW_LINE> <INDENT> super(Autoencoder, self).__init__() <NEW_LINE> self.encoder = Encoder() <NEW_LINE> self.decoder = Decoder() | define encoder and decoder | 625941d4d6c5a10208144248 |
def rptWrite(self, _addr, _data): <NEW_LINE> <INDENT> print("ZwireDummy rptWrite " + str(_addr) + " " + str(_data)) <NEW_LINE> return 0 | Pretend to write a list of values, _data, to _addr. | 625941d41b99ca400220acae |
def __getstate__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> state = super(NotifierMixin, self).__getstate__() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> state = self.__dict__.copy() <NEW_LINE> <DEDENT> state['_listeners'] = None <NEW_LINE> return state | Exclude listeners when saving the listener's state, since they may be
ephemeral. | 625941d4e76e3b2f99f3aa05 |
def provisioners_get_with_http_info(self, **kwargs): <NEW_LINE> <INDENT> all_params = [] <NEW_LINE> all_params.append('callback') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_LINE> params = locals() <NEW_LIN... | List all Provisioners
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.provisioners_get_with_http_info(callback=... | 625941d424f1403a92600d61 |
def depthFirstSearch(problem): <NEW_LINE> <INDENT> start = problem.getStartState() <NEW_LINE> stack = util.Stack() <NEW_LINE> stack.push((start, [])) <NEW_LINE> visited = [] <NEW_LINE> while stack.isEmpty()==False: <NEW_LINE> <INDENT> node, allactions = stack.pop() <NEW_LINE> if node not in visited: <NEW_LINE> <INDENT... | Search the deepest nodes in the search tree first.
Your search algorithm needs to return a list of actions that reaches the
goal. Make sure to implement a graph search algorithm.
To get started, you might want to try some of these simple commands to
understand the search problem that is being passed in:
print("Start... | 625941d49f2886367277aa89 |
def removeNamespace(obj): <NEW_LINE> <INDENT> obj.name = safelyName(obj, stripNamespaceFromName(obj.name)) | Removes the namespace from an object if present.
Args:
obj(bpy.types.Object): The object to remove the namespace from.
Returns: | 625941d43c8af77a43ae399d |
@app.route('/api/projects/1/task_ids/', methods=['GET']) <NEW_LINE> @exception_treatment <NEW_LINE> def api_all_task_ids(): <NEW_LINE> <INDENT> project = project_get_or_create() <NEW_LINE> ids = list(sorted(project.source_storage.ids())) <NEW_LINE> project.analytics.send(getframeinfo(currentframe()).function) <NEW_LINE... | Get all tasks ids
| 625941d430dc7b7665901b61 |
def testBadLen( self ): <NEW_LINE> <INDENT> testlst = self.jk._results <NEW_LINE> explst = ResultList() <NEW_LINE> res = JKindResult( '', '' ) <NEW_LINE> res['name'] = 'var1' <NEW_LINE> res['answer'] = 'valid' <NEW_LINE> res['K'] = '0' <NEW_LINE> explst.append( res ) <NEW_LINE> res = JKindResult( '', '' ) <NEW_LINE> re... | Test that our Results List class can deal with mis-matching count of
results. | 625941d4f7d966606f6aa202 |
def distances(self, lng, lat, lngfield, latfield): <NEW_LINE> <INDENT> arrays = (self.comparator(field, 'double') for field in (lngfield, latfield)) <NEW_LINE> return DistanceComparator(lng, lat, *arrays) | Return distance comparator computed from cached lat/lng fields. | 625941d450812a4eaa59c51d |
def to_sql(self): <NEW_LINE> <INDENT> s_date = str(self.date.year()) + '-' + to_str(self.date.month()) + '-' + to_str(self.date.day()) <NEW_LINE> if self.period: <NEW_LINE> <INDENT> e_date = str(self.period.year()) + '-' + to_str(self.period.month()) + '-' + to_str(self.period.day()) <NEW_LINE> return 'BETWEEN ? AND ?'... | returns string date in yyyy-mm-dd format.
if Days.period is set, returns a string 'BETWEEN YYYY-MM-DD AND YYYY-MM-DD' | 625941d463f4b57ef0001312 |
def connect(controlAddr="127.0.0.1", controlPort=9051, passphrase=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> s.connect((controlAddr, controlPort)) <NEW_LINE> conn = Connection(s) <NEW_LINE> authType, authValue = conn.get_auth_type(), "" <NEW_LINE... | Convenience function for quickly getting a TorCtl connection. This is very
handy for debugging or CLI setup, handling setup and prompting for a password
if necessary (if either none is provided as input or it fails). If any issues
arise this prints a description of the problem and returns None.
Arguments:
controlAdd... | 625941d482261d6c526ab69d |
def transposta(self): <NEW_LINE> <INDENT> resp = [[0 for i in range(self.lin)] for j in range(self.col)] <NEW_LINE> for i in range(self.lin): <NEW_LINE> <INDENT> for j in range(self.col): <NEW_LINE> <INDENT> resp[j][i] = self.mat[i][j] <NEW_LINE> <DEDENT> <DEDENT> return Matriz(resp) | Retorna a transposta da matriz | 625941d4009cb60464c635ad |
def groebner(self, mat=None, project=None): <NEW_LINE> <INDENT> project = self._process_input(locals()) <NEW_LINE> self.call('groebner -q -parbitrary', project) <NEW_LINE> return self.read_matrix(project+'.gro') | Runs the 4ti2 program ``groebner`` on the parameters. This
computes a Toric Groebner basis of a matrix. See
``http://www.4ti2.de/`` for details.
EXAMPLES::
sage: from sage.interfaces.four_ti_2 import four_ti_2
sage: A = [6,10,15]
sage: four_ti_2.groebner(A) # optional - 4ti2
[-5 0 2]
[-5 3 0] | 625941d47d43ff24873a2e9d |
def stop(self): <NEW_LINE> <INDENT> self._should_stop = True <NEW_LINE> self.join(1) | Stop the mock device running. Blocks until the thread shuts down
gracefully with a one second timeout. | 625941d4adb09d7d5db6c98b |
def bts_type(self): <NEW_LINE> <INDENT> return self.conf.get('type') | Get the type of BTS | 625941d43539df3088e2e547 |
def create_account(self, username, email, password): <NEW_LINE> <INDENT> url = reverse('user_api_registration') <NEW_LINE> request_data = { 'username': username, 'email': email, 'password': password, 'name': 'username', 'terms_of_service': 'true', 'honor_code': 'true', } <NEW_LINE> self.assert_request_status_code(200, ... | Create the account and check that it worked. | 625941d4cc0a2c11143dd08d |
def getDelta(self, res, index = None): <NEW_LINE> <INDENT> if not index: <NEW_LINE> <INDENT> for resIndex, currRes in enumerate(res): <NEW_LINE> <INDENT> currIter = self.iterate[resIndex] <NEW_LINE> currIter.delta = currRes['value'] - currRes['alter'] <NEW_LINE> if abs(currIter.delta) < currIter.tol: <NEW_LINE> <INDENT... | Input: residuals and optional index
Output: array with iteration helpers | 625941d43346ee7daa2b2f69 |
def __init__(self, columns=0, rows=0): <NEW_LINE> <INDENT> self.columns = columns <NEW_LINE> self.rows = rows <NEW_LINE> self.data = [[0 for col in range(columns)] for row in range(rows)] | Create an image. | 625941d410dbd63aa1bd2d9f |
def endload(self): <NEW_LINE> <INDENT> self._enqueuenoreturn('endload') <NEW_LINE> self._endbatch() <NEW_LINE> self._join() <NEW_LINE> return None | Invoke endload on the decoupled Dimension in the separate process and
return when all waiting method calls have been executed | 625941d4293b9510aa2c3491 |
def get_flow(**kwargs): <NEW_LINE> <INDENT> task_id = kwargs.get('task_id') <NEW_LINE> task_type = kwargs.get('task_type') <NEW_LINE> task_repo = kwargs.get('task_repo') <NEW_LINE> image_repo = kwargs.get('image_repo') <NEW_LINE> image_factory = kwargs.get('image_factory') <NEW_LINE> uri = kwargs.get('uri') <NEW_LINE> ... | Return task flow
:param task_id: Task ID
:param task_type: Type of the task
:param task_repo: Task repo
:param image_repo: Image repository used
:param image_factory: Glance Image Factory
:param uri: uri for the image file | 625941d4e5267d203edcde98 |
def factorial(value): <NEW_LINE> <INDENT> if (value == 0) or (value == 1): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return value * factorial(value - 1) | Compute factorial of given value.
:param value: A non-negative integer.
:return: Factorial of given value.
>>> factorial(0)
1
>>> factorial(1)
1
>>> factorial(2)
2
>>> factorial(3)
6
>>> factorial(4)
24 | 625941d4167d2b6e31218d92 |
def save(self, target): <NEW_LINE> <INDENT> if self.compareVolumes: <NEW_LINE> <INDENT> frameList = self.__createCompareFrames() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> frameList = self.__createFrames() <NEW_LINE> <DEDENT> frames2Gif(frameList, target, self.gifSpeed) <NEW_LINE> for frame in frameList: frame.close | Generate animated gif with convert from imagemagick
Args:
imageList: list of png to convert
target: output filename
gifSpeed: delay between images (tens of ms) | 625941d4097d151d1a223055 |
def maximum(x, y, name=None): <NEW_LINE> <INDENT> op_type = 'elementwise_max' <NEW_LINE> axis = -1 <NEW_LINE> act = None <NEW_LINE> if in_dygraph_mode(): <NEW_LINE> <INDENT> return _elementwise_op_in_dygraph( x, y, axis=axis, act=act, op_name=op_type) <NEW_LINE> <DEDENT> return _elementwise_op(LayerHelper(op_type, **lo... | Compare two tensors and returns a new tensor containing the element-wise maxima. The equation is:
.. math::
out = max(x, y)
**Note**:
``paddle.maximum`` supports broadcasting. If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting` .
Args:
x (Tensor): the input tensor, it's d... | 625941d43c8af77a43ae399e |
def attach_field(self, name, values): <NEW_LINE> <INDENT> assert self.mode in ["a"], ( "Attach field option only " "available in mode 'a'" ) <NEW_LINE> with exodus(self._filename, self.mode) as e: <NEW_LINE> <INDENT> if values.size == self.nelem: <NEW_LINE> <INDENT> e.put_element_variable_values( blockId=1, name=name, ... | Write values with name to exodus file
:param name: name of the variable to be written
:param values: numpy array of values to be written
:return: | 625941d4f7d966606f6aa203 |
def __init__(self, hass, location_id, sensor_entities): <NEW_LINE> <INDENT> self.hass = hass <NEW_LINE> self.location_id = location_id <NEW_LINE> self.sensor_entities = sensor_entities <NEW_LINE> self.last_update = None <NEW_LINE> self.location_city = None <NEW_LINE> self.data = {} | Initialize the probe. | 625941d4d10714528d5ffee2 |
@cliutils.arg('address', metavar='<address>', help=_('IP of Floating IP.')) <NEW_LINE> def do_floating_ip_delete(cs, args): <NEW_LINE> <INDENT> floating_ips = cs.floating_ips.list() <NEW_LINE> for floating_ip in floating_ips: <NEW_LINE> <INDENT> if floating_ip.ip == args.address: <NEW_LINE> <INDENT> return cs.floating_... | De-allocate a floating IP. | 625941d4d268445f265b506b |
def saveComponents(self, app): <NEW_LINE> <INDENT> for c in self.constructs: saveDefinitionComponents(app, c.componentClass) | save components to file | 625941d45166f23b2e1a5356 |
def is_purchaseable(self): <NEW_LINE> <INDENT> if self.active: <NEW_LINE> <INDENT> if self.start_options in ["signup_date", "first_booking_date"]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if self.expired(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.advance_purchase_allowed: <NEW_LINE> <IND... | A subscription is purchaseable if:
- it's active
- it starts from sign up or booking date
- it starts from a start date AND
- advance purchase is allowed OR
- has a current period which hasn't exipred yet OR
- has a next period which starts within the next 3 days | 625941d4283ffb24f3c55afc |
def test_example_app_role_admin(example_app): <NEW_LINE> <INDENT> cmd = 'curl http://0.0.0.0:5000/' <NEW_LINE> output = subprocess.check_output(cmd, shell=True) <NEW_LINE> assert b'Welcome to Invenio-Galter-Test' in output | Test example app. | 625941d4507cdc57c6306edb |
def plot_rsi(ax, df, period=14, style=style): <NEW_LINE> <INDENT> rsi_data = relative_strength_index(df.close, n=period) <NEW_LINE> legend_text = 'RSI %s' % str(period) <NEW_LINE> ax = _plot_rsi(ax, df.index, rsi_data, line_color=style.rsi_line_color, line_width=style.rsi_linewidth, signal_line_color=style.rsi_signal_l... | plot rsi
:param ax: axis
:param df: price dataframe
:param style: style object
:return: axis | 625941d473bcbd0ca4b2c273 |
def repercent_broken_unicode(path): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> path.decode() <NEW_LINE> <DEDENT> except UnicodeDecodeError as e: <NEW_LINE> <INDENT> repercent = quote(path[e.start:e.end], safe=b"/#%[]=:;$&()+,!?*@'~") <NEW_LINE> path = path[:e.start] + repercent.encode(... | As per section 3.2 of RFC 3987, step three of converting a URI into an IRI,
repercent-encode any octet produced that is not part of a strictly legal
UTF-8 octet sequence. | 625941d4462c4b4f79d1d8cd |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.