code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def run(self) -> None: <NEW_LINE> <INDENT> self.tcex.log.trace('run') | Run the App main logic. | 625941c91f5feb6acb0c4bdd |
def _retrieve_schema_from_server(self, url, conn): <NEW_LINE> <INDENT> assert conn is not None <NEW_LINE> self.log.debug( 'retrieving schema for SchemaCache url=%s conn=%s', url, conn) <NEW_LINE> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> schema_entry = conn.search_s('cn=schema', ldap.SCOPE_BASE, attrlist=['attr... | Retrieve the LDAP schema from the provided url and determine if
User-Private Groups (upg) are configured.
Bind using kerberos credentials. If in the context of the
in-tree "lite" server then use the current ccache. If in the context of
Apache then create a new ccache and bind using the Apache HTTP service
principal.
... | 625941c9442bda511e8be4a5 |
@screener.route('/patient_details/<id>', methods=['POST', 'GET']) <NEW_LINE> @login_required <NEW_LINE> def patient_details(id): <NEW_LINE> <INDENT> check_patient_permission(id) <NEW_LINE> patient = Patient.query.get(id) <NEW_LINE> form = ( get_unsaved_form(request, patient, 'patient_details', PatientForm) or PatientFo... | Display the full patient details form for an existing user. | 625941c93c8af77a43ae382c |
def test_test_config(self): <NEW_LINE> <INDENT> app = create_app('local_knowledge.settings.TestConfig') <NEW_LINE> assert app.config['DEBUG'] is True <NEW_LINE> assert app.config['SQLALCHEMY_ECHO'] is True <NEW_LINE> assert app.config['CACHE_TYPE'] == 'null' | Tests if the test config loads correctly | 625941c97c178a314d6ef4eb |
def test_create_activity_participant_using_post(self): <NEW_LINE> <INDENT> pass | Test case for create_activity_participant_using_post
createActivityParticipant | 625941c956ac1b37e626425d |
def _one_iteration( self, input_vecs, targets, rate ): <NEW_LINE> <INDENT> samples = zip( input_vecs, targets ) <NEW_LINE> for ( input_vec, target ) in samples: <NEW_LINE> <INDENT> output = self.predict( input_vec ) <NEW_LINE> self._update_weights( input_vec, output, target, rate ) <NEW_LINE> lst_weight.append(self.wei... | 一次迭代,把所有的训练数据过一遍 | 625941c9be7bc26dc91cd68d |
def add_observer(self, observer): <NEW_LINE> <INDENT> self.observers.append(observer) | Add an observer that will be given the wavefunction after each call of evolve | 625941c982261d6c526ab52a |
def __init__(self, context_manager): <NEW_LINE> <INDENT> self._context_manager = context_manager | Initializes the search index context. | 625941c90a366e3fb873e8a6 |
def report(person_id, cause, explanation=''): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> url = config.host + '/report/%s' % person_id <NEW_LINE> r = requests.post(url, headers=headers, data={ "cause": cause, "text": explanation}) <NEW_LINE> return r.json() <NEW_LINE> <DEDENT> except requests.exceptions.RequestExcepti... | There are three options for cause:
0 : Other and requires an explanation
1 : Feels like spam and no explanation
4 : Inappropriate Photos and no explanation | 625941c9187af65679ca51ab |
def get_data_field(field, result): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if (isinstance(field, basestring)): <NEW_LINE> <INDENT> field_value = result.get(field) <NEW_LINE> <DEDENT> elif (isinstance(field, list)): <NEW_LINE> <INDENT> field_value = result.get(field[0]) <NEW_LINE> for i in range(1, len(field)): <NE... | Given a field name in ThreatExchange, grabs the resulting field value
from the ThreatExchange object.
:param field: name of ThreatExchange field
:type field: list, str
:param result: The resulting object received from ThreatExchange
:type result: ThreatExchange object
:returns: str, int | 625941c95fdd1c0f98dc02bf |
@contextmanager <NEW_LINE> def add_filter_set(name): <NEW_LINE> <INDENT> factory = FilterSetFactory(name) <NEW_LINE> yield factory <NEW_LINE> filter_sets[name] = factory.build_filter_set() | Builds and registers a global :class:`FilterSet`.
Args:
name (str): The name of the set.
Yields:
FilterSetFactory: A configurable factory for building a :class:`FilterSet`. | 625941c9d268445f265b4efa |
def test_suboptions_assignable(): <NEW_LINE> <INDENT> d = {'option1': 5, 'section1': {'option2': True, 'section3': {}}} <NEW_LINE> c = Config(d) <NEW_LINE> c.section1.option2 = 7 <NEW_LINE> assert c.section1.option2 == 7 | options in sections or subsections can be assigned to | 625941c9507cdc57c6306d66 |
def Parser(folder): <NEW_LINE> <INDENT> directorio = os.getcwd() <NEW_LINE> try: <NEW_LINE> <INDENT> if os.path.isfile("parserfile.fasta") == True: <NEW_LINE> <INDENT> os.remove("parserfile.fasta") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> output_handle = open("parserfile.fasta", "a") <NEW_... | Function to check the genbank format and
create a multifasta | 625941c9236d856c2ad44866 |
def getting__camera__info(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> time.sleep(8) <NEW_LINE> camIDList=list(self.find_elements("CameraId List")) <NEW_LINE> camNameList=list(self.find_elements("CameraName List")) <NEW_LINE> camStatusList = list(self.find_elements("CameraStatus List")) <NEW_LINE> for index,cNam... | getting desired camera information::- id, name & status
:return: desired info of camera | 625941c91b99ca400220ab3e |
@cli.group() <NEW_LINE> def environment(): <NEW_LINE> <INDENT> _check_credentials() | Manipulate Faculty server environments. | 625941c9a8ecb033257d315a |
def remove_options_entry(self, widget): <NEW_LINE> <INDENT> self.options_dict.pop(widget) | Removes the options entry associated with the provided `widget`, no
longer tracking its values. | 625941c9cc40096d615959dd |
def detail(request, pk): <NEW_LINE> <INDENT> posible_photo = photo.objects.filter(pk=pk) <NEW_LINE> photo0 = posible_photo[0] if len(posible_photo) == 1 else None <NEW_LINE> if photo0 is not None: <NEW_LINE> <INDENT> context = { 'photo' : photo0 } <NEW_LINE> return render(request,'photos/detail.html',context) <NEW_LINE... | Carga la pagina de detalle de una foto
:param request: HTTPRequuest
:param pk: id photo
:return httpresponse | 625941c924f1403a92600bf3 |
def update_rippeddiscs(*keys: str, db: str = DATABASE, **kwargs: Any) -> int: <NEW_LINE> <INDENT> changes: int = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> changes = _update_disc("rippeddiscs", *keys, db=db, **kwargs) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> return changes | :param keys:
:param db:
:param kwargs:
:return: | 625941c9091ae35668666fec |
def set_line_alpha(self, *args, **kwargs): <NEW_LINE> <INDENT> return _qtgui_swig.time_raster_sink_f_sptr_set_line_alpha(self, *args, **kwargs) | set_line_alpha(time_raster_sink_f_sptr self, int which, double alpha) | 625941c95166f23b2e1a51e6 |
def get_list(self): <NEW_LINE> <INDENT> f_result = [] <NEW_LINE> for f_effect in self.effects: <NEW_LINE> <INDENT> f_result.append(f_effect.get_class()) <NEW_LINE> <DEDENT> return f_result | return a list of pydaw_audio_item_fx instances | 625941c915fb5d323cde0b9b |
def cossim(inA, inB): <NEW_LINE> <INDENT> num = float(inA.T * inB) <NEW_LINE> denom = la.norm(inA) * la.norm(inB) <NEW_LINE> return 0.5 + 0.5 * (num / denom) | 计算相似度.
:param inA:
:param inB:
:return:相似度 | 625941c915baa723493c4001 |
def share(token,fileid): <NEW_LINE> <INDENT> global a <NEW_LINE> x=a.post("http://fangcloud.zju.edu.cn/apps/files/share", """{"access":"public","disable_download":"0","due_time":"never_expire","password_protected":false,"item_typed_id":"%s"}"""%fileid, headers={"requesttoken":token}) <NEW_LINE> result=x.json() <NEW_LIN... | 分享一个文件,fileid来自upload,返回文件分享链接file_unique_name
可以反复执行,返回相同的分享链接 | 625941c96fb2d068a760f129 |
def typeInfo(self, type_: typing.Type['Module']) -> typing.Dict[str, typing.Any]: <NEW_LINE> <INDENT> return {} | Returns info about the type
In fact, right now, it returns an empty dict, that will be extended by typeAsDict | 625941c95e10d32532c5efb3 |
def get_nm(self): <NEW_LINE> <INDENT> return self.__net_info['NM'] | Get Netmask (IP class type) | 625941c9bf627c535bc1325b |
def range_input_producer(limit, num_epochs=None, shuffle=True, seed=None, capacity=32, shared_name=None, name=None): <NEW_LINE> <INDENT> with ops.op_scope([limit], name, "input_producer") as name: <NEW_LINE> <INDENT> range_tensor = math_ops.range(limit) <NEW_LINE> return _input_producer( range_tensor, dtypes.int32, num... | Produces the integers from 0 to limit-1 in a queue.
Args:
limit: An int32 scalar tensor.
num_epochs: An integer (optional). If specified, `range_input_producer`
produces each integer `num_epochs` times before generating an
OutOfRange error. If not specified, `range_input_producer` can cycle
through the... | 625941c97047854f462a1497 |
def preprocess_cell(self, cell, resources, cell_index): <NEW_LINE> <INDENT> unique_key = resources.get('unique_key', 'output') <NEW_LINE> output_files_dir = resources.get('output_files_dir', None) <NEW_LINE> if not isinstance(resources['outputs'], dict): <NEW_LINE> <INDENT> resources['outputs'] = {} <NEW_LINE> <DEDENT>... | Apply a transformation on each cell,
Parameters
----------
cell : NotebookNode cell
Notebook cell being processed
resources : dictionary
Additional resources used in the conversion process. Allows
preprocessors to pass variables into the Jinja engine.
cell_index : int
Index of the cell being processed... | 625941c94f6381625f114ac8 |
def parse_string_equations(eqns, namespace, exhaustive, level): <NEW_LINE> <INDENT> equations = {} <NEW_LINE> try: <NEW_LINE> <INDENT> parsed = EQUATIONS.parseString(eqns, parseAll=True) <NEW_LINE> <DEDENT> except ParseException as p_exc: <NEW_LINE> <INDENT> raise SyntaxError('Parsing failed: \n' + str(p_exc.line) + '\... | Parse a string defining equations.
Parameters
----------
eqns : str
The (possibly multi-line) string defining the equations. See the
documentation of the Equations class for details.
namespace : dict
An explictly given namespace (dictionary mapping names to objects)
exhaustive : bool
Whether the namesp... | 625941c90c0af96317bb8275 |
def test_set_x(self): <NEW_LINE> <INDENT> mock = MagicMock(return_value='us') <NEW_LINE> with patch.dict(keyboard.__salt__, {'cmd.run': mock}): <NEW_LINE> <INDENT> self.assertEqual(keyboard.set_x('us'), 'us') | Test if it set current X keyboard setting | 625941c92eb69b55b151c93b |
@pytest.mark.parametrize('delimiter_format_type', ['CUSTOM']) <NEW_LINE> @pytest.mark.parametrize('data_format', ['DELIMITED']) <NEW_LINE> @pytest.mark.parametrize('quote_character', ['\t', ';' , ' ']) <NEW_LINE> @pytest.mark.parametrize('delimiter_character', ['^']) <NEW_LINE> def test_directory_origin_configuration_q... | Verify if directory origin can read delimited data with custom quote character.
This TC check for different escape characters. Input data fields have delimiter characters.
Directory origin should read this data and produce field without escape character.
e.g. ;|Field is value of field with "|" as delimiter character an... | 625941c923e79379d52ee5f1 |
def testGenerateVersionCodesAndroidTrichrome(self): <NEW_LINE> <INDENT> output = GenerateVersionCodes( self.EXAMPLE_VERSION_VALUES, arch='arm', is_next_build=False) <NEW_LINE> trichrome_version_code = output['TRICHROME_VERSION_CODE'] <NEW_LINE> self.assertEqual(trichrome_version_code, '372000030') | Assert it gives correct values for standard/example inputs | 625941c973bcbd0ca4b2c103 |
def test_filter_by_update_time(live_c8y: CumulocityApi, sample_device, sample_events: List[Event]): <NEW_LINE> <INDENT> event = sample_events[0] <NEW_LINE> updated_datetimes = [a.updated_datetime for a in sample_events] <NEW_LINE> updated_datetimes.sort() <NEW_LINE> pivot = updated_datetimes[len(updated_datetimes)//2] ... | Verify that filtering by lastUpdatedTime works as expected. | 625941c93cc13d1c6d3c7407 |
def missingancestors(self, revs): <NEW_LINE> <INDENT> revsvisit = set(revs) <NEW_LINE> basesvisit = self.bases <NEW_LINE> pfunc = self.pfunc <NEW_LINE> bothvisit = revsvisit.intersection(basesvisit) <NEW_LINE> revsvisit.difference_update(bothvisit) <NEW_LINE> if not revsvisit: <NEW_LINE> <INDENT> return [] <NEW_LINE> <... | return all the ancestors of revs that are not ancestors of self.bases
This may include elements from revs.
Equivalent to the revset (::revs - ::self.bases). Revs are returned in
revision number order, which is a topological order. | 625941c930bbd722463cbe52 |
def setup(client): <NEW_LINE> <INDENT> global discord_cli <NEW_LINE> discord_cli = client <NEW_LINE> client.add_cog(_ChatCommands(client)) | Runs on cog load, sets up the bot object and adds the cog to the bot.
:param client: Bot object. | 625941c93317a56b86939ce7 |
def open_url(url, **kargs): <NEW_LINE> <INDENT> data = None <NEW_LINE> log = logging.getLogger("utils_http:open_url") <NEW_LINE> handlers = [urllib2.HTTPCookieProcessor(cookielib.CookieJar()), urllib2.HTTPHandler(), urllib2.HTTPSHandler(), utils_log.HTTPDebugProcessor(log), HTTPErrorProcessor() ] <NEW_LINE> if kargs.ha... | open an url and return an handler on it.
arguments can be :
headers : http headers to send
headers = {"Accept": "text/plain",
"User-Agent": "a user agent"
}
proxy : the proxy to use when connecting to the url
proxy = { "url": "http://aproxy.server",
... | 625941c9287bf620b61d3af1 |
def cleanup(self): <NEW_LINE> <INDENT> pass | Do whatever cleanup after the test was ran.
This can be used, for example, to clean resources that were uploaded
to a distant server during setup().
Its eventual return value is ignored.
If it raises, the test will be aborted.
This implementation does nothing. | 625941c92c8b7c6e89b3584e |
def predict(self, sentence: str): <NEW_LINE> <INDENT> s = Sentence(sentence) <NEW_LINE> self.tagger.predict(s) <NEW_LINE> for token in s.tokens: <NEW_LINE> <INDENT> tag = token.get_tag("ner").value <NEW_LINE> word = token.text <NEW_LINE> yield word.strip(), tag if tag != "word" else "_" | Predict labels for a given sentence.
| 625941c99f2886367277a91a |
def transfer_file(self, compress_with=None): <NEW_LINE> <INDENT> filename = self.document['filename'] <NEW_LINE> config = Config() <NEW_LINE> upload_url = config.get('distribute', 'upload_url') <NEW_LINE> user = config.get('distribute', 'username') <NEW_LINE> pw = config.get('distribute', 'password') <NEW_LINE> payload... | Initiate transfer via HTTPS
:param compress_with: if document isn't already compressed and
this is set, compress the file before transfering. | 625941c963f4b57ef00011a8 |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> _simuPOP_baop.InfoExec_swiginit(self, _simuPOP_baop.new_InfoExec(*args, **kwargs)) | Usage:
InfoExec(stmts="", usePopVars=False, exposeInd="", output="",
begin=0, end=-1, step=1, at=[], reps=ALL_AVAIL,
subPops=ALL_AVAIL, infoFields=[])
Details:
Create an operator that executes Python statements stmts using
individual information fields and population variables as
variable... | 625941c9be8e80087fb20cd0 |
def __init__(self, ai_settings, screen, msg): <NEW_LINE> <INDENT> self.screen = screen <NEW_LINE> self.screen_rect = screen.get_rect() <NEW_LINE> self.width, self.height = 200, 50 <NEW_LINE> self.button_color = (165, 42, 42) <NEW_LINE> self.text_color = (255, 255, 255) <NEW_LINE> self.font = pygame.font.SysFont(None, 4... | Initialize button attributes. | 625941c9656771135c3eb8fb |
def set_default_shareds(self, shares=None): <NEW_LINE> <INDENT> if shares is not None: <NEW_LINE> <INDENT> sql = ("INSERT INTO assets_shared (user_from, user_to, group_to, asset_id, editable) " "VALUES ") <NEW_LINE> sharelist = [] <NEW_LINE> for share in shares: <NEW_LINE> <INDENT> sharelist.append("({}, {}, {}, {}, {!... | Asocia el asset a los usarios compartidos por default.
:type shares: dict
:param shares: Lista con los datos del las comparticiones default (default None) | 625941c9462c4b4f79d1d75d |
@Transform_Wrapper(shared_docs = doc_matching_rules) <NEW_LINE> def Adjust_Ship_Missile_Storage( *match_rule_multipliers ): <NEW_LINE> <INDENT> def Node_Update(ship_macro, multiplier): <NEW_LINE> <INDENT> storage = ship_macro.find('./properties/storage') <NEW_LINE> if storage != None and storage.get('missile'): <NEW_LI... | Adjusts the missile storage of ships.
* match_rule_multipliers:
- Series of matching rules paired with the multipliers to use. | 625941c9d58c6744b4257ced |
def test_agenda_get_all_agenda_items_returns_ascending_order(self): <NEW_LINE> <INDENT> response = self.client.get('/api/agendaItems/', {'all': ''}) <NEW_LINE> response.render() <NEW_LINE> self.assertEqual(response.content, self.expectations['all_agenda_items']) | Ensures that when we GET agendaItems?all, they're in ascending order by date, and past agendaItems are included. | 625941c99c8ee82313fbb802 |
@transform(PicardMarkDuplicate, suffix(".dedup.bam"), ['.rnaSeqc', ".alignQcSucess.txt"]) <NEW_LINE> def RNAseQC(inputFile, outFiles): <NEW_LINE> <INDENT> tasks.rnaSeQC(inputFile[0], outFiles) | Check alignments before proceeding with downstream analysis with RNAseQC | 625941c901c39578d7e74ec8 |
def __init__(self, data, maintain_original): <NEW_LINE> <INDENT> if maintain_original: <NEW_LINE> <INDENT> self._data = copy.deepcopy(data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._data = None <NEW_LINE> <DEDENT> self.data = data <NEW_LINE> self.value = self.__class__.EVENT | @param data: any payload that needs to be used by the event
handlers.
@param maintain_original: when set to true, create and attempt
to prevent modification of the original data passed in during
event creation. | 625941c9d99f1b3c44c6761c |
def send_data(self): <NEW_LINE> <INDENT> self.controller.process_msg(COMMIT_PRJ_MSG) | Notify controller that we need to send data to db and let it
do the work | 625941c9baa26c4b54cb11ad |
def execute(self): <NEW_LINE> <INDENT> return self.cmd("Convert %s" % self.__target, "%s %s %s", self.__imagemagick.convert(), self.__source.path(), self.__target.path()) | Run convert. | 625941c97d847024c06be348 |
def test_common_architecture_filtering(self): <NEW_LINE> <INDENT> release_file_architectures = "arm64 armel armhf i386 mips mips64el mipsel amd64" <NEW_LINE> self.assertEqual( _filter_split_architectures(release_file_architectures, "amd64", "stable"), ["amd64"], ) <NEW_LINE> self.assertEqual( _filter_split_architecture... | Represents the common case where a remote asks to filter for one or two architectures. | 625941c93346ee7daa2b2df8 |
def maxProfit(self, prices): <NEW_LINE> <INDENT> min_so_far = sys.maxsize <NEW_LINE> max_profit = 0 <NEW_LINE> for i in prices: <NEW_LINE> <INDENT> max_profit = max(max_profit, i - min_so_far) <NEW_LINE> min_so_far = min(min_so_far, i) <NEW_LINE> <DEDENT> return max_profit | :type prices: List[int]
:rtype: int | 625941c9e1aae11d1e749d43 |
def test_sec_reset_password_custom_complexity(self): <NEW_LINE> <INDENT> client = self.app.test_client() <NEW_LINE> self.app.config["FAB_PASSWORD_COMPLEXITY_ENABLED"] = True <NEW_LINE> self.app.config["FAB_PASSWORD_COMPLEXITY_VALIDATOR"] = custom_password_validator <NEW_LINE> _ = self.browser_login(client, USERNAME_ADM... | Test Security reset password with custom complexity | 625941c90a50d4780f666f1f |
def delete_category(category_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> res = _pybossa_req('delete', 'category', category_id) <NEW_LINE> if type(res).__name__ == 'bool': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return res <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDEN... | Deletes a Category with id = category_id
:param category_id: PyBossa Category ID
:type category_id: integer
:returns: True -- the response status code | 625941c94e4d5625662d4466 |
def getPen(self): <NEW_LINE> <INDENT> self.raiseNotImplementedError() | Return a :ref:`type-pen` object for adding outline data
to the glyph.
>>> pen = glyph.getPen() | 625941c9adb09d7d5db6c81d |
def test_init_shuffle_y(self): <NEW_LINE> <INDENT> X=pd.DataFrame([1,2,3,4,5,6]) <NEW_LINE> Y=pd.DataFrame([1,2,3,4,4,5]) <NEW_LINE> kfold=CV(X,Y) <NEW_LINE> self.assertFalse(kfold.y.equals(Y)) | Tests to see whether the class returns the x and y dataframes properly | 625941c9a4f1c619b28b00c8 |
@main.route('/traces/<trace_id>') <NEW_LINE> def trace(trace_id): <NEW_LINE> <INDENT> trace = Traces.query.get(trace_id) <NEW_LINE> return render_template('traces/trace_detail.html', trace=trace, home_button=True) | Retrieve single trace datas | 625941c960cbc95b062c65d0 |
@follows(runMACSsolo, loadMACSsolo, summarizeMACSsolo, loadMACSsoloSummary, exportIntervalsAsBedsolo) <NEW_LINE> def macs(): <NEW_LINE> <INDENT> pass | align fastq files to genome using Bowtie and convert BAM to bigwig | 625941c9796e427e537b0653 |
@cli.command('sync') <NEW_LINE> @click.argument('pathname', type=click.Path(exists=True)) <NEW_LINE> @click.argument('bucket') <NEW_LINE> def sync(pathname, bucket): <NEW_LINE> <INDENT> s3_bucket = s3.Bucket(bucket) <NEW_LINE> root = Path(pathname).expanduser().resolve() <NEW_LINE> def handle_directory(target): <NEW_LI... | Sync contents of PATHNAME to BUCKET. | 625941c97d43ff24873a2d2e |
@commands.create('stripurl', category='String') <NEW_LINE> @string_filter <NEW_LINE> def strip_html(text): <NEW_LINE> <INDENT> return LINK_PATTERN.sub('', text) | Strip URLs from a string. | 625941c923e79379d52ee5f2 |
def find_primes(max_number: int) -> List[int]: <NEW_LINE> <INDENT> is_compose = [False] * max_number <NEW_LINE> for i in range(4, max_number, 2): <NEW_LINE> <INDENT> is_compose[i] = True <NEW_LINE> <DEDENT> next_prime = 3 <NEW_LINE> stop_at = math.sqrt(max_number) <NEW_LINE> while next_prime < stop_at: <NEW_LINE> <INDE... | Поиск простых чисел от 1 до max_number. Решето Эратосфена.
Search of Prime numbers from 1 to max_number. The Sieve Of Eratosthenes. | 625941c9498bea3a759b9b3c |
def loss(self, labels, logits, features=None, mode=None, regularization_losses=None): <NEW_LINE> <INDENT> return self._base_head.loss( labels, logits, features, mode, regularization_losses) | Returns a loss `Tensor` from provided arguments.
The returned loss is the same as that of the base head and is meant
solely for book-keeping purposes. We do not return the custom loss used to
create the train_op for constrained optimization, as this loss makes use of
auxilliary variables whose values may not be set pr... | 625941c9cb5e8a47e48b7b39 |
def _Promote(arg, klass): <NEW_LINE> <INDENT> if arg is None: <NEW_LINE> <INDENT> return arg <NEW_LINE> <DEDENT> if klass == 'Image': <NEW_LINE> <INDENT> return Image(arg) <NEW_LINE> <DEDENT> elif klass == 'Feature': <NEW_LINE> <INDENT> if isinstance(arg, Collection): <NEW_LINE> <INDENT> return ApiFunction.call_( 'Feat... | Wrap an argument in an object of the specified class.
This is used to e.g.: promote numbers or strings to Images and arrays
to Collections.
Args:
arg: The object to promote.
klass: The expected type.
Returns:
The argument promoted if the class is recognized, otherwise the
original argument. | 625941c98da39b475bd65000 |
def get_train_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples(self._read_tsv(os.path.join(data_dir, "train_new.tsv")), "train") | See base class. | 625941c93eb6a72ae02ec569 |
def test3(self): <NEW_LINE> <INDENT> exception_raised = False <NEW_LINE> try: <NEW_LINE> <INDENT> result = train(gamma=0.001) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> exception_raised = True <NEW_LINE> <DEDENT> self.assertFalse(exception_raised) | testing the train() function with hyperparameter gamma only | 625941c944b2445a33932124 |
def get_tags(self, name=None) -> List['Tag']: <NEW_LINE> <INDENT> lststr = self._lststr <NEW_LINE> type_to_spans = self._type_to_spans <NEW_LINE> if name: <NEW_LINE> <INDENT> if name in _tag_extensions: <NEW_LINE> <INDENT> string = lststr[0] <NEW_LINE> return [ Tag(lststr, type_to_spans, span, 'ExtensionTag') for span ... | Return all tags with the given name. | 625941c9d8ef3951e32435cb |
def test_model_can_create_a_counting_request(self): <NEW_LINE> <INDENT> old_count = CountRequest.objects.count() <NEW_LINE> self.count_request.save() <NEW_LINE> new_count = CountRequest.objects.count() <NEW_LINE> self.assertNotEqual(old_count, new_count) | Test the count request model can create a count_request. | 625941c963d6d428bbe4457d |
def mpa_sum(X): <NEW_LINE> <INDENT> node = Node('sum', [X]) <NEW_LINE> X.add_children(node) <NEW_LINE> return node | Returns a Node, child of X, with the Operation sum of X (sums all the elements of X) | 625941c910dbd63aa1bd2c31 |
def rpc_getMethods(self, target): <NEW_LINE> <INDENT> validMethods = [] <NEW_LINE> target_members = inspect.getmembers(target) <NEW_LINE> for attr, val in target_members: <NEW_LINE> <INDENT> if inspect.ismethod(val) and not attr.startswith('_'): <NEW_LINE> <INDENT> validMethods.append(attr) <NEW_LINE> <DEDENT> <DEDENT>... | Get a list of valid methods in the registered objects. Protected methods
that begin with an underscore ('_') are not included.
:returns: list of strings | 625941c956b00c62f0f146e6 |
def test_home_brewery_name(self): <NEW_LINE> <INDENT> response = self.app.get('/') <NEW_LINE> self.assertIn(b'CARTON', response.data) | testing if home is getting Brewery name from database
and showing on page when page load | 625941c9c432627299f04cd3 |
def append(self, item): <NEW_LINE> <INDENT> focus = self._adjust_focus_on_contents_modified( slice(len(self), len(self)), [item]) <NEW_LINE> rval = super(MonitoredFocusList, self).append(item) <NEW_LINE> self._set_focus(focus) <NEW_LINE> return rval | >>> def modified(indices, new_items):
... print "range%r <- %r" % (indices, new_items)
>>> ml = MonitoredFocusList([0,1,2], focus=2)
>>> ml.set_validate_contents_modified(modified)
>>> ml.append(6)
range(3, 3, 1) <- [6] | 625941c996565a6dacc8f759 |
def tails(file_object, last_lines): <NEW_LINE> <INDENT> with open(file_object) as file_object: <NEW_LINE> <INDENT> assert last_lines >= 0 <NEW_LINE> pos, lines = last_lines + 1, [] <NEW_LINE> while len(lines) <= last_lines: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> file_object.seek(-pos, 2) <NEW_LINE> <DEDENT> excep... | mimics the tail command | 625941c98a43f66fc4b540f3 |
def get_training_directory(self): <NEW_LINE> <INDENT> return self.join_path(self.get_data_general_directory, PATH_FOR_TRAINING) | Gets training data directory
Returns:
training data directory path | 625941c985dfad0860c3aee8 |
def create_loss(self, features, mode, logits, labels): <NEW_LINE> <INDENT> del mode <NEW_LINE> logits = ops.convert_to_tensor(logits) <NEW_LINE> labels = _check_dense_labels_match_logits_and_reshape( labels=labels, logits=logits, expected_labels_dimension=self._logits_dimension) <NEW_LINE> labels = tf.cast(labels, dtyp... | See `Head`. | 625941c98a349b6b435e8201 |
def net_representation_shift(side, shape, line): <NEW_LINE> <INDENT> line = n.array(line) <NEW_LINE> if len(line) == 0: <NEW_LINE> <INDENT> return line <NEW_LINE> <DEDENT> if side == 0: <NEW_LINE> <INDENT> line[:, 0] += shape <NEW_LINE> line[:, 1] += shape <NEW_LINE> <DEDENT> elif side == 1: <NEW_LINE> <INDENT> line[:,... | Given a side, a shape, and a line from that side's array, shifts
the line in the x-y plane so that it will be in the right place in
a net diagram. | 625941c9a934411ee3751721 |
def __tf_rotation_config(M, axis, q): <NEW_LINE> <INDENT> cs = np.cos <NEW_LINE> sn = np.sin <NEW_LINE> if axis == ROT_AXIS_X: <NEW_LINE> <INDENT> M[0, 0] = 1. <NEW_LINE> M[1, 1] = cs(q) <NEW_LINE> M[1, 2] = -sn(q) <NEW_LINE> M[2, 1] = sn(q) <NEW_LINE> M[2, 2] = cs(q) <NEW_LINE> <DEDENT> elif axis == ROT_AXIS_Y: <NEW_L... | @brief Configures rotation part of transformation matrix
@param[out] M - transformation matrix at least [3x3]
@param[in] axis - rotation axis
@param[in] q - joint angles | 625941c96e29344779a626a0 |
def get_event_detail(self, pguid, guid): <NEW_LINE> <INDENT> params = dict(self.params) <NEW_LINE> params.update({'lang': 'en-us', 'usertz': get_localzone().zone}) <NEW_LINE> url = '%s/%s/%s' % (self._calendar_event_detail_url, pguid, guid) <NEW_LINE> req = self.session.get(url, params=params) <NEW_LINE> self.response ... | Fetches a single event's details by specifying a pguid
(a calendar) and a guid (an event's ID). | 625941c916aa5153ce362506 |
def dsp(self): <NEW_LINE> <INDENT> zn = self.pole / abs(self.pole) <NEW_LINE> num = self.gain * (zn - self.pole) <NEW_LINE> pm1 = self.pole - 1.0 <NEW_LINE> return num, pm1 | Convert abstract setup to complex kx, ky | 625941c9a8ecb033257d315b |
def test_unread(dbsession: Session, user_id, test_request): <NEW_LINE> <INDENT> with transaction.manager: <NEW_LINE> <INDENT> u = dbsession.query(User).get(user_id) <NEW_LINE> stream = Stream.get_or_create_user_stream(u) <NEW_LINE> assert get_unread_activity_count(stream) == 0 <NEW_LINE> object_id = uuid4() <NEW_LINE> ... | Get unread activity count. | 625941c91b99ca400220ab3f |
@staticmethod <NEW_LINE> def _is_control(ch): <NEW_LINE> <INDENT> return unicodedata.category(ch) in ('Cc', 'Cf') | 控制类字符判断
| 625941c929b78933be1e573b |
def confirm_on_close(widget, title="Close ScopeFoundry?", message="Do you wish to shut down ScopeFoundry?", func_on_close=None): <NEW_LINE> <INDENT> widget.closeEventEater = ConfirmCloseEventEater(title, message, func_on_close) <NEW_LINE> widget.installEventFilter(widget.closeEventEater) | Calls the :class:`ConfirmCloseEventEater` class which asks for user
confirmation in a pop-up dialog upon closing the ScopeFoundry app. | 625941c9009cb60464c63440 |
def get_all(self): <NEW_LINE> <INDENT> self.__read_settings() <NEW_LINE> return self._setting | Get all settings.
Returns:
dict: all settings. | 625941c94428ac0f6e5ba880 |
def image_persistent(call=None, kwargs=None): <NEW_LINE> <INDENT> if call != "function": <NEW_LINE> <INDENT> raise SaltCloudSystemExit( "The image_persistent function must be called with -f or --function." ) <NEW_LINE> <DEDENT> if kwargs is None: <NEW_LINE> <INDENT> kwargs = {} <NEW_LINE> <DEDENT> name = kwargs.get("na... | Sets the Image as persistent or not persistent.
.. versionadded:: 2016.3.0
name
The name of the image to set. Can be used instead of ``image_id``.
image_id
The ID of the image to set. Can be used instead of ``name``.
persist
A boolean value to set the image as persistent or not. Set to true
for pers... | 625941c9187af65679ca51ac |
def delete(self, request, pk): <NEW_LINE> <INDENT> photo = get_object_or_404(Photo, pk=pk) <NEW_LINE> user = request.user <NEW_LINE> photo.voters.remove(user) <NEW_LINE> photo.save() <NEW_LINE> serializer_context = {"request": request} <NEW_LINE> serializer = self.serializer_class(photo, context=serializer_context) <NE... | Remove request.user from the voters queryset of an answer instance. | 625941c9236d856c2ad44867 |
def processFrame(frameImage): <NEW_LINE> <INDENT> timeImage = frameImage.crop((589,656,751,701)) <NEW_LINE> altitudeImage = frameImage.crop((1359,226,1464,254)) <NEW_LINE> speedImage = frameImage.crop((1665,226,1764,256)) <NEW_LINE> heartImage = frameImage.crop((1368,526,1460,555)) <NEW_LINE> respirImage = frameImage.c... | Extract text from a PIL image frame | 625941c90fa83653e465704a |
def stop(self): <NEW_LINE> <INDENT> return lib.process.kill_mprocess(self.proc) | stop host | 625941c97c178a314d6ef4ed |
def clean_lines(commands): <NEW_LINE> <INDENT> if isinstance(commands, basestring): <NEW_LINE> <INDENT> if path.isfile(commands): <NEW_LINE> <INDENT> commands = open(commands, 'rb') <NEW_LINE> <DEDENT> elif len(commands.split(',')) > 1: <NEW_LINE> <INDENT> commands = commands.split(',') <NEW_LINE> <DEDENT> else: <NEW_L... | Generate strings that are not comments or lines with only whitespace.
Purpose: This function is a generator that will read in either a
| plain text file of strings(IP list, command list, etc), a
| comma separated string of strings, or a list of strings. It
| will crop out any comments or blank lin... | 625941c91f5feb6acb0c4bdf |
def equals(self, obj): <NEW_LINE> <INDENT> if obj == None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not isinstance(obj, Node): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self._type != obj.type: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self._name != obj.name: <NEW_LINE> <INDENT... | Compare two nodes for equality. This method returns true if the two topology nodes
are equal and the same. For CDP nodes the hostname and the management IP address of
the node are compared.
@param obj: The other Node object to compare with.
@return: Returns true if the two topology nodes are equal and the same. | 625941c9fbf16365ca6f6251 |
def add_port(self, port): <NEW_LINE> <INDENT> self.interfaces[port] = port | Associate the given port to this node
:param port: The Port object to register | 625941c9287bf620b61d3af2 |
def _build_graph(self): <NEW_LINE> <INDENT> self._inputs = tf.placeholder("float", [None, self._w_img_dim, self._h_img_dim, 3]) <NEW_LINE> self._targets = tf.placeholder("float", [None, self._n_outputs]) <NEW_LINE> self._predict = self._model(self._inputs) <NEW_LINE> self._loss = tf.losses.huber_loss( labels=self._targ... | Build graph and define placeholders and variables. | 625941c9a4f1c619b28b00c9 |
def on_click(self, button, button_state, cursor_x, cursor_y): <NEW_LINE> <INDENT> self.isdragging = False <NEW_LINE> if (button == GLUT.GLUT_LEFT_BUTTON and button_state == GLUT.GLUT_UP): <NEW_LINE> <INDENT> self.lastrot = copy.copy(self.thisrot) <NEW_LINE> <DEDENT> elif (button == GLUT.GLUT_LEFT_BUTTON and button_stat... | Mouse button clicked.
Glut calls this function when a mouse button is
clicked or released. | 625941c94c3428357757c3b6 |
@blueprint.route("/recipe/tag/<tags>", methods=["GET"]) <NEW_LINE> @response(template_file="recipe/tag.html") <NEW_LINE> def recipes_with_tags(tags: List[str]): <NEW_LINE> <INDENT> if not isinstance(tags, MutableSequence): <NEW_LINE> <INDENT> tags = [tags] <NEW_LINE> <DEDENT> uc = RecipeUC(current_app.config["DB_DRIVER... | Routing required to view recipes with a given tag.
:param recipe_id: (str) the DB id of the recipe.
:returns: recipe or 404 if recipe is not found. | 625941c92c8b7c6e89b3584f |
def generate_insert_formatter_dict(self): <NEW_LINE> <INDENT> r = {} <NEW_LINE> for k, v in self.__dict__.items(): <NEW_LINE> <INDENT> if not self.is_valid_field_key(k, True): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if isinstance(v, str): <NEW_LINE> <INDENT> v = v.replace("'", "\\'") <NEW_LINE> v = v.replace('... | 生成用于格式化的字典,对内容进行转义 | 625941c97b180e01f3dc488d |
def _transform(x, y): <NEW_LINE> <INDENT> x, y = np.array(x), np.array(y) <NEW_LINE> x = -x if flip_direction else x <NEW_LINE> return (x, y) if horizontal else (y, x) | Transform raw drawing coordinates if
axis or direction is flipped | 625941c93539df3088e2e3d9 |
def main(args): <NEW_LINE> <INDENT> for seq in SeqIO.parse(args.fasta, 'fasta'): <NEW_LINE> <INDENT> filename = '{}.fa'.format(seq.id).lower() <NEW_LINE> if not os.path.isfile(filename) or check_continue(message='{} already exists. Overwrite?'.format(filename)): <NEW_LINE> <INDENT> SeqIO.write(seq, filename, 'fasta') | Main script | 625941c9507cdc57c6306d68 |
def test_parse_date_time(self): <NEW_LINE> <INDENT> self.assertEqual( self.test_quote.parse_datetime(self.test_raw_date, self.test_raw_time), self.test_parsed_datetime ) | parse_date_time should parse a Yahoo CSV date and time correctly. | 625941c96aa9bd52df036e32 |
def self_path_and_context(self): <NEW_LINE> <INDENT> context = {} <NEW_LINE> path = 'openassessmentblock/self/oa_self_unavailable.html' <NEW_LINE> problem_closed, reason, start_date, due_date = self.is_closed(step="self-assessment") <NEW_LINE> if due_date < DISTANT_FUTURE: <NEW_LINE> <INDENT> context['self_due'] = due_... | Determine the template path and context to use when rendering the self-assessment step.
Returns:
tuple of `(path, context)`, where `path` (str) is the path to the template,
and `context` (dict) is the template context.
Raises:
SubmissionError: Error occurred while retrieving the current submission.
Se... | 625941c95fdd1c0f98dc02c1 |
def generateExportSymbols(self): <NEW_LINE> <INDENT> exportSymbols = '' <NEW_LINE> for cat in self.categoryList_.categories(self.name_, self.coreCategories_, self.addinCategories_, supportedplatform.MANUAL): <NEW_LINE> <INDENT> for func in cat.functions(self.name_, supportedplatform.MANUAL): <NEW_LINE> <INDENT> exportS... | Generate directives that cause exported symbols to be available to
clients of this Addin. | 625941c992d797404e304218 |
def expand_string(string, display=None, glob_sequence=False, frame=None, token_dict=dict(), asFilePath=False): <NEW_LINE> <INDENT> global __SCENE_STRING_CONVERTER__ <NEW_LINE> def _resetStringConverter(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> __SCENE_STRING_CONVERTER__.expr = None <NEW_LINE> <DEDENT> except: <NE... | expand a string containing tokens.
Args:
- string (str): a string that may or may not contain tokens.
Kwargs:
- display (str): the name of a display driver to update <ext> tokens.
- frame (str): the frame to use for expanding
- token_dict (dict): dictionary of token/vals that also need to be set.
- asFilePath (bool):... | 625941c9435de62698dfdcdb |
def associate_detections_to_trackers(detections, trackers, iou_threshold=0.3): <NEW_LINE> <INDENT> if (len(trackers) == 0): <NEW_LINE> <INDENT> return np.empty((0, 2), dtype=int), np.arange(len(detections)), np.empty((0, 5), dtype=int) <NEW_LINE> <DEDENT> iou_matrix = np.zeros((len(detections), len(trackers)), dtype=np... | Assigns detections to tracked object (both represented as bounding boxes)
Returns 3 lists of matches, unmatched_detections and unmatched_trackers | 625941c95166f23b2e1a51e7 |
def testRandomizedList(self): <NEW_LINE> <INDENT> l = self.l[:] <NEW_LINE> random.shuffle(l) <NEW_LINE> self.checkIntervals(self.buildIndex(l)) | test randomized list. | 625941c98c0ade5d55d3ea49 |
def load( self, loader, treeitem ): <NEW_LINE> <INDENT> self.treeitem = treeitem <NEW_LINE> self.h5_obj = loader <NEW_LINE> self.start() | start loading the icecache data | 625941c9046cf37aa974cdd7 |
def __init__(self, *arg, **kwarg): <NEW_LINE> <INDENT> super().__init__(*arg, **kwarg) <NEW_LINE> self.initUI() <NEW_LINE> self.setObjectName('subWidget') | Reimplemented from QWidget | 625941c97cff6e4e81117a14 |
def numIslands(self, grid): <NEW_LINE> <INDENT> row_cnt = len(grid) <NEW_LINE> if row_cnt == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> col_cnt = len(grid[0]) <NEW_LINE> if col_cnt == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> islands_count = 0 <NEW_LINE> for r in range(row_cnt): <NEW_LINE> <INDENT> f... | :type grid: List[List[str]]
:rtype: int | 625941c93346ee7daa2b2df9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.