code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def hamster_to_dbus_tag(tag): <NEW_LINE> <INDENT> def get_pk(tag): <NEW_LINE> <INDENT> return _none_to_int(tag.pk) <NEW_LINE> <DEDENT> def get_name(tag): <NEW_LINE> <INDENT> return tag.name <NEW_LINE> <DEDENT> if tag is None: <NEW_LINE> <INDENT> result = DBusTag(-2, '') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res... | Convert a ``hamster_lib.Tag`` instance to its dbus representation.
The resulting tuple is suitable for dbus messages and has the following
signature: '(is)'.
i = tag.pk
s = tag.name
Args:
tag (hamster_lib.Tag): Tag instance to be serialized.
Returns:
DBusTag: Serialized tag instance. If the tag to be
se... | 625941c7f7d966606f6aa03d |
def now() -> ir.TimestampScalar: <NEW_LINE> <INDENT> return ops.TimestampNow().to_expr() | Return an expression that will compute the current timestamp.
Returns
-------
TimestampScalar
A "now" expression | 625941c7e64d504609d7487a |
def inputLineChunk(): <NEW_LINE> <INDENT> values = [] <NEW_LINE> firstChrom = None <NEW_LINE> firstPos = None <NEW_LINE> lastChrom = None <NEW_LINE> lastPos = None <NEW_LINE> for line in subprocess.Popen(['zcat', "whole_genome_SNVs.tsv.gz"], stdout=subprocess.PIPE, encoding="ascii").stdout: <NEW_LINE> <INDENT> if line.... | yield all values at consecutive positions as a tuple (chrom, pos, list of (nucl, phred value)) | 625941c7d18da76e2353250f |
def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): <NEW_LINE> <INDENT> if system == "win32": <NEW_LINE> <INDENT> if appauthor is None: <NEW_LINE> <INDENT> appauthor = appname <NEW_LINE> <DEDENT> path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) <NEW_LINE> if appname: <NEW_LIN... | Return full path to the user-shared data dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the name of the
appauthor or distributing body for this application. Typically
it is the owning ... | 625941c7aad79263cf390a7a |
def __init__(self, path_dd = DEF_PATH_DD, source = DEF_SOURCE, destination = DEF_DEST, blocksize = DEF_BLOCKSIZE, redirectOutput = None): <NEW_LINE> <INDENT> self.path_dd = path_dd <NEW_LINE> self.source = source <NEW_LINE> self.destination = destination <NEW_LINE> self.blocksize = blocksize <NEW_LINE> self.redirectOut... | Initialises the settings instance. All parameters have default values. Check the
instance variables in this module.
@param path_dd: Path to the command dd
@type path_dd: C{String}
@param source: Source to be imaged
@type source: C{String}
@param destination: Filename of the image file to be created
@type destination: ... | 625941c79b70327d1c4e0e0f |
def timestr_to_seconds(timestr, fmt=TIMESTR_FORMAT_DEFAULT): <NEW_LINE> <INDENT> return int(time.mktime(time.strptime(timestr, fmt))) | Convert time in str to unix time.
>>> timestr_to_seconds('20140324_150016')
1395644416
>>> timestr_to_seconds('14M03D24h15m00s16', TIMESTR_FORMAT_API)
1395644416
>>> timestr_to_seconds('2014-03-24 15:00:16', TIMESTR_FORMAT_FULL)
1395644416 | 625941c75fdd1c0f98dc026d |
def delete_things(ckan, thing, arguments, worker_pool=None, stdin=None, stdout=None, stderr=None): <NEW_LINE> <INDENT> if worker_pool is None: <NEW_LINE> <INDENT> worker_pool = workers.worker_pool <NEW_LINE> <DEDENT> if stdin is None: <NEW_LINE> <INDENT> stdin = getattr(sys.stdin, 'buffer', sys.stdin) <NEW_LINE> <DEDEN... | delete datasets, groups, orgs, users etc,
The parent process creates a pool of worker processes and hands
out json lines to each worker as they finish a task. Status of
last record completed and records being processed is displayed
on stderr. | 625941c71b99ca400220aaec |
def get_file(self, handle_or_path: Union[int, str], default=None) -> File: <NEW_LINE> <INDENT> warnings.warn( "get_file() is deprecated. Please use objects.query() instead.", DeprecationWarning ) <NEW_LINE> if isinstance(handle_or_path, int): <NEW_LINE> <INDENT> condition = dict(handle=handle_or_path) <NEW_LINE> <DEDEN... | Gets a file by handle or path. Returns default if not existent.
:raises TypeError: if handle points and object that is not a File. | 625941c7442bda511e8be454 |
def start(self, bot): <NEW_LINE> <INDENT> self.bot = bot | Start the adapter. This is where the connection will be initialized. All subclasses must
super this method. | 625941c721a7993f00bc7d28 |
def copy_from(self, source_image, **kwargs): <NEW_LINE> <INDENT> teek.tcl_call(None, self, 'copy', source_image, *_options(kwargs)) | See ``imageName copy sourceImage`` documented in :man:`photo(3tk)`.
Options are passed as usual, except that ``from=something`` is invalid
syntax in Python, so this method supports ``from_=something`` instead.
If you do ``image1.copy_from(image2)``, the ``imageName`` in
:man:`photo(3tk)` means ``image1``, and ``source... | 625941c757b8e32f524834d5 |
def setMxPrint(self): <NEW_LINE> <INDENT> m = self.stream <NEW_LINE> foundAny = m.getElementsByClass('LayoutBase') <NEW_LINE> if not foundAny: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> mxPrint = None <NEW_LINE> found = m.getElementsByClass('PageLayout') <NEW_LINE> if found: <NEW_LINE> <INDENT> pl = found[0] <NEW_L... | Creates a <print> element and appends it to root, if one is needed. | 625941c782261d6c526ab4d8 |
def do_draw(self, cr): <NEW_LINE> <INDENT> alloc = self.get_allocation() <NEW_LINE> if self._background is not None: <NEW_LINE> <INDENT> Gdk.cairo_set_source_pixbuf(cr, self._background, 0, 0) <NEW_LINE> cr.paint() <NEW_LINE> <DEDENT> if not self._show_offset: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> offset = sel... | Draw widget | 625941c715baa723493c3faf |
def test_graphql_healthcheck_with_data(self, client): <NEW_LINE> <INDENT> json = {"query": self.query, "variables": {"name": "Test"}} <NEW_LINE> response = client.post("/graphql", json=json) <NEW_LINE> result = response.json() <NEW_LINE> assert result["data"]["healthcheck"] == "Hello Test!" | [GQL-HC-02] returns a custom greeting with 'name' variable | 625941c74a966d76dd551049 |
def updateDistribution(distribution, samples, costs): <NEW_LINE> <INDENT> raise NotImplementedError('subclasses must override updateDistribution()!') | Update a distribution with reward-weighted averaging.
\param[in] distribution Distribution before the update
\param[in] samples Samples in parameter space.
\param[in] costs The cost of each sample.
eturn The updated distribution. | 625941c7091ae35668666f9b |
def test_time_away(self): <NEW_LINE> <INDENT> result = self.test_client.away <NEW_LINE> assert isinstance(result, dict) | Unit test for `ResultBase.time` | 625941c744b2445a339320d1 |
def __init__(self, parent=None): <NEW_LINE> <INDENT> QDialog.__init__(self, parent) <NEW_LINE> self.setupUi(self) <NEW_LINE> self.setWindowTitle('QGIS WPS-Client ' + version()) | Constructor | 625941c74f88993c3716c0a3 |
def removeData(key): <NEW_LINE> <INDENT> if ( type(key) != str ): return None <NEW_LINE> try: <NEW_LINE> <INDENT> del Co8PersistentData.__dataDict[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass | Remove the data entry with that key(string only). | 625941c74527f215b584c493 |
def __init__(self, script='', title='', id=None, last_updated=None, script_language_version=None): <NEW_LINE> <INDENT> self.title = title if title else DEFAULT_SCRIPT_NAME <NEW_LINE> self.script = script <NEW_LINE> if not id: <NEW_LINE> <INDENT> self._set_new_id() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.id =... | Base class for Picard script objects
Args:
script (str): Text of the script.
title (str): Title of the script.
id (str): ID code for the script. Defaults to a system generated uuid.
last_updated (str): The UTC date and time when the script was last updated. Defaults to current date/time. | 625941c75166f23b2e1a5194 |
def p_constructor_header(self, p): <NEW_LINE> <INDENT> p[1]['parameters'] = p[2] <NEW_LINE> p[1]['throws'] = p[4] <NEW_LINE> p[1]['lineno'] = p.lexer.lineno <NEW_LINE> p[0] = p[1] | constructor_header : constructor_header_name formal_parameter_list_opt ')' method_header_throws_clause_opt | 625941c7596a897236089afd |
def sim_pearson(song_a, song_b, database): <NEW_LINE> <INDENT> both_rated = shared(song_a, song_b, database) <NEW_LINE> n = len(both_rated) <NEW_LINE> sum_a = 0 <NEW_LINE> sum_b = 0 <NEW_LINE> sq_sum_a = 0 <NEW_LINE> sq_sum_b = 0 <NEW_LINE> sum_ab = 0 <NEW_LINE> for sID in both_rated: <NEW_LINE> <INDENT> sum_a += datab... | Returns a similarity score using the pearson correlation coefficient formula between the ratings of two songs given a database. | 625941c7377c676e912721e4 |
def __init__(self, in_channels, out_channels, stride=1, padding=None, kernel_size=(3,3), bn=True, nonlinear='relu', dropout = 0., bias=True, **kwargs): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.weight = nn.Parameter(th.randn(out_channels, in_channels, *kernel_size)) <NEW_LINE> if bias: <NEW_LINE> <INDENT... | A 2d convolution block. The convolution is followed by batch
normalization (if active).
Args:
in_channels: number of input channels
out_channels: number of output channels
stride (int, optional): stride of the convolutions (default: 1)
kernel_size (tuple, optional): kernel shape (default: 3)
bn (b... | 625941c72eb69b55b151c8e8 |
@vacancy_blueprint.route('', methods=['GET', 'POST']) <NEW_LINE> def vacancy(): <NEW_LINE> <INDENT> vac = Vacancy.query.all() <NEW_LINE> return render_template('vacancy.html', vac=vac) | Loading vacancy list. | 625941c7c4546d3d9de72a6e |
def change_password(request): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> page_title = "Eigenes Passwort ändern" <NEW_LINE> if request.method == 'POST': <NEW_LINE> <INDENT> form = PasswordChangeForm(user, request.POST) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> user = form.save() <NEW_LINE> update_sessio... | Changes the password for a user with entering the old password | 625941c78c0ade5d55d3e9f5 |
def get_per_instance_usage(self, *args, **kwargs): <NEW_LINE> <INDENT> return {} | Get information about instance resource usage.
:returns: dict of nova uuid => dict of usage info | 625941c7cc0a2c11143dcecb |
def move(src, dst): <NEW_LINE> <INDENT> if not isinstance(dst, Path): <NEW_LINE> <INDENT> dst = local.path(dst) <NEW_LINE> <DEDENT> if isinstance(src, (tuple, list)): <NEW_LINE> <INDENT> if not dst.exists(): <NEW_LINE> <INDENT> dst.mkdir() <NEW_LINE> <DEDENT> elif not dst.is_dir(): <NEW_LINE> <INDENT> raise ValueError(... | Moves the source path onto the destination path; ``src`` and ``dst`` can be either
strings, :class:`LocalPaths <plumbum.path.local.LocalPath>` or
:class:`RemotePath <plumbum.path.remote.RemotePath>`; any combination of the three will
work.
.. versionadded:: 1.3
``src`` can also be a list of strings/paths, in which... | 625941c7c432627299f04c80 |
def reset(self): <NEW_LINE> <INDENT> super(IronicNode, self).reset() <NEW_LINE> self.wait_for_state(expected_state='active', timeout=self.wait_active_timeout) <NEW_LINE> self.driver.conn.node.set_power_state( node_id=self.uuid, state='reboot', soft=False, ) | Reboot node | 625941c7293b9510aa2c32d2 |
def download_file(url, outdir='.', session=None): <NEW_LINE> <INDENT> if session is None: <NEW_LINE> <INDENT> session = requests.session() <NEW_LINE> <DEDENT> path = os.path.join(outdir, os.path.basename(url)) <NEW_LINE> logger.info('Downloading URL: {}'.format(url)) <NEW_LINE> r = session.get(url, stream=True, verify=... | Download file to specified directory. | 625941c785dfad0860c3ae96 |
def test_multiple_negated_condition_values(self): <NEW_LINE> <INDENT> from bigquery.query_builder import render_query <NEW_LINE> result = render_query( dataset='dataset', tables=['2013_06_appspot_1'], select={ 'start_time': {'alias': 'timestamp'}, 'status': {'alias': 'status'}, 'resource': {'alias': 'url'} }, condition... | Ensure that render query can handle conditions with multiple negated
values. | 625941c721a7993f00bc7d29 |
def do_POST_edits(self): <NEW_LINE> <INDENT> if not _SERVER.is_editable: <NEW_LINE> <INDENT> raise Exception('this server is not running in --editable mode') <NEW_LINE> <DEDENT> content_type = self.headers[_HTTP_HEADER_CONTENT_TYPE] <NEW_LINE> if content_type != 'application/json;charset=UTF-8': <NEW_LINE> <INDENT> rai... | Handle a POST request with modifications to GM expectations, in this
format:
{
KEY__EDITS__OLD_RESULTS_TYPE: 'all', # type of results that the client
# loaded and then made
# modifications to
KEY__EDITS__OLD_RESULTS_HASH: 39850913, # ... | 625941c73539df3088e2e386 |
def __init__(self): <NEW_LINE> <INDENT> self.ScheduledActionId = None | :param ScheduledActionId: ID of the scheduled task to be deleted.
:type ScheduledActionId: str | 625941c7293b9510aa2c32d3 |
def __init__(self): <NEW_LINE> <INDENT> pass | Constructor | 625941c794891a1f4081bae4 |
def autosize_scatter(x, y, color_array=None, mask=None, mask_color='k', subplots_kwargs=None, **kwargs): <NEW_LINE> <INDENT> if subplots_kwargs is None: <NEW_LINE> <INDENT> subplots_kwargs = dict(figsize=(6,7.3)) <NEW_LINE> <DEDENT> if 'cmap' not in kwargs: <NEW_LINE> <INDENT> kwargs['cmap'] = 'Greys' <NEW_LINE> <DEDEN... | Make a scatter plot of the input and automatically figure out the
size of the marker so there is no whitespace between the markers.
To switch to a log colorbar, for example, use the kwarg
`norm=matplotlib.colors.LogNorm()`.
Parameters
----------
x : array_like
x positions.
y : array_like
y positions.
color_ar... | 625941c7004d5f362079a36f |
def testSizeOfOverlap(self): <NEW_LINE> <INDENT> region1 = GenomicInterval("chr1", 10, 20, "read", 1, "+") <NEW_LINE> region2 = GenomicInterval("chr1", 10, 20, "read", 1, "+") <NEW_LINE> self.assertEqual(region1.sizeOfOverlap(region2), len(region2)) <NEW_LINE> self.assertEqual(region1.sizeOfOverlap(region2), region2.si... | Test getting the sie of overlap between two regions. | 625941c73317a56b86939c96 |
def notify(context, topic, msg, envelope=False): <NEW_LINE> <INDENT> return _get_impl().notify(cfg.CONF, context, topic, msg, envelope) | Send notification event.
:param context: Information that identifies the user that has made this
request.
:param topic: The topic to send the notification to.
:param msg: This is a dict of content of event.
:param envelope: Set to True to enable message envelope for notifications.
:returns: None | 625941c7a8370b77170528dc |
def test_dijkstra_on_a_path_of_five(path_graph): <NEW_LINE> <INDENT> path = path_graph.dijkstra('A', 'F')[1] <NEW_LINE> assert path == ['A', 'C', 'D', 'E', 'F'] | Test dijkstra for a path of 5 nodes. | 625941c7cc0a2c11143dcecc |
def __init__(self, components=None, mapping=None, initial_pressures=None, initial_states=None): <NEW_LINE> <INDENT> if not components: <NEW_LINE> <INDENT> components = {} <NEW_LINE> <DEDENT> if not mapping: <NEW_LINE> <INDENT> mapping = {} <NEW_LINE> <DEDENT> if not initial_pressures: <NEW_LINE> <INDENT> initial_pressu... | Initialize the plumbing engine.
The engine can either be initialized with an empty graph, or with the same parameters as
load_engine().
Parameters
----------
components: dict
components is a dict of {component_name: PlumbingComponent} where component_name
is a string that matches the name attribute of its co... | 625941c730dc7b76659019a3 |
def main(): <NEW_LINE> <INDENT> main_stack = [] <NEW_LINE> aux_stack = [] <NEW_LINE> in_gene = False <NEW_LINE> for element in sys.argv[2:]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> main_stack.append(int(element)) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> for char in element: <NEW_LINE> <INDENT> ma... | The main body of the interpreter | 625941c707f4c71912b114bd |
def test_parse_bad_orbit(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> parse_cassini_orbit('-1') <NEW_LINE> <DEDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> parse_cassini_orbit('1') <NEW_LINE> <DEDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> parse_cas... | CassiniOrbit parse: Bad orbit | 625941c7711fe17d825423a9 |
def reset(self): <NEW_LINE> <INDENT> for reader in self.__readers: <NEW_LINE> <INDENT> reader.reset() <NEW_LINE> <DEDENT> if self.__buffer is not None: <NEW_LINE> <INDENT> self.__buffer.clear() <NEW_LINE> <DEDENT> self.__length = 0 | Reset the readers and buffer. | 625941c77b180e01f3dc483b |
def _symbolic_control(self, st): <NEW_LINE> <INDENT> sbits = 0 <NEW_LINE> for bitidx in range(self.state.arch.bits): <NEW_LINE> <INDENT> if st[bitidx].symbolic: <NEW_LINE> <INDENT> sbits += 1 <NEW_LINE> <DEDENT> <DEDENT> return sbits | Determine the amount of symbolic bits in an AST, useful to determining how much control we have
over registers.
:param st: A claripy AST object to examine.
:return: Number of symbolic bits in the AST.
:rtype: int | 625941c7a79ad161976cc181 |
def nll_l2_msssim(x, recon_x_logits, merge_strategy=torch.mul): <NEW_LINE> <INDENT> batch_size = x.size(0) <NEW_LINE> l2_nll = torch.sum(F.mse_loss(input=x.view(batch_size, -1), target=recon_x_logits.view(batch_size, -1), reduction='none'), dim=-1) <NEW_LINE> l2_msssim = calculate_mssim(x, recon_x_logits, size_average=... | Negative log-likelihood for bernoulli distribution.
:param x: input tensor
:param recon_x_logits: reconstruction logits
:param merge_strategy: torch.mul, torch.add, etc
:returns: tensor of batch size for the NLL
:rtype: torch.Tensor | 625941c7cc40096d6159598c |
def choice_validator(optdict, name, value): <NEW_LINE> <INDENT> if not value in optdict['choices']: <NEW_LINE> <INDENT> msg = "option %s: invalid value: %r, should be in %s" <NEW_LINE> raise optparse.OptionValueError(msg % (name, value, optdict['choices'])) <NEW_LINE> <DEDENT> return value | validate and return a converted value for option of type 'choice'
| 625941c75fc7496912cc39b9 |
def test_images_have_owner(self): <NEW_LINE> <INDENT> self.assertEquals(self.image1.owner, self.test_user1) | Test to verify that images have owners. | 625941c7be8e80087fb20c80 |
def random_select_revealed_node(self, alpha, index1, index2): <NEW_LINE> <INDENT> same_nodes = set(self.graphs[index1].nodes()) & set(self.graphs[index2].nodes()) <NEW_LINE> s = int(alpha * len(same_nodes)) <NEW_LINE> logging.info("graph {}-{} random revealed nodes {}/{}.".format (index1, index2, s, len(same_nodes))) <... | select some nodes as revealed nodes randomly,
alpha is percent of all same nodes. | 625941c7167d2b6e31218bd1 |
def pack_string(obj): <NEW_LINE> <INDENT> payload = str(obj).encode('ASCII') <NEW_LINE> pl = len(payload) <NEW_LINE> if pl < (2**5): <NEW_LINE> <INDENT> prefix = struct.pack('B', 0b10100000 | pl) <NEW_LINE> <DEDENT> elif pl < (2**8): <NEW_LINE> <INDENT> prefix = struct.pack('BB', 0xD9, pl) <NEW_LINE> <DEDENT> elif pl <... | Optimally pack a string according to msgpack format | 625941c7187af65679ca515a |
def _destroy_evacuated_instances(self, context): <NEW_LINE> <INDENT> filters = { 'source_compute': self.host, 'status': ['accepted', 'done'], 'migration_type': 'evacuation', } <NEW_LINE> with utils.temporary_mutation(context, read_deleted='yes'): <NEW_LINE> <INDENT> evacuations = objects.MigrationList.get_by_filters(co... | Destroys evacuated instances.
While nova-compute was down, the instances running on it could be
evacuated to another host. This method looks for evacuation migration
records where this is the source host and which were either started
(accepted) or complete (done). From those migration records, local
instances reported... | 625941c7eab8aa0e5d26db93 |
def __repr__(self,*args): <NEW_LINE> <INDENT> pass | __repr__(x: UInt16) -> str | 625941c7ff9c53063f47c230 |
@login_required <NEW_LINE> def update_recurring_transaction(request, account_slug, recurring_transaction_id): <NEW_LINE> <INDENT> account = get_object_or_404(Account, slug=account_slug, owner=request.user) <NEW_LINE> recurring_transaction = get_object_or_404(RecurringTransaction, pk=recurring_transaction_id, account=ac... | Update a RecurringTransaction. | 625941c7dd821e528d63b1e5 |
def begin_create_or_update( self, resource_group_name, route_filter_name, route_filter_parameters, **kwargs ): <NEW_LINE> <INDENT> polling = kwargs.pop('polling', True) <NEW_LINE> cls = kwargs.pop('cls', None) <NEW_LINE> lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) <NEW_LINE> cont_token =... | Creates or updates a route filter in a specified resource group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param route_filter_name: The name of the route filter.
:type route_filter_name: str
:param route_filter_parameters: Parameters supplied to the create or update ro... | 625941c73d592f4c4ed1d0ac |
def get_texts_from_url(self, send_msg): <NEW_LINE> <INDENT> urls = set() <NEW_LINE> urls.add((self.url, 1)) <NEW_LINE> used_urls = set() <NEW_LINE> max_depth = 1 <NEW_LINE> if not os.path.exists(self.dst_texts): <NEW_LINE> <INDENT> with open(self.dst_texts, 'w') as texts: <NEW_LINE> <INDENT> while max_depth <= self.dep... | Получение текстов с сайтов
:param send_msg: Функция для отправления сообщений через бота | 625941c76e29344779a6264e |
def comment(self, s): <NEW_LINE> <INDENT> self.script += 'C;%s;\r\n' % s | Adds a comment to the worklist file. Comments are completely ignored at runtime | 625941c71f037a2d8b94623a |
def test_get_group_member(self): <NEW_LINE> <INDENT> rv = self.app.get("/groups/natsuki/guneap") <NEW_LINE> logger.info(rv.data) | I should be able to add a member to a group | 625941c72ae34c7f2600d16d |
@register.simple_tag <NEW_LINE> def auth_name(auth): <NEW_LINE> <INDENT> if auth in SOCIALS: <NEW_LINE> <INDENT> auth_data = SOCIALS[auth] <NEW_LINE> if 'fa_icon' in auth_data: <NEW_LINE> <INDENT> return mark_safe(FA_SOCIAL_TEPMPLATE.format(**auth_data)) <NEW_LINE> <DEDENT> if 'fl_icon' in auth_data: <NEW_LINE> <INDENT... | Creates HTML markup for social authentication method. | 625941c738b623060ff0ae29 |
def batch(self, filename: str) -> float: <NEW_LINE> <INDENT> self.trinity.clean() <NEW_LINE> start = timer() <NEW_LINE> with self.trinity.session() as session: <NEW_LINE> <INDENT> with open(filename, "r") as f: <NEW_LINE> <INDENT> stmts = "" <NEW_LINE> for index, line in enumerate(f): <NEW_LINE> <INDENT> stmts += line ... | Given a filename, iterate over it, collecting batch_size elements, execute
each batch and return the time the entire process took. | 625941c763f4b57ef0001158 |
def test_create_team(self): <NEW_LINE> <INDENT> self.instance.create_team('team-name', permission='push') <NEW_LINE> self.post_called_with( url_for('teams'), data={ 'name': 'team-name', 'repo_names': [], 'permission': 'push' } ) | Show that one can create a team in an organization. | 625941c74c3428357757c364 |
def __init__(self, cache=None, timeout=None, proxy_info=None, ca_certs=None, disable_ssl_certificate_validation=False): <NEW_LINE> <INDENT> self.proxy_info = proxy_info <NEW_LINE> self.ca_certs = ca_certs <NEW_LINE> self.disable_ssl_certificate_validation = disable_ssl_certificate_validation <NEW_LINE> s... | The value of proxy_info is a ProxyInfo instance.
If 'cache' is a string then it is used as a directory name
for a disk cache. Otherwise it must be an object that supports
the same interface as FileCache. | 625941c7e5267d203edcdcda |
def test_get_record_id(self): <NEW_LINE> <INDENT> ice_entry1 = ICEEntry(typ='PLASMID') <NEW_LINE> self.__ice_client.set_ice_entry(ice_entry1) <NEW_LINE> self.assertNotEqual(ice_entry1.get_record_id(), None) <NEW_LINE> ice_entry2 = ICEEntry(metadata={'type': 'PLASMID'}) <NEW_LINE> self.__ice_client.set_ice_entry(ice_ent... | Tests get_record_id method. | 625941c799fddb7c1c9de3cd |
def simulate_move(self, orig_dn): <NEW_LINE> <INDENT> if not self._base_object: <NEW_LINE> <INDENT> raise ObjectException(C.make_error('OBJECT_MOVE_NON_BASE_OBJECT')) <NEW_LINE> <DEDENT> obj = self <NEW_LINE> zope.event.notify(ObjectChanged("pre move", obj, dn=self.dn, orig_dn=orig_dn)) <NEW_LINE> self.update_dn_refs(s... | Simulate a moves for this object | 625941c76aa9bd52df036ddf |
def table_with_variants_on_diff_c_copies(self, select_columns: Optional[list]): <NEW_LINE> <INDENT> if len(self.region_attrs.with_variants_diff_c_copy) != 2: <NEW_LINE> <INDENT> raise ValueError('You must provide exactly two Mutation instances in order to use this method.') <NEW_LINE> <DEDENT> interm_select_column_name... | Returns a table of variants of the same type of the ones contained in RegionAttrs.with_variants_diff_c_copy and only
form the individuals that own both of them on opposite chromosome copies.
:param select_columns: the list of column names to select from the result. If None, all the columns are taken. | 625941c7b5575c28eb68e03b |
def calcAngSepDeg(RADeg1, decDeg1, RADeg2, decDeg2): <NEW_LINE> <INDENT> if not isinstance(RADeg1, float): <NEW_LINE> <INDENT> RADeg1 = hms2decimal(RADeg1, ':') <NEW_LINE> <DEDENT> if not isinstance(decDeg1, float): <NEW_LINE> <INDENT> decDeg1 = dms2decimal(decDeg1, ':') <NEW_LINE> <DEDENT> if not isinstance(RADeg2, fl... | Calculates the angular separation of two positions on the sky (specified
in decimal degrees) in decimal degrees, assuming a tangent plane projection
(so separation has to be <90 deg). Note that RADeg2, decDeg2 can be numpy
arrays.
@type RADeg1: float
@param RADeg1: R.A. in decimal degrees for position 1
@type decDeg1:... | 625941c732920d7e50b2820b |
def check(request): <NEW_LINE> <INDENT> context = { 'menu': MENU, 'title': 'Check a Site', 'page': 'check', } <NEW_LINE> return render(request, 'check.html', context) | Check view. | 625941c7cc40096d6159598d |
def load_patches(filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(filename, "rb") as f: <NEW_LINE> <INDENT> return pkl.load(f) <NEW_LINE> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <INDENT> return None | Args:
filename: where the pkl file should be located
Returns:
unpickled patches | 625941c715fb5d323cde0b4a |
def main(): <NEW_LINE> <INDENT> _solution = Solution() <NEW_LINE> inp = [] <NEW_LINE> for i in inp: <NEW_LINE> <INDENT> print(_solution.cloneGraph(i)) | main function | 625941c729b78933be1e56ea |
def setW(self, W): <NEW_LINE> <INDENT> PW = 0 <NEW_LINE> self.__W = round(W,1) <NEW_LINE> if self.__W < self.__WMin: <NEW_LINE> <INDENT> self.__W = self.__WMin <NEW_LINE> <DEDENT> if self.__W > self.__WMax: <NEW_LINE> <INDENT> self.__W = self.__WMax <NEW_LINE> <DEDENT> PW = int(1000 + (self.__W) * 10) <NEW_LINE> if sel... | Checks W% is between limits than sets it | 625941c7b57a9660fec338bf |
def run(self, steps=1000): <NEW_LINE> <INDENT> [ self.update(1) for step in xrange(steps) ] | Run the Environment for given number of time steps. | 625941c71b99ca400220aaed |
def PbEq(args, k, ctx = None): <NEW_LINE> <INDENT> ctx, sz, _args, _coeffs = _pb_args_coeffs(args) <NEW_LINE> return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx) | Create a Pseudo-Boolean inequality k constraint.
>>> a, b, c = Bools('a b c')
>>> f = PbEq(((a,1),(b,3),(c,2)), 3) | 625941c796565a6dacc8f708 |
def _choose_parser(app_name: str, ns: str) -> Optional[BaseConfigParser]: <NEW_LINE> <INDENT> parser: Optional[BaseConfigParser] = None <NEW_LINE> ns = os.environ.get('EDUID_CONFIG_NS', ns) <NEW_LINE> app_name = os.environ.get('EDUID_CONFIG_APP_NAME', app_name) <NEW_LINE> yaml_file = os.environ.get('EDUID_CONFIG_YAML')... | Choose a parser to use for this app.
Do local imports accordingly to not make etcd, yaml etc. mandatory requirements for
all users of eduid-common.
:param app_name: Name of the application
:param ns: Namespace for the application
:return: Config parser instance | 625941c78da39b475bd64fae |
def get_single_item(request, item_id): <NEW_LINE> <INDENT> return get_object_or_404(CartItem, id=item_id, cart_id=_cart_id(request)) | Получаем конкретный товар в корзине | 625941c77cff6e4e811179c2 |
def __writing_interval(self): <NEW_LINE> <INDENT> return abs(gauss(self.__creation_rate, self.__creation_rate / 4)) | Generate a time interval according to a gaussian distribution around the creation rate.
:return: interval in seconds between generating two messages | 625941c7b545ff76a8913e53 |
def is_command(self, command): <NEW_LINE> <INDENT> return command == self.get_base() | Simple boolean-returning method used during command
parsing. | 625941c7d99f1b3c44c675cc |
def GetKeywords(self): <NEW_LINE> <INDENT> return [BOO_KW] | Returns Specified Keywords List | 625941c7a219f33f346289a8 |
def __init__(self, name, system, repository): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._system = system <NEW_LINE> self._repository = repository <NEW_LINE> self._install_path = None <NEW_LINE> self._installed = False <NEW_LINE> self._dependencies = {} | Construct the package with a *name* and the *system* installation information.
:param string name: name of this package.
:param system: class that manages system commands
:type system: :class:`nusoft.system.System` instance
:param repository: local name of the repository the package is from | 625941c74e4d5625662d4415 |
def label_barh(ax, fmt="{}", spacing=5, align='left', is_inside=False, **kwargs): <NEW_LINE> <INDENT> for rect in ax.patches: <NEW_LINE> <INDENT> x_value = rect.get_width() <NEW_LINE> y_value = rect.get_y() + rect.get_height() / 2 <NEW_LINE> if callable(fmt): <NEW_LINE> <INDENT> label = fmt(x_value) <NEW_LINE> <DEDENT>... | Attach a text label to each horizontal bar displaying its y value.
fmt - Format string for labels or callable with receives a value and gives
it back formatted as a string.
spacing - Number of points between bar and label (default: 5).
align - Alignment for positive values. | 625941c7004d5f362079a370 |
def generate_default_question_label(): <NEW_LINE> <INDENT> question_nr = int(answer_id.split('_')[-2]) - 1 <NEW_LINE> return _("Question {}").format(question_nr) | To create question string like "Question 2" by adding "Question" and its position number.
For instance 'd2e35c1d294b4ba0b3b1048615605d2a_2_1' contains 2,
which is used in question number 1 (see example XML in comment above)
There's no question 0 (question IDs start at 1, answer IDs at 2) | 625941c70c0af96317bb8224 |
def get_detail_url(pk): <NEW_LINE> <INDENT> return reverse('core:user_detail', kwargs={'pk': pk}) | Returns detail url | 625941c7d58c6744b4257c9d |
def remove_parameter_group(self, parameter_group): <NEW_LINE> <INDENT> self._parameter_groups.remove(parameter_group) | Removes a parameter group from the template.
:type parameter_group: tuskar.templates.heat.ParameterGroup
:raise ValueError: if the parameter group is not in the template | 625941c791af0d3eaac9ba54 |
def __init__(self, title, x = -1 , y = -1, w = -1, h = -1 ): <NEW_LINE> <INDENT> Component.__init__(self,None,-1) <NEW_LINE> self.title = title <NEW_LINE> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.w = w <NEW_LINE> self.h = h | takes title for frame not on tab order | 625941c77b25080760e39496 |
def create_views_from_file(yaml_filepath, view_callback): <NEW_LINE> <INDENT> urlpatterns = [] <NEW_LINE> with open(yaml_filepath) as yaml_paths_file: <NEW_LINE> <INDENT> url_paths = yaml.load(yaml_paths_file.read()) <NEW_LINE> if url_paths: <NEW_LINE> <INDENT> for url_path, url_settings in url_paths.items(): <NEW_LINE... | Givan a YAML file mapping URL paths to values, e.g.:
path/one: {"some": "value"}
path/two: {"another": "value"}
Create a Django URL pattern from each value, so that when that path
is requested, view_callback is run, passing the mapped value.
Returns a list of Django urlpatterns. | 625941c7498bea3a759b9aec |
def Trim(t, p=0.01): <NEW_LINE> <INDENT> n = int(p * len(t)) <NEW_LINE> t = sorted(t)[n:-n] <NEW_LINE> return t | Trims the largest and smallest elements of t.
Args:
t: sequence of numbers
p: fraction of values to trim off each end
Returns:
sequence of values | 625941c766673b3332b920cd |
def percent(x, total): <NEW_LINE> <INDENT> return x * 100 / total | Metodo que efetua o calculo da porcentagem | 625941c7d18da76e23532512 |
def get_bitno_seed_rnd(bloom_filter, key): <NEW_LINE> <INDENT> hasher = random.Random(key).randrange <NEW_LINE> for dummy in range(bloom_filter.num_probes_k): <NEW_LINE> <INDENT> bitno = hasher(bloom_filter.num_bits_m) <NEW_LINE> yield bitno % bloom_filter.num_bits_m | Apply num_probes_k hash functions to key. Generate the array index and bitmask corresponding to each result | 625941c75fdd1c0f98dc026f |
def invitation_tickets_id_delete(self, id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.invitation_tickets_id_delete_with_http_info(id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.invitation_tickets... | Delete a model instance by {{id}} from the data source.
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.invit... | 625941c73617ad0b5ed67f35 |
def make_yaml_file(yaml_file, pipeline, project_name, workflow, analysis_steps, s3_input_files_address, sample_list, group_list, s3_output_files_address, genome, style, pairs_list): <NEW_LINE> <INDENT> filewriter = open(yaml_file, "w") <NEW_LINE> filewriter.write("project: " + project_name + "\n") <NEW_LINE> filewriter... | Writes user input to a yaml file.
The user information is taken from a pipeline's jupyter notebook. Yaml
file is later used in the PipelineManager execute function.
Args:
yaml_file: A string name of file being written to
pipeline: A string name of the pipeline being run
project_name: A string name of the ... | 625941c757b8e32f524834d7 |
def _historical_sys_profile_mapping(historical_sys_profile): <NEW_LINE> <INDENT> return { "id": historical_sys_profile["id"], "display_name": historical_sys_profile["display_name"], "updated": historical_sys_profile["captured_date"], "system_id": historical_sys_profile["inventory_id"], } | create a header mapping for one historical profile
note that we use "captured_date" for the "updated" field, to retain API
compatability. Users are typically interested in the captured_date here and
not the internal updated timestamp. | 625941c7cdde0d52a9e5306f |
def removeNthFromEnd(self, head, n): <NEW_LINE> <INDENT> start = head <NEW_LINE> org = head <NEW_LINE> for i in range(1, n): <NEW_LINE> <INDENT> start = start.next <NEW_LINE> i = i + 1 <NEW_LINE> <DEDENT> while start.next != None: <NEW_LINE> <INDENT> start = start.next <NEW_LINE> org = org.next <NEW_LINE> <DEDENT> head... | :type head: ListNode
:type n: int
:rtype: ListNode | 625941c70a366e3fb873e856 |
def check_call(args): <NEW_LINE> <INDENT> _logger.info("%s", subprocess.list2cmdline(args)) <NEW_LINE> subprocess.check_call(args) | Log the command then call subprocess.check_call() | 625941c72ae34c7f2600d16e |
def check_permissions(self, request): <NEW_LINE> <INDENT> if self.permissions_required: <NEW_LINE> <INDENT> return request.user.has_perms(self.permissions_required) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return request.user.has_perm( '{}.change_{}'.format(self.model._meta.app_label, self.model._meta.model_name)) | Return true is user has permission to view page | 625941c744b2445a339320d3 |
@release.command() <NEW_LINE> @click.argument('version') <NEW_LINE> def bump(version): <NEW_LINE> <INDENT> bump_version(version) | Bump the version number.
| 625941c7ec188e330fd5a7de |
def hook(self, *args): <NEW_LINE> <INDENT> self.args = args | This method actually implements the hook.
| 625941c74527f215b584c495 |
def do_chgnumval(self, args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> arglist = self._get_int_args(args) <NEW_LINE> if len(arglist) == 2: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> vtClient.ChangeNumericValue(*arglist) <NEW_LINE> <DEDENT> except isobus.IBSException as e: <NEW_LINE> <INDENT> print('Error: {reason... | Send a change numeric value command: chgnumval OBJID VALUE | 625941c70383005118ecf620 |
def contains_bbox(self, bb2): <NEW_LINE> <INDENT> return (bb2.x1 >= self.x1 and bb2.x2 <= self.x2 and bb2.y1 >= self.y1 and bb2.y2 <= self.y2) | Checks if this BBox fully contains another BBox
:param b: (BBox)
:returns (bool) | 625941c78e7ae83300e4b009 |
def generate_table(expression): <NEW_LINE> <INDENT> variables = get_unique_variables(expression) <NEW_LINE> steps = get_expression_steps(expression) | Takes a valid expression and generates a 2d collection that represents
the truth table
param1(list of strings): the validated expression
return: 2d list of the truth table. First row is the header, and
subsequent rows are the table rows. | 625941c7462c4b4f79d1d70d |
def dec2hex(datadec): <NEW_LINE> <INDENT> if data_dec < 16: <NEW_LINE> <INDENT> prefix = "000" <NEW_LINE> <DEDENT> elif datadec > 15 & datadec < 256: <NEW_LINE> <INDENT> prefix = "00" <NEW_LINE> <DEDENT> elif datadec > 255 & datadec < 4096: <NEW_LINE> <INDENT> prefix = "0" <NEW_LINE> <DEDENT> elif datadec > 4095 & data... | Convert decimal data into two hexadecimal bytes. | 625941c7596a897236089aff |
def test_create_user(self): <NEW_LINE> <INDENT> call_command('create_user', email=self.email, username=self.username, password=self.password) <NEW_LINE> user = User.objects.get(username=self.username) <NEW_LINE> self.assertEquals(user.email, 'talib@kweli.com') | Test that the `create_user` custom manage.py command creates a
user with the specified email, username, and password. | 625941c79c8ee82313fbb7b1 |
def cross_down(self, *args): <NEW_LINE> <INDENT> another = Indicators(self.market_event) <NEW_LINE> another.data_dict['arg'].append(self) <NEW_LINE> another.data_dict['func'] = 'cross_down' <NEW_LINE> another.data_dict['arg'] += [*args] <NEW_LINE> return another | Indicators.cross_down(类, *args) | 625941c7851cf427c661a54d |
def AllRegister(*args): <NEW_LINE> <INDENT> return _gdal.AllRegister(*args) | AllRegister() | 625941c7377c676e912721e6 |
def test_pizza(): <NEW_LINE> <INDENT> window1 = rg.RoseWindow(800, 800, 'testing pizza') <NEW_LINE> circle1 = rg.Circle(rg.Point(400, 400), 300) <NEW_LINE> pizza(window1, circle1, 5, 'blue') | Tests the pizza function. | 625941c7656771135c3eb8aa |
@click.group(context_settings={'help_option_names': ['-h', '--help']}) <NEW_LINE> def cli(): <NEW_LINE> <INDENT> pass | Working with Cython actors and functions in Ray | 625941c756b00c62f0f14696 |
def __exit__(self, *exc): <NEW_LINE> <INDENT> self.close() | Exit a runtime context for the connection. | 625941c766656f66f7cbc1e7 |
def test_anonymous(self): <NEW_LINE> <INDENT> backend = CachedModelAuthBackend() <NEW_LINE> mock_user = Mock() <NEW_LINE> mock_user.is_anonymous.return_value = True <NEW_LINE> result = backend.get_all_permissions(mock_user) <NEW_LINE> self.assertEqual(result, set()) <NEW_LINE> self.assertFalse(self.mockcache.get.called... | Test for an anonymous user object | 625941c74d74a7450ccd4201 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.