code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_word_cloud_constructor(self): <NEW_LINE> <INDENT> fragment = self.runtime.render(self.item_descriptor, STUDENT_VIEW) <NEW_LINE> expected_context = { 'ajax_url': self.item_descriptor.ajax_url, 'display_name': self.item_descriptor.display_name, 'instructions': self.item_descriptor.instructions, 'element_class': ... | Make sure that all parameters extracted correctly from xml. | 625941d46e29344779a627fb |
def __init__(self, start=1, base=2): <NEW_LINE> <INDENT> super().__init__(start) <NEW_LINE> self._base = base | Create a new arithmetic progression.
start the first term of the progression
base the fixed constant of the progression (default 0) | 625941d44527f215b584c63f |
def top_rated(request): <NEW_LINE> <INDENT> return render_to_response('cab/top_rated.html', { 'object_list': Rating.objects.top_rated(20) }, context_instance=RequestContext(request)) | Shows a list of the top-rated Snippets.
Context::
object_list
The list of Snippets
Template::
cab/top_rated.html | 625941d4462c4b4f79d1d8ba |
def enqueue(self, item): <NEW_LINE> <INDENT> self.list.append(item) | Insert the given item at the back of this queue.
Running time: O(1), LL has a reference to the tail
and the item is appended after that | 625941d44d74a7450ccd43ae |
@app.post('/download') <NEW_LINE> def do_download(): <NEW_LINE> <INDENT> global dl_process <NEW_LINE> try: <NEW_LINE> <INDENT> dest_path = request.forms.get('dest_path') <NEW_LINE> url = request.forms.get('url') <NEW_LINE> subs = request.forms.get('subs') <NEW_LINE> if not os.path.isdir(dest_path): <NEW_LINE> <INDENT> ... | Start the video download | 625941d45fc7496912cc3b68 |
def k_or_more_friends(network, k): <NEW_LINE> <INDENT> x = 0 <NEW_LINE> a = [] <NEW_LINE> for i in range(len(network)): <NEW_LINE> <INDENT> a = network[i][1] <NEW_LINE> if len(a) >= k: <NEW_LINE> <INDENT> x += 1 <NEW_LINE> <DEDENT> <DEDENT> return x | (2Dlist,int)->int
Given a 2D-list for friendship network and non-negative integer k,
returns the number of users who have at least k friends in the network
Precondition: k is non-negative | 625941d40c0af96317bb83d3 |
def get_form(self, request, formname): <NEW_LINE> <INDENT> if formname not in self.forms: <NEW_LINE> <INDENT> raise Http404(formname) <NEW_LINE> <DEDENT> items = [] <NEW_LINE> clsname = self.forms[formname].__name__ <NEW_LINE> hasfiles = False <NEW_LINE> for fldname in self.forms[formname].base_fields: <NEW_LINE> <INDE... | Convert the form given in "formname" to an ExtJS FormPanel. | 625941d4ec188e330fd5a987 |
def merge_all(src: dict, delete_ori: bool = False): <NEW_LINE> <INDENT> for title, files in src.items(): <NEW_LINE> <INDENT> with open('merge.txt', 'w', encoding='utf-8') as f: <NEW_LINE> <INDENT> f.write("file '" + "'\nfile '".join(files) + "'") <NEW_LINE> <DEDENT> system('ffmpeg -f concat -i merge.txt -c copy %s' % t... | :param src: {title: [flv_file_1, flv_file_2, ...], ...}
:param delete_ori: delete the old file (after merging them) or not
:return: None | 625941d42eb69b55b151ca9b |
def test_open_with_default_env(gdalenv): <NEW_LINE> <INDENT> with rasterio.open('tests/data/RGB.byte.tif') as dataset: <NEW_LINE> <INDENT> assert dataset.count == 3 | Read from a dataset with a default env. | 625941d4099cdd3c635f0e45 |
def close_widget(self): <NEW_LINE> <INDENT> QApplication.quit() <NEW_LINE> logging.info("Closing application") <NEW_LINE> sys.exit() | Close application | 625941d4442bda511e8be600 |
def output_message(self, level, msg, file_name, line_num, func_name, use_gmtime = None, show_timezone = None): <NEW_LINE> <INDENT> if use_gmtime is None: <NEW_LINE> <INDENT> use_gmtime = self.is_use_gmtime() <NEW_LINE> <DEDENT> if show_timezone is None: <NEW_LINE> <INDENT> show_timezone = self.is_show_timezone() <NEW_L... | Implements the abstract method defined in parent class. | 625941d431939e2706e4d053 |
def cadence(struct, filename, logfile, verbose): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> int_time = get(filename, struct, 'INT_TIME', logfile, verbose) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> txt = ('ERROR -- KEPKEY.CADENCE: Cannot read keyword INT_TIME in file ' + filename + '[1]') <NEW_LINE> kepmsg.err(l... | calculate timestamp cadence from keywords | 625941d43617ad0b5ed680e1 |
def cancel_download_cb(self, widget): <NEW_LINE> <INDENT> self.base.force_cancel = True | Annule un téléchargement en cours. | 625941d48c3a8732951585a6 |
def repeat(inp, times): <NEW_LINE> <INDENT> with tf.name_scope("repeat"): <NEW_LINE> <INDENT> inp = inp[:, tf.newaxis, :] <NEW_LINE> inp = tf.tile(inp, [1, times, 1]) <NEW_LINE> return tf.reshape(inp, [-1, tf.shape(inp)[2]]) | np.repeat equivalent.
Currently only works for 2D inputs and repeats along axis 0!!
TODO make less limited lol. | 625941d43eb6a72ae02ec6cb |
def __init__(self, data): <NEW_LINE> <INDENT> super(Subscription, self).__init__(data) <NEW_LINE> self.human_name = data.get("human_name", None) <NEW_LINE> self.list_name = data.get("list_name", None) <NEW_LINE> self.subscribed = data.get("subscribed", None) | Parameterized constructor for the Subscription object.
:param client: The client which is defining the object.
:param data: The JSON data to define the object with. | 625941d410dbd63aa1bd2d8d |
def _evalcmd(self, arg1, s0, y, d, C, NT, Tk=None): <NEW_LINE> <INDENT> assert arg1 is None <NEW_LINE> prefix = self._new_prefix() <NEW_LINE> assert isinstance(y, list) and len(y) == NT <NEW_LINE> assert isinstance(d, list) and len(d) == NT <NEW_LINE> varl = filter_strings([s0] + y) <NEW_LINE> y = list2dict(y, 1, NT) <... | Evalutate CMD[arg1](*args). | 625941d4293b9510aa2c347f |
def smoothness_penalty(self, coordP1, coordP2, d): <NEW_LINE> <INDENT> if self.color: <NEW_LINE> <INDENT> return self.smoothness_penalty_color(coordP1, coordP2, d) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.smoothness_penalty_gray(coordP1, coordP2, d) | Compute the smoothness penalty of assignments (p1,p1+d) and (p2,p2+d)
:param coordP1:
:param coordP2:
:param d:
:return: int | 625941d492d797404e304375 |
def in_lists(self, ip): <NEW_LINE> <INDENT> ret = "" <NEW_LINE> for z in self.ll: <NEW_LINE> <INDENT> if ip in self.la[z]: <NEW_LINE> <INDENT> ret += self.l_pre + str(z) + self.l_post <NEW_LINE> <DEDENT> <DEDENT> return ret | Return string of lists where 'ip' is in 'la'.
'la' - dict with key='list', val = list of 'ip'.
la = {list1: [ip1, ip2], list2: [ip1, ip3]} | 625941d4097d151d1a223043 |
def _parse(self, words): <NEW_LINE> <INDENT> post_parse = [] <NEW_LINE> for word in words: <NEW_LINE> <INDENT> split = word.split(' ') <NEW_LINE> if len(split) > 1: <NEW_LINE> <INDENT> post_parse.extend(split) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> post_parse.append(word) <NEW_LINE> <DEDENT> <DEDENT> return post... | Split twoword-phrases. | 625941d463b5f9789fde72d0 |
def __init__(self): <NEW_LINE> <INDENT> self.managed_logger = ManagedLogger() <NEW_LINE> self.loaded_config = configparser.RawConfigParser() <NEW_LINE> self.loaded_config.read_dict(self.default_config) <NEW_LINE> self.configure_logging() <NEW_LINE> path = self.read_config_from_file() <NEW_LINE> if path is not None: <NE... | Load the application configuration.
Note that this | 625941d476e4537e8c35185e |
def available(self): <NEW_LINE> <INDENT> raise Exception('implement me') | returns a dictionary of the versions available and at least the url for
each of those versions where we can download the tar ball, like so:
{
1.0 : {
url : 'http://xxx/blah-1.0.tar.gz'
},
2.0 : {
url : 'http://xxx/blah-1.0.tar.gz'
},
2.1 : {
... | 625941d438b623060ff0afd8 |
def _extract_basis_from_bfgs_blocks(self, text): <NEW_LINE> <INDENT> basis = { "units": "crystal", "elements": [], "coordinates": [] } <NEW_LINE> matches = re.findall(settings.REGEX["ion_position"]["regex"], text) <NEW_LINE> if matches: <NEW_LINE> <INDENT> for idx, match in enumerate(matches): <NEW_LINE> <INDENT> basis... | Extracts basis data in crystal units.
Args:
text (str): text to extract data from.
Returns:
dict
Example:
{
'units': 'crystal',
'elements': [{'id': 1, 'value': 'Si'}, {'id': 2, 'value': 'Si'}],
'coordinates': [{'id': 1, 'value': [0.0, 0.0, 0.0]}, {'id': 2, 'value': [0.0, 0.0, 0.0]... | 625941d4d268445f265b5059 |
def annotate_nongatk_vcf(orig_file, bam_file, dbsnp_file, ref_file, config): <NEW_LINE> <INDENT> broad_runner = broad.runner_from_config(config) <NEW_LINE> out_file = "%s-gatkann%s" % os.path.splitext(orig_file) <NEW_LINE> if not file_exists(out_file): <NEW_LINE> <INDENT> with file_transaction(out_file) as tx_out_file:... | Annotate a VCF file with dbSNP and standard GATK called annotations.
| 625941d44e4d5625662d45c1 |
def execute_program(executable, input_file, output_file): <NEW_LINE> <INDENT> with open(input_file) as infile, open(output_file, 'w') as outfile: <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> try: <NEW_LINE> <INDENT> subprocess.check_call( [executable], stdin=infile, stdout=outfile, timeout=60 ) <NEW_LINE> <D... | Use subprocess to execute the file with given input and output paths. | 625941d48e7ae83300e4b1b8 |
def get_sequences(self, organism_id): <NEW_LINE> <INDENT> return self.post('getSequencesForOrganism', {'organism': organism_id}) | Get the sequences for an organism
:type organism_id: str
:param organism_id: Organism ID Number
:rtype: list of dict
:return: The set of sequences associated with an organism | 625941d41f5feb6acb0c4d39 |
def filter_rectified(self, mask): <NEW_LINE> <INDENT> wx = np.median(np.sum(mask, axis=0)) <NEW_LINE> wy = np.median(np.sum(mask, axis=1)) <NEW_LINE> return wx > self.min_rectified_w and wy > self.min_rectified_w | mask : 1 where 'ON', 0 where 'OFF' | 625941d407d97122c4178a79 |
def make_image(self, name=None, description=None, date=0, client=None): <NEW_LINE> <INDENT> if client is None: <NEW_LINE> <INDENT> client = self.client <NEW_LINE> <DEDENT> image = self.new_image(name=name, description=description, date=date) <NEW_LINE> return client.sf.getUpdateService().saveAndReturnObject(image) | Creates a new image instance and returns the persisted object.
:param name: The image name. If None, a UUID string will be used
:param description: The image description
:param date: The image acquisition date
:param client: The client to use to create the object | 625941d40a50d4780f66707e |
def get_query(): <NEW_LINE> <INDENT> return QueDoidura.query() | Retorna um objeto query das coisas que precisam ser migradas | 625941d445492302aab5e4b0 |
def get_default_config(self): <NEW_LINE> <INDENT> config = super(LoadAverageCollector, self).get_default_config() <NEW_LINE> config.update({ 'enabled': 'True', 'path': 'loadavg', 'method': 'Threaded' }) <NEW_LINE> return config | Returns the default collector settings | 625941d4bd1bec0571d9081b |
def time(self): <NEW_LINE> <INDENT> time = {} <NEW_LINE> index = -1 <NEW_LINE> time_pattern = re.compile('[-.0-9长期]{2,}') <NEW_LINE> for i in range(self.N): <NEW_LINE> <INDENT> txt = self.result[i].replace('.', '').replace( ':', '').replace('B', '8').replace(';', '') <NEW_LINE> for j, num in enumerate(txt): <NEW_LINE> ... | 有效期限 | 625941d46fece00bbac2d92b |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <... | Returns the model properties as a dict | 625941d47c178a314d6ef64d |
def get_trades(self): <NEW_LINE> <INDENT> trade_data = [] <NEW_LINE> for ev in self.event_log: <NEW_LINE> <INDENT> match = re.match("TRADE\|", ev) <NEW_LINE> if match: <NEW_LINE> <INDENT> data = _Event.parse_str_data(ev[match.end():]) <NEW_LINE> trade_data.append(data) <NEW_LINE> <DEDENT> <DEDENT> trades = pd.DataFrame... | Return quantity, multiplier, price, no tcost price, instrument,
currency, and FX conversion rate of executed trades in order of
execution.
The quantity is the number of instruments traded. The multiplier is any
multiplier associated with futures contracts, this should be 1 for FX.
The price is the executed price of th... | 625941d4fff4ab517eb2f628 |
def add(self, args, skip_check=False): <NEW_LINE> <INDENT> if not skip_check: <NEW_LINE> <INDENT> for dev in args.device[:]: <NEW_LINE> <INDENT> item = self.dev[dev] <NEW_LINE> if item and 'pool_name' in item: <NEW_LINE> <INDENT> if item['pool_name'] == args.pool.name: <NEW_LINE> <INDENT> args.device.remove(dev) <NEW_L... | Add devices into the pool | 625941d4adb09d7d5db6c97a |
def get_formset(self): <NEW_LINE> <INDENT> formset_class = formset_factory(self.get_form_class(), **self.get_factory_kwargs()) <NEW_LINE> extra_form_kwargs = self.get_extra_form_kwargs() <NEW_LINE> if extra_form_kwargs: <NEW_LINE> <INDENT> formset_class.form = staticmethod(curry(formset_class.form, **extra_form_kwargs)... | Returns the final formset class from the formset factory | 625941d4187af65679ca530a |
def test_wavelet_length_error(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> bases.wavelets.Haar.wavelet(8, 6) | Test if ValueError is raised if the wavelet length is greater
than the signal length. | 625941d41d351010ab855d07 |
def _update(self, repos): <NEW_LINE> <INDENT> for repo in repos: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> repo._update_git() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> _logger.exception('Fail to update repo %s', repo.name) | Update the physical git reposotories on FS | 625941d4baa26c4b54cb1309 |
def doc_builder(template, dao_env, cfg): <NEW_LINE> <INDENT> working_template = dict(template) <NEW_LINE> global_config = _global_env(working_template, cfg) <NEW_LINE> top_node = working_template.keys() <NEW_LINE> if len(top_node) > 2: <NEW_LINE> <INDENT> raise TemplateError("Too many top-level nodes in template") <NEW... | Returns a tree of objects. Attributes can be picked up from
your configuration file (such as "institute"), from command-line
options or provided in the template. The resulting tree of objects
can be be walked to build up the CIM document. | 625941d47d847024c06be4a9 |
def test_registration_existing_username(self): <NEW_LINE> <INDENT> self.client().post(self.base_url + 'register', data=self.register_data) <NEW_LINE> response = self.client().post(self.base_url + 'register', data=self.register_data) <NEW_LINE> self.assertEqual(response.status_code, 400) <NEW_LINE> result = json.loads(r... | Test API for user registration with existing email address (POST request) | 625941d4c4546d3d9de72c20 |
def Disable(self): <NEW_LINE> <INDENT> return self.Enable(False) | Disables the control.
:returns: ``True`` if the window has been disabled, ``False`` if it had been
already disabled before the call to this function.
:note: This is functionally equivalent of calling :meth:`~Control.Enable` with a ``False`` flag. | 625941d4aad79263cf390c2e |
def experiment_finished(self, saving): <NEW_LINE> <INDENT> if saving: <NEW_LINE> <INDENT> self.exp_cntrls.curr_exp_config.start_btn.setEnabled(False) <NEW_LINE> self.exp_cntrls.curr_exp_config.start_btn.toggle_state('SAVING_VIDEOS') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.vid_cntrls.bounds_frm.setEnabled(Tru... | This runs when the experiment is finished | 625941d46fece00bbac2d92c |
def face_distance(known_face_encodings, face_to_compare): <NEW_LINE> <INDENT> return numpy.empty(0) if len(known_face_encodings) == 0 else numpy.linalg.norm(known_face_encodings - face_to_compare, axis=1) | Return the distance between two face encodings. | 625941d4287bf620b61d3c4e |
def searchMatrix(self, matrix, target): <NEW_LINE> <INDENT> m = len(matrix) <NEW_LINE> if m == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> n = len(matrix[0]) <NEW_LINE> if n == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> l = 0 <NEW_LINE> r = m*n-1 <NEW_LINE> while l<=r: <NEW_LINE> <INDENT> mid =... | :type matrix: List[List[int]]
:type target: int
:rtype: bool | 625941d48a43f66fc4b5424f |
@login_required <NEW_LINE> def profile_wizard(request): <NEW_LINE> <INDENT> profile = Profile.objects.get_or_create(user=request.user)[0] <NEW_LINE> if request.method == "POST": <NEW_LINE> <INDENT> form = ProfileForm(request.POST, instance=profile) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> form.save() <NEW_LIN... | View to fill Profile form
Arguments:
request {Request} -- The Request from the browser
Returns:
rendered template -- Render to My workouts, with modal for successful activation | 625941d46fb2d068a760f28b |
def params(*p): <NEW_LINE> <INDENT> def decorator(function): <NEW_LINE> <INDENT> wrapper = _wrap(function) <NEW_LINE> wrapper.simplestatic["params"] = p <NEW_LINE> return wrapper <NEW_LINE> <DEDENT> return decorator | Specifies the types of the parameters that the function accepts. | 625941d4b545ff76a8914001 |
def create_vtk_array(vtk_arr_type): <NEW_LINE> <INDENT> return vtkDataArray.CreateDataArray(vtk_arr_type) | Internal function used to create a VTK data array from another
VTK array given the VTK array type. | 625941d421a7993f00bc7edd |
def mmd_plus(graph, strategy="least-c"): <NEW_LINE> <INDENT> h = graph.copy() <NEW_LINE> maxmin = 0 <NEW_LINE> while len(h.vertices) >= 2: <NEW_LINE> <INDENT> v = h.get_minimum_degree_vertex() <NEW_LINE> maxmin = max(maxmin, v.get_degree()) <NEW_LINE> w = select_neighbour(v.neighbours_list, strategy) <NEW_LINE> h.contr... | Algorithm 3 MMD+(Graph G)
1: H = G
2: maxmin = 0
3: while H has at least two vertices do
4: Select a vertex v from H that has minimum degree in H.
5: maxmin = max(maxmin,dH (v)).
6: Select a neighbour w of v. {A specific strategy can be used here.}
7: Contract the edge {v, w} in H.
8: end while
9: r... | 625941d491af0d3eaac9bc06 |
def __init__(self, ip_string, client_type, userlevel, reporter = None): <NEW_LINE> <INDENT> self.ip = ip_string; <NEW_LINE> self.type = client_type; <NEW_LINE> self.userlevel = userlevel; <NEW_LINE> self.reporter = reporter; <NEW_LINE> self.last_action = time(); <NEW_LINE> self.id = Ice.Identity(); <NEW_LINE> self.inga... | @param ip_string IP string, which is retrieved from current.con.toString().
@param client_type Type of client that this is.
@param userlevel How powerful this user is.
@param reporter Optional reporter function for debug output. | 625941d4796e427e537b07b3 |
def say(self, stuff): <NEW_LINE> <INDENT> return stuff | *** YOUR CODE HERE *** | 625941d4cad5886f8bd271c4 |
@root.group("workshop") <NEW_LINE> @click.pass_context <NEW_LINE> def group_workshop(ctx): <NEW_LINE> <INDENT> pass | Manage workshop definitions. | 625941d4090684286d50eed2 |
def updateStatus(self, keyVar=None): <NEW_LINE> <INDENT> isOpen = self.model.calShutter[0] <NEW_LINE> isCurrent = self.model.calShutter.isCurrent <NEW_LINE> with self.updateLock(): <NEW_LINE> <INDENT> if isOpen == None: <NEW_LINE> <INDENT> self.shutterWdg.setIsCurrent(False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT... | shutterLimitSwitch keyword callback
| 625941d4c432627299f04e33 |
def loadDataExtents(self, arg2): <NEW_LINE> <INDENT> return _DataModel.DatabaseReader_loadDataExtents(self, arg2) | loadDataExtents(DatabaseReader self, DataAvailability arg2) -> int | 625941d47cff6e4e81117b71 |
def sync_data_down(context): <NEW_LINE> <INDENT> for syncdir in get_sync_dirs_down(): <NEW_LINE> <INDENT> sync_data_down_dir(syncdir) | Synchronizes the data from the cloud.
Returns the list of volume names. | 625941d4dc8b845886cb5721 |
def WeightedLearner(unweighted_learner): <NEW_LINE> <INDENT> def train(dataset, weights): <NEW_LINE> <INDENT> return unweighted_learner(replicated_dataset(dataset, weights)) <NEW_LINE> <DEDENT> return train | Given a learner that takes just an unweighted dataset, return
one that takes also a weight for each example. [p. 749 footnote 14] | 625941d4d58c6744b4257e4a |
def averageSeriesWithWildcards(requestContext, seriesList, *position): <NEW_LINE> <INDENT> if type(position) is int: <NEW_LINE> <INDENT> positions = [position] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> positions = position <NEW_LINE> <DEDENT> result = [] <NEW_LINE> matchedList = {} <NEW_LINE> for series in seriesLi... | Call averageSeries after inserting wildcards at the given position(s).
Example:
.. code-block:: none
&target=averageSeriesWithWildcards(host.cpu-[0-7].cpu-{user,system}.value, 1)
This would be the equivalent of
``target=averageSeries(host.*.cpu-user.value)&target=averageSeries(host.*.cpu-system.value)`` | 625941d4cad5886f8bd271c5 |
def get_bucket(length_file, num_batch_tokens, idx_init=150): <NEW_LINE> <INDENT> print('get the dataset info') <NEW_LINE> list_len = [] <NEW_LINE> with open(length_file) as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> length = int(line.strip().split()[1]) <NEW_LINE> list_len.append(length) <NEW_LINE> <DEDE... | enlarge idx_init can shrink the num of buckets | 625941d426238365f5f0f05c |
def insert_with_mapping(*, db, descrs, entity_table, pk_name, join_table, mapping, app_id, crawl_time): <NEW_LINE> <INDENT> for descr in descrs: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> entity_id = mapping[descr] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> entity_id = db[entity_table].insert({'descr': ... | Given a db connection, some list of description data, a table of entities, the name of the PK,
a many-to-many join table for the entities to game crawls,
a mapping from descrs to entity table IDs, and an app_id/crawl_time,
update the entity table/mapping if necessary and insert
the entity in the many-to-many join table... | 625941d445492302aab5e4b1 |
def on_exception(self, error): <NEW_LINE> <INDENT> print("Exception occured on the Twitter stream: {}".format(error)) | Simply prints out an exception if one occurs.
:param error: The error string received from upstream (Twitter) when an exception occurs. | 625941d40c0af96317bb83d4 |
def apply_gaussian_blur(network_pos, fluor, A=0.15, lamb=0.0315): <NEW_LINE> <INDENT> network_pos = network_pos[:] <NEW_LINE> fluor = fluor[:] <NEW_LINE> blurmat = get_blurring_matrix(network_pos, A, lamb) <NEW_LINE> crosstalk = np.dot((np.eye(blurmat.shape[0]) + blurmat), fluor) <NEW_LINE> blurred_fluor = fluor + cros... | Simulate optical blurring of fluorescence signal as a Gaussian function of
distance (as described in Stetter et al., 2012)
Arguments:
------------
network_pos: (2, ncells) float array
the x, y positions of each cell (nominally in mm)
fluor: (ncells, ntimebins) float array
the fluorescence tra... | 625941d4b5575c28eb68e1ed |
def create_cnn(): <NEW_LINE> <INDENT> model = Sequential() <NEW_LINE> model.add(Convolution2D(nb_filter=10, nb_row=2, nb_col=2, input_shape=(1, 64, 64))) <NEW_LINE> model.add(Activation('relu')) <NEW_LINE> model.add(MaxPooling2D(pool_size=(3, 3))) <NEW_LINE> model.add(Convolution2D(nb_filter=10, nb_row=2, nb_col=2, inp... | Create a convolutional neural network for compressing the input images.
Reference:
Koutnik, Jan, Jurgen Schmidhuber, and Faustino Gomez. "Evolving deep
unsupervised convolutional networks for vision-based reinforcement
learning." Proceedings of the 2014 conference on Genetic and
evolutionary computation. ACM, 2014. | 625941d485dfad0860c3b047 |
def _random_gamma(alpha=_Null, beta=_Null, shape=_Null, ctx=_Null, dtype=_Null, out=None, name=None, **kwargs): <NEW_LINE> <INDENT> return (0,) | Draw random samples from a gamma distribution.
Samples are distributed according to a gamma distribution parametrized by *alpha* (shape) and *beta* (scale).
Example::
gamma(alpha=9, beta=0.5, shape=(2,2)) = [[ 7.10486984, 3.37695289],
[ 3.91697288, 3.65933681]]
Defi... | 625941d4dc8b845886cb5722 |
def _setVals(self, ip_A=0, port_A=0, ip_B=0, port_B=0, mhp_seq=0, meas_out=0, basis=0, t_create=0.0, goodness=0.0, DF=0, create_id=0): <NEW_LINE> <INDENT> self.ip_A = ip_A <NEW_LINE> self.port_A = port_A <NEW_LINE> self.ip_B = ip_B <NEW_LINE> self.port_B = port_B <NEW_LINE> self.mhp_seq = mhp_seq <NEW_LINE> self.meas_o... | Set using given values. | 625941d4a79ad161976cc332 |
def default_multivariate_normal_fn(dtype, shape, name, trainable, add_variable_fn): <NEW_LINE> <INDENT> del name, trainable, add_variable_fn <NEW_LINE> dist = tfd.Normal(loc=tf.zeros(shape, dtype), scale=1.0) <NEW_LINE> batch_ndims = tf.size(dist.batch_shape_tensor()) <NEW_LINE> return tfd.Independent(dist, reinterpret... | Creates multivariate standard `Normal` distribution.
Args:
dtype: Type of parameter's event.
shape: Python `list`-like representing the parameter's event shape.
name: Python `str` name prepended to any created (or existing)
`tf.Variable`s.
trainable: Python `bool` indicating all created `tf.Variable`s shoul... | 625941d423e79379d52ee74e |
def set_features_from_ipa(self, ipa_str): <NEW_LINE> <INDENT> ipa_char_features = self.feature_model.get_features_from_ipa(ipa_str) <NEW_LINE> self.clear_features() <NEW_LINE> self.set_features_to_values(self.feature_model.features, ipa_char_features) | Takes Unicode IPA symbol (optionally with diacritics) and
automagically assigns appropriate featural values to Phone | 625941d41f037a2d8b9463ea |
def random_word(a_list): <NEW_LINE> <INDENT> return random.choice(a_list) | Takes a list and returns a random element from that list.
Keyword Arguments:
a_list -- list to select from | 625941d49c8ee82313fbb961 |
def insert_lhb_summary_table(self, items): <NEW_LINE> <INDENT> for item in items: <NEW_LINE> <INDENT> row = (item['stock_id'], item['end_date'], item['reason'].encode('utf-8'), item['change_percent'], item['buy_value'], item['sell_value'], item['net_value'], get_current_timestamp("Asia/Shanghai")) <NEW_LINE> self.datab... | This method inserts a list of items into table cinema_info
Parameters
----------
items: list of cinema items to insert
Returns
-------
None | 625941d4cdde0d52a9e53220 |
def get_chunk(self): <NEW_LINE> <INDENT> return self.chunk | Retrieve chunk content | 625941d494891a1f4081bc95 |
def delimitString(xstr, delimeter=" - "): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> op = "" <NEW_LINE> xlist = None <NEW_LINE> if type(xstr) is str: <NEW_LINE> <INDENT> xlist = xstr.split(" ") <NEW_LINE> <DEDENT> elif type(xstr) is list: <NEW_LINE> <INDENT> xlist = xstr <NEW_LINE> <DEDENT> if xlist is None: <NEW_LIN... | Delimits the string with the delimiter.
Args:
xstr: str or list
delimeter: str
Raises:
ValueError: Exception
Returns:
str: | 625941d49c8ee82313fbb962 |
def test_activation_invalid_key(self): <NEW_LINE> <INDENT> self.assertFalse(RegistrationProfile.objects.activate_user('foo')) | Attempting to activate with a key which is not a UUID
fails. | 625941d450812a4eaa59c50c |
def set_scientific_name(self, scientific_name): <NEW_LINE> <INDENT> definition = self.get_last_definition() <NEW_LINE> if definition is None: <NEW_LINE> <INDENT> definition = self.create_definition() <NEW_LINE> self.add_definition(definition) <NEW_LINE> <DEDENT> definition.set_scientific_name(scientific_name) <NEW_LINE... | ! @brief Set scientific name.
Attribute 'scientificName' is owned by Statement, which is owned by Definition.
@param scientific_name Scientific name.
@return Sense instance. | 625941d44c3428357757c513 |
def log_to_stdout(self): <NEW_LINE> <INDENT> logger = logging.getLogger('ExperimentUtils') <NEW_LINE> logger.setLevel(logging.INFO) <NEW_LINE> logger.handlers = [logging.StreamHandler(sys.stdout)] | Make ExperimentUtils instance log to stdout.
:return: None | 625941d44f88993c3716c252 |
def logger_config(log_path,logging_name): <NEW_LINE> <INDENT> logger = logging.getLogger(logging_name) <NEW_LINE> logger.setLevel(level=logging.DEBUG) <NEW_LINE> handler = logging.FileHandler(log_path, encoding='UTF-8') <NEW_LINE> handler.setLevel(logging.INFO) <NEW_LINE> formatter = logging.Formatter('%(asctime)s - %(... | 配置log
:param log_path: 输出log路径
:param logging_name: 记录中name,可随意
:return: | 625941d407f4c71912b11670 |
def test_past_as_clockingblock_2(self): <NEW_LINE> <INDENT> moddict = ModDict() <NEW_LINE> moddict.parse(inputs.TEST_MODULE_2) <NEW_LINE> printer = Printer(moddict, indent_size=2) <NEW_LINE> clockingblock = printer['ClockingBlock'] <NEW_LINE> self.assertEqual('\n' + clockingblock, TEST_MODULE_2_REF) | Test past as clockingblock with TEST_MODULE_2 | 625941d416aa5153ce362663 |
def __imul__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, int): <NEW_LINE> <INDENT> raise TypeError("can't multiply Seq by non-int type") <NEW_LINE> <DEDENT> return self.__class__(str(self) * other, self.alphabet) | Multiply Seq in-place.
Note although Seq is immutable, the in-place method is
included to match the behaviour for regular Python strings.
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_dna
>>> seq = Seq('ATG', generic_dna)
>>> seq *= 2
>>> seq
Seq('ATGATG', DNAAlphabet()) | 625941d47d847024c06be4aa |
def createMessage(self, commentnode, defaulttitle=None): <NEW_LINE> <INDENT> title = get_value(commentnode, 'title') <NEW_LINE> if title is None: <NEW_LINE> <INDENT> title = defaulttitle <NEW_LINE> <DEDENT> sender = self.getPerson(get_element(commentnode, 'sender')) <NEW_LINE> if sender is None: <NEW_LINE> <INDENT> sen... | Create an IMessage representing a <comment> element. | 625941d4b830903b967e9af6 |
def _write(self, message): <NEW_LINE> <INDENT> from syr.lock import locked <NEW_LINE> with locked(_Log.lock): <NEW_LINE> <INDENT> self.check_user() <NEW_LINE> if not self.opened: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.open() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.last_exception() <NEW_LINE> <DE... | Write directly to python logger. | 625941d4460517430c39436e |
def normalize(self, gradients): <NEW_LINE> <INDENT> gradients.data = torch.sign(gradients.data) | Normalization.
:param gradients: gradients
:type gradients: torch.autograd.Variable | 625941d4462c4b4f79d1d8bc |
def _parse_file(self, data_file): <NEW_LINE> <INDENT> raise UserError( _( "This bank statement file format is not supported.\n" "Did you install the Odoo module to support this format?" ) ) | Each module adding a file support must extends this method.
It processes the file if it can, returns super otherwise,
resulting in a chain of responsability.
This method parses the given file and returns the data required
by the bank statement import process, as specified below.
rtype: triplet
- currency code: stri... | 625941d43c8af77a43ae398d |
def customize_discussion(block, block_data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> block_data['name'] = block.attrib['discussion_target'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> block_data['name'] = block.attrib['discussion_category'] <NEW_LINE> <DEDENT> except KeyError:... | Sets the block name for Discussions if emtpy. | 625941d4d8ef3951e324372a |
def autosave_data(nargs, kwargs_keys=None, version=None): <NEW_LINE> <INDENT> def decorator_function(function): <NEW_LINE> <INDENT> posargs_keys = list(inspect.signature(function).parameters)[:nargs] <NEW_LINE> @functools.wraps(function) <NEW_LINE> def autosave(*args, **kwargs): <NEW_LINE> <INDENT> description = kwargs... | Enable autosaving of results for a function.
Args:
nargs: Number of args which are relevant for the calculation.
kwargs_keys (opt.): List of keyword arguments which are relevant for the calculation.
version (opt.):
An optional version number of the decorated function, which replaces the checksum o... | 625941d4f8510a7c17cf98e8 |
def rev_geocode_locs(db='Session_db.db'): <NEW_LINE> <INDENT> k = get_keys()['MapQuest'] <NEW_LINE> con = sqlite3.connect(db) <NEW_LINE> cur = con.cursor() <NEW_LINE> get_locs_sql = "SELECT id, Lat, Lon FROM Location" <NEW_LINE> pop_locs_sql = '''UPDATE Location SET Name = "{s}, {c}, {p}" WHERE id = {i}''' <NEW_LINE> c... | Takes 1 argument - db - path to sqlite db.
Updates the Location table with reverse geocoded location names using MapQuest API | 625941d4d58c6744b4257e4b |
@workflow.command(name='remove-subject-sets') <NEW_LINE> @click.argument('workflow-id', type=int) <NEW_LINE> @click.argument('subject-set-ids', type=int, nargs=-1) <NEW_LINE> def remove_subject_sets(workflow_id, subject_set_ids): <NEW_LINE> <INDENT> workflow = Workflow.find(workflow_id) <NEW_LINE> workflow.remove_subje... | Unlinks the given subject sets from the given workflow. | 625941d4ad47b63b2c50a16c |
def clear(self): <NEW_LINE> <INDENT> self.size = 0 | Remove all items but keep the shape and dtype unchanged. | 625941d401c39578d7e75028 |
def darkBrewerColors(listlength=6): <NEW_LINE> <INDENT> return np.array(["#1f78b4", "#33a02c", "#e31a1c", "#ff7f00", "#6a3d9a", "#b15928"][:min(6, listlength)]) | Returns a list of dark Brewer-scale colors. | 625941d4e1aae11d1e749ea5 |
def transformationMode(self): <NEW_LINE> <INDENT> pass | QGraphicsPixmapItem.transformationMode() -> Qt.TransformationMode | 625941d4596a897236089cab |
def config_key_exists(self, key, body='json', timeout=None): <NEW_LINE> <INDENT> kwargs = dict(body=body, timeout=timeout) <NEW_LINE> if not isinstance(key, six.string_types): <NEW_LINE> <INDENT> raise CephClientTypeError( name='key', actual=type(key), expected=six.string_types) <NEW_LINE> <DEDENT> kwargs['key'] = key ... | check for <key>'s existence | 625941d40383005118ecf7ce |
def centroid(polygon): <NEW_LINE> <INDENT> if polygon[0] != polygon[-1]: <NEW_LINE> <INDENT> raise Exception('Polygon not closed') <NEW_LINE> <DEDENT> num_point = len(polygon) <NEW_LINE> A = 0 <NEW_LINE> xmean = 0 <NEW_LINE> ymean = 0 <NEW_LINE> for i in range(num_point-1): <NEW_LINE> <INDENT> p1 = polygon[i] <NEW_LINE... | Calculates the centroid and area of a polygon.
Input
pgon: a list of Point objects
Output
A: the area of the polygon
C: the centroid of the polygon | 625941d4eab8aa0e5d26dd45 |
def test_create_table_from_final_row(): <NEW_LINE> <INDENT> t1 = table.Table([(1, 2)], names=['col']) <NEW_LINE> row = t1[-1] <NEW_LINE> t2 = table.Table(row)['col'] <NEW_LINE> assert t2[0] == 2 | Regression test for issue #8422: passing the last row of a table into
Table should return a new table containing that row. | 625941d43617ad0b5ed680e3 |
def install_packages(self): <NEW_LINE> <INDENT> installs, upgraded = [], [] <NEW_LINE> for inst in (self.dep_install + self.install): <NEW_LINE> <INDENT> package = (self.tmp_path + inst).split() <NEW_LINE> pkg_ver = "{0}-{1}".format(split_package(inst)[0], split_package(inst)[1]) <NEW_LINE> self.checksums(inst) <NEW_LI... | Install or upgrade packages
| 625941d42c8b7c6e89b359ad |
def countNodes(self, root): <NEW_LINE> <INDENT> h = height(root) <NEW_LINE> if h < 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if height(root.right) == h - 1: <NEW_LINE> <INDENT> return (1 << h) + countNodes(root.right) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (1 << h - 1) ... | :type root: TreeNode
:rtype: int | 625941d463b5f9789fde72d2 |
def test_units_vTh(self): <NEW_LINE> <INDENT> distFunc = kappa_velocity_3D( vx=self.vx, vy=self.vy, vz=self.vz, T=self.T, kappa=self.kappa, vTh=self.vTh, particle=self.particle, units="units", ) <NEW_LINE> errStr = ( f"Distribution function should be {self.distFuncTrue} " f"and not {distFunc}." ) <NEW_LINE> assert np.i... | Tests distribution function with units and passing vTh. | 625941d4cc0a2c11143dd07d |
def confd_state_snmp_version_v1(self, **kwargs): <NEW_LINE> <INDENT> config = ET.Element("config") <NEW_LINE> confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") <NEW_LINE> snmp = ET.SubElement(confd_state, "snmp") <NEW_LINE> version = ET.SubElement(snmp, "version") <NEW_... | Auto Generated Code
| 625941d4167d2b6e31218d82 |
def merge_datelist_xr(ds1, ds2, col="date"): <NEW_LINE> <INDENT> import pandas as pd <NEW_LINE> d = pd.merge(pd.Series(ds1.indexes[col]), pd.Series(ds2.indexes[col]), how="outer") <NEW_LINE> out_series = d.sort_values([col]).reset_index(drop=True) <NEW_LINE> return out_series.to_xarray().date | Find the outer join of ds1[col] and ds2[col] | 625941d4596a897236089cac |
def create_new_release( repository, github_token, version_tag, message, should_prompt_for_message ): <NEW_LINE> <INDENT> master_commit = get_commit(repository, github_token, "master") <NEW_LINE> if not message: <NEW_LINE> <INDENT> latest_release = get_latest_release(repository, github_token) <NEW_LINE> commit_summaries... | Creates a new release, optionally prompting the user for a release message
Args:
repository: The github repository
github_token: The github token that can create releases
verison_tag: The version tag that should be created at the current 'master'
message: If None, prompt the user for a message (or crea... | 625941d4bde94217f3682fdc |
def search_file_for_timestamp_boundry(file_path, time_boundry: datetime.datetime): <NEW_LINE> <INDENT> index_file = f"{file_path}.index" <NEW_LINE> char_indexes = None <NEW_LINE> with open(index_file) as f: <NEW_LINE> <INDENT> char_indexes = [int(l) for l in f.readlines()] <NEW_LINE> <DEDENT> with open(file_path) as f:... | :param file_path: The file path to search through
:return: | 625941d4be8e80087fb20e2e |
def new_asset_instance_output_file( asset_instance, temporal_entity, output_type, task_type, comment, name="master", mode="output", working_file=None, person=None, revision=0, nb_elements=1, representation="", sep="/" ): <NEW_LINE> <INDENT> asset_instance = normalize_model_parameter(asset_instance) <NEW_LINE> temporal_... | Create a new output file for given asset instance, temporal entity, task
type and output type. It generates and store the expected path and sets a
revision number (last revision + 1).
Args:
entity (str / id): Entity for which an output file is needed.
output_type (str / id): Output type of the generated file.... | 625941d4435de62698dfde3a |
def postorder(self, root): <NEW_LINE> <INDENT> if root == None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> stack1 = [] <NEW_LINE> stack2 = [] <NEW_LINE> cur = self.root <NEW_LINE> stack1.append(cur) <NEW_LINE> while stack1: <NEW_LINE> <INDENT> cur = stack1.pop() <NEW_LINE> if cur.lchild: <NEW_LINE> <INDENT> stack1.... | 深度优先——后序遍历:左子树->右子树->根节点---栈实现 | 625941d44e4d5625662d45c3 |
def set(self, db_key: str, db_value: str) -> bool: <NEW_LINE> <INDENT> self.c_logger.info( "Starting to set the '{}:{}' string key-value pair".format(db_key, db_value) ) <NEW_LINE> try: <NEW_LINE> <INDENT> self.c_logger.debug("Try to convert the getting value to string.") <NEW_LINE> db_value: str = str(db_value) <NEW_L... | Setting a new item in the DB (string).
This is the default setting of DB.
:param db_key: Key of the item.
:param db_value: Value of the key.
:return: True if the operation is success else False. | 625941d48e7ae83300e4b1ba |
def enable_quantitative_normalization(self, enable): <NEW_LINE> <INDENT> self.quantitative_normalization = bool(enable) <NEW_LINE> tmp = self.param_quant_analysis <NEW_LINE> self.param_quant_analysis = ParamQuantitativeAnalysis() <NEW_LINE> self.param_quant_analysis = tmp <NEW_LINE> self.set_low_high_value() <NEW_LINE>... | Enable/Disable quantitative normalization.
Parameters
----------
enable: bool
Enable quantitative normalization if True, disable if False. | 625941d407d97122c4178a7b |
def test_parser_without_type(parser): <NEW_LINE> <INDENT> with pytest.raises(SystemExit): <NEW_LINE> <INDENT> parser.parse_args( ["-H", "localhost", "-U", "user", "-P" "5432", "--driver", "local", "backups"]) | Without a specified driver the parser will exit | 625941d41f5feb6acb0c4d3b |
@app.route("/api/v1.0/tobs") <NEW_LINE> def tobs(): <NEW_LINE> <INDENT> results = session.query(Measurement.date, Measurement.tobs). filter(Measurement.date >= '2016-08-24'). filter(Measurement.date <= '2017-08-23'). group_by(Measurement.date).order_by(Measurement.date.desc()).all() <NEW_L... | Returns list of Temperature Observations (tobs) for the previous year. | 625941d4fff4ab517eb2f629 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.