code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def __new__(cls, *args, **kwargs): <NEW_LINE> <INDENT> pass | # to allow initialization from a single int | 625941dc5510c4643540f6da |
def init(self, parent): <NEW_LINE> <INDENT> self.control = panel = TraitsUIPanel(parent, -1) <NEW_LINE> sizer = wx.BoxSizer(wx.VERTICAL) <NEW_LINE> sizer2 = wx.BoxSizer(wx.HORIZONTAL) <NEW_LINE> facenames = self.factory.all_facenames() <NEW_LINE> control = self._facename = wx.Choice(panel, -1, wx.Point(0, 0), wx.Size(-... | Finishes initializing the editor by creating the underlying toolkit
widget. | 625941dcbde94217f36830eb |
def get_base_data_directory(self): <NEW_LINE> <INDENT> user = os.getenv("USER").strip().lower() <NEW_LINE> return os.path.join(self.base_directory, user, self.start_time) | Returns the base data directory taking the 'contextual'
information into account, such as if the current user
is inhouse.
:returns: The base data path.
:rtype: str | 625941dc4527f215b584c751 |
def get_spatial_window_corner_coords(aois, d): <NEW_LINE> <INDENT> tops = [x[0][0] for x in aois] <NEW_LINE> bottoms = [x[0][1] for x in aois] <NEW_LINE> lefts = [x[1][0] for x in aois] <NEW_LINE> rights = [x[1][1] for x in aois] <NEW_LINE> tls = [(t, l) for t, l in zip(tops, lefts)] <NEW_LINE> trs = [(t, r) for t, r i... | Summary
Args:
aois (TYPE): Description
d (TYPE): Description
Returns:
TYPE: Description | 625941dc91af0d3eaac9bd18 |
def find_view(self, view_name): <NEW_LINE> <INDENT> data = self._controller.get_api_data() <NEW_LINE> raw_views = data['views'] <NEW_LINE> for cur_view in raw_views: <NEW_LINE> <INDENT> if cur_view['name'] == view_name: <NEW_LINE> <INDENT> turl = cur_view['url'] <NEW_LINE> if turl.find('view') == -1: <NEW_LINE> <INDENT... | Searches views directly managed by this Jenkins instance for a specific view
.. seealso: :py:meth:`.get_view`
:param str view_name: the name of the view to search for
:returns:
If a view with the specified name can be found, an object to manage the view will be returned,
otherwise None
:rtype: :class:`~.view.... | 625941dc23e79379d52ee85d |
def __init__(self): <NEW_LINE> <INDENT> self.__cancellable = Gio.Cancellable() <NEW_LINE> self.connect("next-changed", self.__on_next_changed) | Init player | 625941dc91f36d47f21ac7f2 |
def printLinkList (pLinks): <NEW_LINE> <INDENT> for m in pLinks: <NEW_LINE> <INDENT> print (m.URL) | ' Print the list of links just for testing | 625941dc4428ac0f6e5baaf1 |
def transform(output_dir, compresslevel=0): <NEW_LINE> <INDENT> aliquots_emitter = JSONEmitter(os.path.join(output_dir, 'aliquots.json'), compresslevel=0) <NEW_LINE> for line in reader('source/bcc/assays.tsv'): <NEW_LINE> <INDENT> aliquot = {'type': 'aliquot', '*samples': {'submitter_id': line['ID_Specimen']}} <NEW_LIN... | Read bcc tsv and writes gen3 json. | 625941dc26068e7796caefdf |
def ParseColumnStream(stream, num_column=None, delimiter=None): <NEW_LINE> <INDENT> if num_column is None: <NEW_LINE> <INDENT> for line in stream: <NEW_LINE> <INDENT> yield line.rstrip('\n').split(delimiter) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for line in stream: <NEW_LINE> <INDENT> yield line.rstrip... | Returns parsed columns read from stream. | 625941dcd4950a0f3b08c648 |
@betimer <NEW_LINE> def load_mtpr(): <NEW_LINE> <INDENT> global mtpr <NEW_LINE> global ratio <NEW_LINE> with open("./symbol_info.csv") as f: <NEW_LINE> <INDENT> for line in f.readlines(): <NEW_LINE> <INDENT> lst=line.strip().split(',') <NEW_LINE> mtpr[lst[0].upper()]=float(lst[4]) <NEW_LINE> ratio[lst[0].upper()]=float... | @note:提取品种合约乘数与保证金 | 625941dc7047854f462a1703 |
def get_data_loaders(args, bert_tokenizer, tokenizer): <NEW_LINE> <INDENT> logger.info("Build inputs and labels") <NEW_LINE> datasets = {"train": defaultdict(list), "valid": defaultdict(list)} <NEW_LINE> sourceList_train, targetList_train, attentionList_train, sourceList_valid, targetList_valid, attentionList_valid = g... | Prepare the dataset for training and evaluation | 625941dc004d5f362079a62f |
def test_pwscf_lattice_vectors_alat(): <NEW_LINE> <INDENT> parser_tise2 = PWSCFParser(Path(__file__).parent / "data" / "pwscf_tise2.out") <NEW_LINE> a1, a2, a3 = parser_tise2.lattice_vectors_alat() <NEW_LINE> assert np.allclose(a1, np.array([0.989_891, -0.001_560, -0.001_990])) <NEW_LINE> assert np.allclose(a2, np.arra... | Test the parsing of lattice vectors in alat units | 625941dcf9cc0f698b1408f6 |
def send_message(self, message, user_id, agent_id): <NEW_LINE> <INDENT> corpid, corpsecret, agent_id, token_dict = self.env['ding.ding'].get_ding_common_message(agent_id) <NEW_LINE> ding_obj = Dingtalk(corpid, corpsecret, agent_id, token_dict) <NEW_LINE> dinguser_row = self.search([('ding_user_id', '=', user_id)]) <NEW... | 发送消息必须指定agent_id | 625941dcd6c5a1020814434a |
def parallelize_array_computation(func, *arrays, n_jobs=-1, **kwargs): <NEW_LINE> <INDENT> if n_jobs == -1: <NEW_LINE> <INDENT> n_jobs = cpu_count() <NEW_LINE> <DEDENT> if n_jobs == 1: <NEW_LINE> <INDENT> return [func(*arrays)] <NEW_LINE> <DEDENT> n_elements = list(set(len(a) for a in arrays)) <NEW_LINE> if len(n_eleme... | Chunk arrays into n_jobs blocks and compute func using a multiprocessing.Pool | 625941dc046cf37aa974d042 |
def _assign_person_traits(self, person, traits): <NEW_LINE> <INDENT> for trait, ou_id, roleid in traits: <NEW_LINE> <INDENT> person.populate_trait(trait, target_id=ou_id, strval=roleid) <NEW_LINE> self.logger.info("Person id=%s acquires trait %s " "target_id=%s strval=%s", person.entity_id, self.constants.EntityTrait(t... | Assign HR-data originated traits to a person.
HR source data contains some information which we want to mirror in
Cerebrum as traits. The traits pertinent to each person are collected
elsewhere and passed to this method for registering in Cerebrum.
@type person: an instance of Factory.get('Person')
@param person:
A... | 625941dc046cf37aa974d043 |
def decode_byte(known, num_bytes, prefix_size, needed_extra): <NEW_LINE> <INDENT> prefix = craft_block(len(known), num_bytes + needed_extra) <NEW_LINE> original = encryption_oracle(prefix) <NEW_LINE> length = prefix_size + len(prefix) + len(known) + 1 <NEW_LINE> for i in range(256): <NEW_LINE> <INDENT> ct = encrypt... | Decodes the next byte of the unknown string.
Args:
known: Bytestring containing the bytes from unknown-string that we
know so far.
num_bytes: The length of the ciphertext
prefix_size: The length of the secret prefix
needed_extra: The length of bytes we still need | 625941dc57b8e32f5248379a |
def add(cur): <NEW_LINE> <INDENT> source = prompts.ask_allowlist() <NEW_LINE> utils.warn_long_running() <NEW_LINE> import_list = [] <NEW_LINE> if source in whiteLists: <NEW_LINE> <INDENT> url_source = whiteLists[source] <NEW_LINE> resp = requests.get(url_source["url"]) <NEW_LINE> import_list = utils.process_lines(resp.... | prompt for and process allowlists | 625941dccb5e8a47e48b7da3 |
def _is_osx_107(): <NEW_LINE> <INDENT> if sys.platform != 'darwin': <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> version = platform.mac_ver()[0] <NEW_LINE> return tuple(map(int, version.split('.')))[0:2] == (10, 7) | :return:
A bool if the current machine is running OS X 10.7 | 625941dc3317a56b86939f4f |
def make_game(level): <NEW_LINE> <INDENT> maze_ascii = MAZES_ART[level] <NEW_LINE> for row in range(1, 5): <NEW_LINE> <INDENT> if 'a' in maze_ascii[row]: <NEW_LINE> <INDENT> maze_ascii[row] = maze_ascii[row].replace('a', ' ', 1) <NEW_LINE> <DEDENT> <DEDENT> new_coord = random.sample(ROOMS[2], 1)[0] <NEW_LINE> maze_asci... | Builds and returns a Better Scrolly Maze game for the selected level. | 625941dcf7d966606f6aa305 |
def measure_function(client, extra_tags=None): <NEW_LINE> <INDENT> def decorator(fn): <NEW_LINE> <INDENT> _statsd = client <NEW_LINE> _extra_tags = extra_tags or {} <NEW_LINE> @functools.wraps(fn) <NEW_LINE> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> extra_tags = {"def": fn.__name__} <NEW_LINE> extra_tags.update... | Decorator to measure a function
This places a timer around the entire function and passes in a StatsdFactory instance as the function's `statsd` kwarg
Args:
client (StatsClient): statsd client instance
extra_tags (dict): optional extra tags to add to metrics | 625941dcfff4ab517eb2f73b |
def create_message(payload: dict, msg_type: str) -> str: <NEW_LINE> <INDENT> if msg_type in cs.MESSAGE_TYPES: <NEW_LINE> <INDENT> container = {} <NEW_LINE> container['data'] = payload <NEW_LINE> container['type'] = msg_type <NEW_LINE> container['checksum'] = '' <NEW_LINE> message = json.dumps(container, sort_keys=True)... | Wrap the passed payload into a pyodine-flavoured JSON-String.
| 625941dca219f33f34628c63 |
def writeToPipe (text) : <NEW_LINE> <INDENT> sys.stdout.write(text) <NEW_LINE> sys.stdout.flush() | ͏ ͏ ͏͏ ͏ ͏ ͏ ͏͏ ͏ ͏ ͏͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏͏ ͏ ͏͏͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏ ͏
Writes to the stdout channel ͏ ͏ ͏ ... | 625941dcb5575c28eb68e300 |
def to_rhasspy_dict(self) -> typing.Dict[str, typing.Any]: <NEW_LINE> <INDENT> return { "intent": { "name": self.intent.intent_name, "confidence": self.intent.confidence_score, }, "entities": [ { "entity": s.slot_name, "value": s.value.get("value"), "value_details": s.value, "raw_value": s.raw_value, "start": s.start, ... | Convert to Rhasspy format. | 625941dcab23a570cc250482 |
def pre_order(self): <NEW_LINE> <INDENT> pass | root, left, right | 625941dc7c178a314d6ef761 |
def fit_goodness(ym, yp): <NEW_LINE> <INDENT> ym_bar = np.mean(ym) <NEW_LINE> SSR = sum((yp - ym_bar) ** 2) <NEW_LINE> SST = sum((ym - ym_bar) ** 2) <NEW_LINE> SSE = SST - SSR <NEW_LINE> rsq = SSR / SST <NEW_LINE> return rsq, SSE, SST, SSR | Calculate the goodness of fit.
Parameters
----------
ym : ndarray, shape(n,)
The vector of measured values.
yp : ndarry, shape(n,)
The vector of predicted values.
Returns
-------
rsq : float
The r squared value of the fit.
SSE : float
The error sum of squares.
SST : float
The total sum of squares.... | 625941dc3539df3088e2e648 |
def template_width(self): <NEW_LINE> <INDENT> return 150 | Defines the maximum usable template width in millimeters.
Override this method in a child renderer to provide proper measurements
for the content area of your template. | 625941dc0a50d4780f667192 |
def remove_movie(self, title: str = None, place: int = None) -> bool: <NEW_LINE> <INDENT> if title and self.top250_db.select_by_title(title=title): <NEW_LINE> <INDENT> self.top250_db.delete_movie(title=title) <NEW_LINE> self.LOG.info(f'{title} has been removed from db') <NEW_LINE> <DEDENT> elif place and self.top250_db... | Remove movies from database.
:param title: str, example: 'Joker'
:param place: int, example: 126
:return: True | 625941dc50485f2cf553d098 |
def squared_difference(x, y, name=None): <NEW_LINE> <INDENT> result = _op_def_lib.apply_op("SquaredDifference", x=x, y=y, name=name) <NEW_LINE> return result | Returns (x - y)(x - y) element-wise.
Args:
x: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`.
y: A `Tensor`. Must have the same type as `x`.
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `x`. | 625941dc236d856c2ad44adb |
def replacement(match): <NEW_LINE> <INDENT> code = match.group(1) <NEW_LINE> try: <NEW_LINE> <INDENT> return str(eval(code, scope)) <NEW_LINE> <DEDENT> except SyntaxError: <NEW_LINE> <INDENT> return '' | 用于调用re.sub
:param match:
:return: | 625941dc26238365f5f0f16f |
def solve(self, system): <NEW_LINE> <INDENT> reduced = self.reduce(system) <NEW_LINE> return self.substitute(reduced) | This function puts the matrix into reduced form
and then uses back substituion to get the final value | 625941dc5166f23b2e1a5456 |
def add_routes(config): <NEW_LINE> <INDENT> config.add_route('index', '/') <NEW_LINE> config.add_route('io', '/io/{slowness}') <NEW_LINE> config.add_route('cpu', '/cpu') <NEW_LINE> config.add_route('cpu_offload', '/cpu_offload') <NEW_LINE> config.add_route('mixed', '/mixed/{slowness}') | Add in routes to our views | 625941dcd164cc617578304c |
def get_property_value(self, node, context): <NEW_LINE> <INDENT> uri_attrs = { "a": "href", "audio": "src", "area": "href", "embed": "src", "iframe": "src", "img": "src", "link": "href", "object": "data", "source": "src", "track": "src", "video": "src", } <NEW_LINE> lang = get_lang_from_hierarchy(self.document, node) <... | Generate an RDF object, ie, the value of a property. Note that if this element contains
an @itemscope, then a recursive call to L{MicrodataConversion.generate_triples} is done and the
return value of that method (ie, the subject for the corresponding item) is return as an
object.
Otherwise, either URIRefs are created ... | 625941dc92d797404e304489 |
def open_dictionary_file(file: str) -> dict: <NEW_LINE> <INDENT> assert os.path.isfile(file), "The file does not exist!" <NEW_LINE> dictionary = dict() <NEW_LINE> with open(file, 'r') as json_file: <NEW_LINE> <INDENT> dictionary = json.load(json_file) <NEW_LINE> <DEDENT> if 'result.json' in file: <NEW_LINE> <INDENT> as... | The following function inputs a file name & loads it into a dictionary
that is returned. | 625941dcfb3f5b602dac3994 |
def HideObject(object_id): <NEW_LINE> <INDENT> return HideObjects(object_id)==1 | Hides a single object
Parameters:
object_id: String or Guid representing id of object to hide
Returns:
True of False indicating success or failure | 625941dc29b78933be1e59a5 |
def apply(self, f, codomain=None, to_moments=False): <NEW_LINE> <INDENT> D = {} <NEW_LINE> sd = self._dict <NEW_LINE> if codomain is None: <NEW_LINE> <INDENT> codomain = self._codomain <NEW_LINE> <DEDENT> for ky, val in sd.iteritems(): <NEW_LINE> <INDENT> if to_moments: <NEW_LINE> <INDENT> D[ky] = codomain([f(val.momen... | Returns Manin map given by `x |--> f(self(x))`, where `f` is
anything that can be called with elements of the coefficient
module.
This might be used to normalize, reduce modulo a prime, change
base ring, etc. | 625941dc442bda511e8be712 |
@pytest.mark.parametrize( "test_input,expected", [ ("p(HGNC:HRAS, pmod(Ac))", []), ("p(HGNC:HRAS, pmod(Ac, S, 473))", []), ("p(HGNC:HRAS, pmod(Ac, Ser, 473))", []), ], ) <NEW_LINE> def test_validate_pmod_function(test_input, expected): <NEW_LINE> <INDENT> assertion = AssertionStr(entire=test_input) <NEW_LINE> ast = bel... | Accept Single or three letter Amino Acid code | 625941dca4f1c619b28b0330 |
def GetPointer(self): <NEW_LINE> <INDENT> return _itkSpatialObjectToImageFilterPython.itkSpatialObjectToImageFilterSO2IUC2_GetPointer(self) | GetPointer(self) -> itkSpatialObjectToImageFilterSO2IUC2 | 625941dc711fe17d82542663 |
def page9(self): <NEW_LINE> <INDENT> self.token_modules = 'jquery.autoEllipsis,checkboxShiftClick,highlightText,makeCollapsible,mw-jump,placeholder,suggestions|mediawiki.api,searchSuggest,user|mediawiki.page.ready' <NEW_LINE> self.token_version = '20130422T023354Z' <NEW_LINE> result = request901.GET('/load.ph... | GET load.php (request 901). | 625941dc377c676e912724a5 |
def getFront(self) -> int: <NEW_LINE> <INDENT> return -1 if self.q[self.front] is None else self.q[self.front] | Get the front item from the deque. | 625941dc82261d6c526ab7a1 |
def bitfield(self, peer, message_bytes): <NEW_LINE> <INDENT> bitstring = ''.join('{0:08b}'.format(byte) for byte in message_bytes) <NEW_LINE> peer.has_pieces = [bool(int(c)) for c in bitstring] <NEW_LINE> self.torrent_downloader.pieces_changed_callback(peer) | formats each byte into binary and updates peer.has_pieces list
appropriately. | 625941dc44b2445a33932392 |
def _publish_topic(self, topic_id, topic_name): <NEW_LINE> <INDENT> topic = topic_domain.Topic.create_default_topic( topic_id, topic_name, 'abbrev', 'description') <NEW_LINE> topic.thumbnail_filename = 'thumbnail.svg' <NEW_LINE> topic.thumbnail_bg_color = '#C6DCDA' <NEW_LINE> topic.subtopics = [ topic_domain.Subtopic( ... | Creates and publishes a topic.
Args:
topic_id: str. Topic ID.
topic_name: str. Topic name. | 625941dc1f5feb6acb0c4e4a |
def __init__(self, argument): <NEW_LINE> <INDENT> super().__init__(argument) <NEW_LINE> self._namespace = "http://www.knora.org/ontology/publishing" <NEW_LINE> self._name = "hasMonoAuthorPublicationValue" | :param argument: | 625941dc30dc7b7665901c61 |
def __init__(self): <NEW_LINE> <INDENT> self.model = Category() | Class initialization. | 625941dc379a373c97cfae44 |
def get_access_token(self, by_session: TDomainId) -> str: <NEW_LINE> <INDENT> raise NotImplementedError() | Allows to extract an access token from the specified Session
WARNING: Must NOT to be directly exposed to the API
:param by_session: an identifier of Session which contains
a needed access token
:return: an access token associated with the specified Session | 625941dc21a7993f00bc7ff2 |
def get_final_solution(self, additive=False): <NEW_LINE> <INDENT> pass | Evaluates the final solution | 625941dc0fa83653e46572b7 |
def test_digit_in_account_can_be_blank(self): <NEW_LINE> <INDENT> field = Account._meta.get_field('digit') <NEW_LINE> self.assertTrue(field.blank) | Test if column 'digit' of model `Account` can be blank. Ex: Account not in bank | 625941dc656771135c3ebb70 |
def sell(self, asset, latest_price): <NEW_LINE> <INDENT> current_cash = self.balance <NEW_LINE> quantity_to_sell = self.holdings[asset] <NEW_LINE> proceeds_of_sale = quantity_to_sell * latest_price <NEW_LINE> if quantity_to_sell <= 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.holdings[asset] = self.holdings[a... | Backtest assumes max quantity of assets sold. It also assumes that
orders are filled at the price given. | 625941dc5510c4643540f6db |
def getACECount(aclBytes): <NEW_LINE> <INDENT> return struct.unpack("<H",aclBytes[4:6])[0] | Returns the number of ACEs present in the given ACL | 625941dcac7a0e7691ed43c5 |
def test_operation_error_several(self): <NEW_LINE> <INDENT> self.qc.add('MakeDir', '12', {'path': '/a'}) <NEW_LINE> self.assertEqual(len(self.qc._node_ops), 1) <NEW_LINE> node = self.qc._node_ops[''].children['a'] <NEW_LINE> node.operations = node.operations * 2 <NEW_LINE> r = self.qc.remove('MakeDir', '12', {'path': '... | Finish an operation that is more than once. | 625941dc4d74a7450ccd44c2 |
def jeux(request, page=1): <NEW_LINE> <INDENT> all_games = Game.objects.order_by('-nb_rented') <NEW_LINE> query = request.GET.get("q") <NEW_LINE> if query: <NEW_LINE> <INDENT> all_games = all_games.filter(name__icontains=query) <NEW_LINE> <DEDENT> paginator = Paginator(all_games, 5) <NEW_LINE> try: <NEW_LINE> <INDENT> ... | Liste de tous les jeux | 625941dc462c4b4f79d1d9ce |
def build_archive_download_response(codebase_release, review_archive=False): <NEW_LINE> <INDENT> fs_api = codebase_release.get_fs_api() <NEW_LINE> response = HttpResponse() <NEW_LINE> response["Content-Type"] = "" <NEW_LINE> response["Content-Disposition"] = "attachment; filename={}".format( codebase_release.archive_fi... | Returns an HttpResponse object that uses nginx to serve our codebase archive zipfiles.
(https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/)
:param codebase_release: The specific CodebaseRelease instance archive to download
:param review_archive: when true we force a rebuild of the CodebaseRelease archi... | 625941dc30c21e258bdfa79d |
def raz(self): <NEW_LINE> <INDENT> self.l = 1 <NEW_LINE> self.paintEvent(2) <NEW_LINE> self.ui.conteneur.update() | Réinitialise la variable l pour suprimer, dans le conteneur, l'affichage de placement et des déplacements possibles
Paramètres
----------
Return
------ | 625941dc5fcc89381b1e19c0 |
def statement_list(tokens): <NEW_LINE> <INDENT> node = Node(None, "<statement_list>") <NEW_LINE> child, tokens_lst = statement(tokens) <NEW_LINE> node.append(child) <NEW_LINE> if tokens_lst is None: <NEW_LINE> <INDENT> return (Node(None, "<empty>"), tokens) <NEW_LINE> <DEDENT> child, tokens_lst = statement_list(tokens_... | bang bang | 625941dc15baa723493c4275 |
@mock.patch("robophisher.common.firewall.helper.run_command") <NEW_LINE> def test_redirect_to_localhost_no_error(run_command): <NEW_LINE> <INDENT> run_command.return_value = (True, None) <NEW_LINE> assert firewall.redirect_to_localhost() == (True, None) | Test redirect_to_localhost which results in no error | 625941dc090684286d50efe6 |
def do_send(self, args): <NEW_LINE> <INDENT> message = args <NEW_LINE> msg = str(self.__nickname) + '(' + str(self.__id) + ')' + '[' + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())+']'+'\n' <NEW_LINE> self.txt_msglist.insert(tkinter.END,msg,'green') <NEW_LINE> self.txt_msglist.insert(tkinter.END,message) <NEW_LIN... | 发送消息
:param args: 参数 | 625941dc925a0f43d254a177 |
def _log_entry( self, newsletter ): <NEW_LINE> <INDENT> log = MailerLog( plugin=self.plugin, name=self.name, subject=newsletter.subject, newsletter_pk=newsletter.pk, parameters='; '.join([unicode( p ) for p in MailerParameter.objects.filter( mailer=self )]), ) <NEW_LINE> return log | Create a log entry for sending a mail | 625941dc32920d7e50b284d0 |
def keep_alive(self, debug=False): <NEW_LINE> <INDENT> assert self.started <NEW_LINE> if self.shuttingdown or self.joined: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.pipe.poll(0.01): <NEW_LINE> <INDENT> cmd = self.pipe.recv() <NEW_LINE> if PP_QUIT in cmd: <NEW_LINE> <INDENT> self.shuttingdown = True <... | Send a keep-alive message to the Process and listen for a Quit command | 625941dc293b9510aa2c3591 |
def encrypt(str, key): <NEW_LINE> <INDENT> alphabet=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] <NEW_LINE> encrypted = '' <NEW_LINE> str = str.lower() <NEW_LINE> for char in str: <NEW_LINE> <INDENT> if char == " " : <NEW_LINE> <INDEN... | Input:
text to be encrypted
key of the caesar cypher
Output: Encrypted text | 625941dc3317a56b86939f50 |
def euler_integrate(self, renorm=0, change_dt=1): <NEW_LINE> <INDENT> self.y += self.dt*self.eom(self.y, 0) <NEW_LINE> if change_dt: <NEW_LINE> <INDENT> self.t += self.dt <NEW_LINE> <DEDENT> if renorm: <NEW_LINE> <INDENT> self.y /= np.sqrt(norm(self.y)) | This integration uses the 1st order forward Euler method to update the
function based on the equation of motion. | 625941dcf9cc0f698b1408f7 |
@superuser_required <NEW_LINE> def sync_ding_user(request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> add_sync_ding_user_schedule() <NEW_LINE> return JsonResponse({"status": 0, "msg": f"触发同步成功"}) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return JsonResponse({"status": 1, "msg": f"触发同步异常:{e}"}) | 主动触发同步接口,同时写入schedule每天进行同步 | 625941dc097d151d1a223156 |
def className(self): <NEW_LINE> <INDENT> return _DataModel.Arrival_className(self) | className(Arrival self) -> char const * | 625941dc07f4c71912b11782 |
def get_func(mod_name, func_name): <NEW_LINE> <INDENT> mod = get_module(mod_name) <NEW_LINE> logger.debug("mod: %s" % mod) <NEW_LINE> logger.debug("func_name: %s" % func_name) <NEW_LINE> try: <NEW_LINE> <INDENT> return getattr(mod, func_name) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> logger.error('... | Import function and return. | 625941dccdde0d52a9e53334 |
def bulk_update(model, values, key_fields='id', using=None, set_functions=None, key_fields_ops=(), where=None, returning=None, batch_size=None, batch_delay=0): <NEW_LINE> <INDENT> if not inspect.isclass(model): <NEW_LINE> <INDENT> raise TypeError("model must be django.db.models.Model subclass") <NEW_LINE> <DEDENT> if n... | Updates multiple records of a given model, finding them by key_fields.
:param model: Model to update, a subclass of django.db.models.Model
:param values: Data to update. All items must update same fields!!!
It can come in 2 forms:
+ Iterable of dicts. Each dict is update or create data. Each dict must contain ... | 625941dc8c0ade5d55d3ecbb |
def is_task_number_flagged(self): <NEW_LINE> <INDENT> element = self.driver.find_element(*TaskFormLoc.ERROR_TASK_NUMBER) <NEW_LINE> assert('Task Number is required' in element.text), 'Task number error missing' | Check task number field for an error | 625941dc287bf620b61d3d60 |
def _scheduler(): <NEW_LINE> <INDENT> now = time.time() <NEW_LINE> while asioTasks and now >= asioTasks[0].timeout: <NEW_LINE> <INDENT> caller = heapq.heappop(asioTasks) <NEW_LINE> if caller.cancelled: <NEW_LINE> <INDENT> asioCancelledNum -= 1 <NEW_LINE> continue <NEW_LINE> <DEDENT> if caller.repush: <NEW_LINE> <INDENT... | Run the schedule function due to expire soon. | 625941dc2ae34c7f2600d42f |
def set_artifact_classification_exceptions(self, image_tag: str, exceptions) -> Response: <NEW_LINE> <INDENT> if not isinstance(image_tag, str): <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> if not image_tag: <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> updates = {'classification.exceptions': exce... | Add the code exceptions to an existing artifact's classification metadata.
:param image_tag: The image tag identifying the artifact to update.
:param exceptions: The standard code exceptions for the artifact.
:return: The response object. | 625941dc8c3a8732951586bc |
def train(model, train_loader, epochs, optimizer, loss_fn, device): <NEW_LINE> <INDENT> for epoch in range(1, epochs + 1): <NEW_LINE> <INDENT> model.train() <NEW_LINE> total_loss = 0 <NEW_LINE> for batch in train_loader: <NEW_LINE> <INDENT> batch_X, batch_y = batch <NEW_LINE> batch_X = batch_X.to(device) <NEW_LINE> bat... | This is the training method that is called by the PyTorch training script. The parameters
passed are as follows:
model - The PyTorch model that we wish to train.
train_loader - The PyTorch DataLoader that should be used during training.
epochs - The total number of epochs to train for.
optimizer - The o... | 625941dcc432627299f04f46 |
def test_arith_expr_left_shift_first_space(): <NEW_LINE> <INDENT> group([ ('NAME', 'a'), ('SPACE', ' '), ('LEFT_SHIFT', '<<'), ('NAME', 'b'), ], [ ('NAME', 'a'), ('LEFT_SHIFT', '<<', [('SPACE', ' ')]), ('NAME', 'b'), ]) | a <<b | 625941dc31939e2706e4d164 |
def send_alarm_msg(key): <NEW_LINE> <INDENT> print('\n启动定时自动提醒...') <NEW_LINE> conf = config.get('alarm_info').get('alarm_dict') <NEW_LINE> gf = conf.get(key) <NEW_LINE> is_tomorrow = gf.get('is_tomorrow', False) <NEW_LINE> calendar_info = get_calendar_info(gf.get('calendar'), is_tomorrow) <NEW_LINE> weather = get_weat... | 发送定时提醒 | 625941dc442bda511e8be713 |
def append(self, experience: Tuple) -> None: <NEW_LINE> <INDENT> self.memory.append(experience) <NEW_LINE> while len(self.memory) > self.maximum_capacity: <NEW_LINE> <INDENT> self.memory.pop() | Handle the memory greater than maximum_capacity case.
:param experience: A 4-tuple containing
(state_t, action_t, reward_t, state_{t+1}) for some t. | 625941dc004d5f362079a630 |
def validate_library_no(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> int(value) <NEW_LINE> return value <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise serializers.ValidationError("Invalid Library Number.") | Check if library_no is valid (must be int) | 625941dc796e427e537b08c6 |
def SetAllowOverscaling(self, allowOverscaling): <NEW_LINE> <INDENT> self.allowOverscaling = allowOverscaling | Set whether the image should be overscaled if the panel's size is
bigger than the picture's size.
:param `allowOverscaling`: Set whether the picture should be overscaled.
:type `allowOverscaling`: bool | 625941dc8c0ade5d55d3ecbc |
def init_app(app): <NEW_LINE> <INDENT> def _teardown(_e): <NEW_LINE> <INDENT> _store_user_cache(_SLACK_USER_CACHE) <NEW_LINE> <DEDENT> app.teardown_appcontext(_teardown) | Initialize the specified slack app with this modules teardown routine.
Save the current state of the user cache dictionary to the storage file
on app teardown. | 625941dca17c0f6771cbe34e |
def get_permutation(n, k): <NEW_LINE> <INDENT> k -= 1 <NEW_LINE> l = [(i + 1) for i in range(n)] <NEW_LINE> result = [] <NEW_LINE> while k >= 0: <NEW_LINE> <INDENT> if k == 0: <NEW_LINE> <INDENT> result += l <NEW_LINE> break <NEW_LINE> <DEDENT> base = f(len(l) - 1) <NEW_LINE> y = base <NEW_LINE> for i in range(len(l)):... | :param n:
:param k:
:return: | 625941dc23849d37ff7b338c |
def _listmetadataformats(app, query): <NEW_LINE> <INDENT> with app.test_request_context(): <NEW_LINE> <INDENT> with app.test_client() as c: <NEW_LINE> <INDENT> result = c.get(query) <NEW_LINE> <DEDENT> tree = etree.fromstring(result.data) <NEW_LINE> assert len(tree.xpath('/x:OAI-PMH', namespaces=NAMESPACES)) == 1 <NEW_... | Try ListMetadataFormats. | 625941dc76e4537e8c351973 |
def AdNauseum(self,x,y,gameboard, Color, intervals): <NEW_LINE> <INDENT> answers = [] <NEW_LINE> for xint,yint in intervals: <NEW_LINE> <INDENT> xtemp,ytemp = x+xint,y+yint <NEW_LINE> while self.noConflict(gameboard, Color, xtemp, ytemp): <NEW_LINE> <INDENT> target = gameboard.get((xtemp,ytemp),None) <NEW_LINE> if targ... | Repeats the given interval until another piece is run into.
if that piece is not of the same color, that square is added and
then the list is returned | 625941dcbf627c535bc134ce |
def update(self): <NEW_LINE> <INDENT> self.rect.centery += self.dy | This method is called automatically to move the flea straight down
the screen. | 625941dc1f037a2d8b9464fc |
def copyfile(src, dest, newmtime = None, sstat = None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not sstat: <NEW_LINE> <INDENT> sstat = os.lstat(src) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.warn("copyfile: stat of %s failed (%s)" % (src, e)) <NEW_LINE> return False <NEW_LIN... | Copies a file from src to dest, preserving all permissions and
attributes; mtime will be preserved even when moving across
filesystems. Returns true on success and false on failure. | 625941dc287bf620b61d3d61 |
def shuffle(*args, **kwargs): <NEW_LINE> <INDENT> logging.debug(f"Using the default Randy the Ram (ie. {__the_ram!r})") <NEW_LINE> return __the_ram.shuffle(*args, **kwargs) | Call shuffle with the default random generator. | 625941dc63f4b57ef0001410 |
def symplecticity_condition(a, tree1, tree2): <NEW_LINE> <INDENT> return a(tree1.butcher_product(tree2)) + a(tree2.butcher_product(tree1)) == a(tree1) * a(tree2) | Symmetric function in ``tree1``, ``tree2``. | 625941dc31939e2706e4d165 |
def y_tableau(self): <NEW_LINE> <INDENT> Y = [[0 for i in range(self._max_x)] for j in range(self._max_z)] <NEW_LINE> for C in self.cells(): <NEW_LINE> <INDENT> Y[C[2]][C[0]] += 1 <NEW_LINE> <DEDENT> return Y | Return the projection of ``self`` in the `y` direction.
EXAMPLES::
sage: PP = PlanePartition([[4,3,3,1],[2,1,1],[1,1]])
sage: PP.y_tableau()
[[4, 3, 2], [3, 1, 0], [3, 0, 0], [1, 0, 0]] | 625941dcbe8e80087fb20f3e |
def LstmFastFwEncoder(input_, params, prefix='encoder', mask=None, dropout_param=None): <NEW_LINE> <INDENT> n_layer = C['m_encoder_layer'] <NEW_LINE> use_zigzag = C['use_zigzag'] <NEW_LINE> assert n_layer >= 1, '#layer must >= 1' <NEW_LINE> _lstm_step_func = _lstm_step_slice_with_theta if C['use_theta'] else _lstm_step... | LSTM Fast-Forward Encoder.
input_: source word embedding | 625941dc460517430c39447d |
def process_toi(source_info, options, debug): <NEW_LINE> <INDENT> tags = source_info.get('tags') <NEW_LINE> name = source_info.get('name') <NEW_LINE> category = "" <NEW_LINE> html = "" <NEW_LINE> if options.rss_local: <NEW_LINE> <INDENT> html_source = options.rss_local + "/" + name + ".html" <NEW_LINE> <DEDENT> else: <... | we fetch the source and then use regex to extract the URLs and IDs we want
:param source_info: Information about the furl source (RSS feed in this case)
:param options: Any options passed in
:param debug: If true, print additional debugging info
:return: A list of items extracted from the html, that can be further pro... | 625941dc8e71fb1e9831daa7 |
def make_config(db_name): <NEW_LINE> <INDENT> for db in settings.DATABASES.values(): <NEW_LINE> <INDENT> if db.get('NAME') == db_name: <NEW_LINE> <INDENT> raise RuntimeError( f'pgclone cannot use temporary database named "{db_name}"' ' since it is already configured in settings.DATABASES.' ) <NEW_LINE> <DEDENT> <DEDENT... | Returns a DB config dict for the database named "db_name"
Also ensures that no other database are configured with the provided
database name. This is a sanity check to make sure that no dynamic
databases used by pgclone collide with any that already exist. | 625941dc50812a4eaa59c61e |
def createSampleBuildings(): <NEW_LINE> <INDENT> pass | Create sample buildings for testing purposes | 625941dce76e3b2f99f3ab06 |
def redis_query(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> res = self.redis_cli.llen(name) <NEW_LINE> return res <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return | 查询指定任务列表中数据
:param name:
:return: | 625941dc2ae34c7f2600d430 |
def inspect_inputs(i, node, fn): <NEW_LINE> <INDENT> print(i, node, "IN:", [inp[0] for inp in fn.inputs],) | Inspecting Theano function graph in MonitorMode: print inputs. | 625941dc7047854f462a1705 |
def recurseValidateAndVOnUpSert(m): <NEW_LINE> <INDENT> docData = m.validDocData() <NEW_LINE> doc = docData <NEW_LINE> doc_errors = [] <NEW_LINE> attrPath = [] <NEW_LINE> recurseDoc(docData, m._cls, docData, recurseValidate, attrPath, doc_errors) <NEW_LINE> if doc_errors: <NEW_LINE> <INDENT> return doc_errors <NEW_LINE... | recursively handle validate and execute any doc.vOnUpSert functions | 625941dca79ad161976cc444 |
def encode_full_header(auth): <NEW_LINE> <INDENT> return encode_header({'configs': auth}) | Returns the given auth block encoded for the X-Registry-Config header.
| 625941dc283ffb24f3c55bfd |
def print_cycles_info(data): <NEW_LINE> <INDENT> n_cycles = len(data.cycles) <NEW_LINE> output('number of cycles:', n_cycles) <NEW_LINE> if not n_cycles: <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> slengths = sorted(set(data.cycles_lengths)) <NEW_LINE> lhist, lbins = np.histogram(data.cycles_lengths, bins=sleng... | Print various information about cycles. | 625941dc091ae35668667258 |
def __init__(self, maxsize=0): <NEW_LINE> <INDENT> self._maxsize = maxsize <NEW_LINE> self._unfinished_tasks = 0 <NEW_LINE> self._heap = [] <NEW_LINE> self._size = 0 <NEW_LINE> self._counter = 0 <NEW_LINE> self._lock = threading.Lock() <NEW_LINE> self._notempty = Condition(self._lock) <NEW_LINE> self._notfull = Conditi... | The *maxsize* argument specifies the maximum queue size. If it is less
than or equal to zero, the queue size is infinite. | 625941dc67a9b606de4a81b6 |
def create_canvas(self, frame, row, col): <NEW_LINE> <INDENT> self.canvas = tk.Canvas(frame, width=300, height=100, bg='white') <NEW_LINE> self.canvas.grid(row=row, column=col) | Create, configure and grid result canvas. | 625941dcd53ae8145f87a56a |
def train(self, env, num_episodes=1000, batch_size=50, discount_factor=0.9, checkpoint_freq=None, exploration_range=(1.0, 0.1), exploration_phase_size=0.5): <NEW_LINE> <INDENT> max_exploration_rate, min_exploration_rate = exploration_range <NEW_LINE> exploration_decay = ((max_exploration_rate - min_exploration_rate) / ... | Train the agent to perform well in the given Snake environment.
Args:
env:
an instance of Snake environment.
num_episodes (int):
the number of episodes to run during the training.
batch_size (int):
the size of the learning sample for experience replay.
discount_factor (float):
... | 625941dc3617ad0b5ed681f5 |
def initiate_info() -> Info: <NEW_LINE> <INDENT> return { "ucb_num_terminal_sims": 0, "mcts_num_action_nodes": 0, "ucb_tree_depth": MovingStatistic(), "q_statistic": MovingStatistic(), "iteration": 0, } | Simple initiation of info object, populating expected values
Returns a dictionary with starter values for:
- ucb_num_terminal_sims
- mcts_num_action_nodes
- ucb_tree_depth
- q_statistic
- iteration | 625941dc796e427e537b08c7 |
def __init__( self, l2_norm_clip, noise_multiplier, num_microbatches=None, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self._l2_norm_clip = l2_norm_clip <NEW_LINE> self._noise_multiplier = noise_multiplier <NEW_LINE> self._num_microbatches = num_microbatches <NEW_LINE> self._dp_su... | Initialize the DPOptimizerClass.
Args:
l2_norm_clip: Clipping norm (max L2 norm of per microbatch gradients).
noise_multiplier: Ratio of the standard deviation to the clipping norm.
num_microbatches: Number of microbatches into which each minibatch is
split.
*args: These will be passed on to the base class... | 625941dc046cf37aa974d045 |
def send_error(self, error): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> error_message = json.dumps({ KEY_SITE_ID: self.site_id, KEY_VARIABLE_ID: KEY_ERROR, KEY_VALUE: error, KEY_DATE: timezone.now().isoformat(), KEY_DST_TIMEZONE: tzname[1], KEY_NON_DST_TIMEZONE: tzname[0] }) <NEW_LINE> SIGNAL_TIMESERIES.send(sender=s... | Send signal error to error_receiver
| 625941dc66656f66f7cbc4ab |
def isIsomorphic(self, s, t): <NEW_LINE> <INDENT> sl = len(s) <NEW_LINE> tl = len(t) <NEW_LINE> if sl != tl: return False <NEW_LINE> maps = {} <NEW_LINE> mapp = {} <NEW_LINE> for i in range(sl): <NEW_LINE> <INDENT> if s[i] not in maps: <NEW_LINE> <INDENT> if t[i] not in mapp: <NEW_LINE> <INDENT> maps[s[i]] = t[i] <NEW_... | :type s: str
:type t: str
:rtype: bool | 625941dc9c8ee82313fbba75 |
def test_180_certificate_certlist_search(self): <NEW_LINE> <INDENT> self.certificate.dbstore.certificates_search.side_effect = Exception('exc_certlist_search') <NEW_LINE> with self.assertLogs('test_a2c', level='INFO') as lcm: <NEW_LINE> <INDENT> self.certificate.certlist_search('type', 'value') <NEW_LINE> <DEDENT> self... | test Certificate.certlist_search - dbstore.certificates_search() raises an exception | 625941dca79ad161976cc445 |
def ExtractConfig(self): <NEW_LINE> <INDENT> logging.info("Extracting config file from .pkg.") <NEW_LINE> pkg_path = os.environ.get("PACKAGE_PATH", None) <NEW_LINE> if pkg_path is None: <NEW_LINE> <INDENT> logging.error("Could not locate package, giving up.") <NEW_LINE> return <NEW_LINE> <DEDENT> zf = zipfile.ZipFile(p... | This installer extracts a config file from the .pkg file. | 625941dc3c8af77a43ae3aa2 |
def hdf5_dataset_formatter(self, *args, **kwargs): <NEW_LINE> <INDENT> samplerate = self.AnalysedAudioFile.samplerate <NEW_LINE> skewness = self.create_skewness_analysis(*args, **kwargs) <NEW_LINE> skewness_times = self.calc_skewness_frame_times(skewness, args[0], samplerate) <NEW_LINE> return ({'frames': skewness, 'ti... | Formats the output from the analysis method to save to the HDF5 file. | 625941dcb5575c28eb68e302 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.