code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test(did_pass): <NEW_LINE> <INDENT> linenum = sys._getframe(1).f_lineno <NEW_LINE> if did_pass: <NEW_LINE> <INDENT> msg = "Test at line {0} ok.".format(linenum) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = ("Test at lne {0} FAILED.".format(linenum)) <NEW_LINE> <DEDENT> print(msg) | Print the result of a test. | 625941e2711fe17d8254271b |
def adam(x, y, b1, b2, phi1, phi2, epsilon, delta, t, s, r): <NEW_LINE> <INDENT> grad_dict = {} <NEW_LINE> grad_dict["1"], grad_dict["2"] = grad(x,y, b1, b2) <NEW_LINE> s_hat = {} <NEW_LINE> r_hat = {} <NEW_LINE> for i in list(grad_dict.keys()): <NEW_LINE> <INDENT> s[i] = phi1*s[i] + (1-phi1)*grad_dict[i] <NEW_LINE> s_... | Implementation of adam optimizer | 625941e2bd1bec0571d909e7 |
def remove_comment(cmt_id, user_id): <NEW_LINE> <INDENT> comment = session.query(Comment).filter_by(_id=cmt_id).one() <NEW_LINE> if comment.author == user_id: <NEW_LINE> <INDENT> session.delete(comment) <NEW_LINE> session.commit() <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Remove the comment from DB. | 625941e2d486a94d0b98e4ff |
def p_return(p): <NEW_LINE> <INDENT> p[0] = opc_compile(p[1]) | return : RETURN | 625941e23346ee7daa2b3126 |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> tk.Tk.__init__(self, *args, **kwargs) <NEW_LINE> self.title("Quickmedia") <NEW_LINE> container = tk.Frame(self) <NEW_LINE> container.pack(side="top", fill="both", expand = True) <NEW_LINE> container.grid_rowconfigure(0, weight=1) <NEW_LINE> container.grid_columnc... | method initialiizes the applcation, sets up the start window | 625941e271ff763f4b549a4a |
def test_merge_ignores_unpublished_vor_when_setting_status_date(self): <NEW_LINE> <INDENT> fixture = join(self.fixture_dir, "ajson", "elife-16695-v2.xml.json") <NEW_LINE> data = json.load(open(fixture, "r")) <NEW_LINE> av2 = ajson_ingestor.ingest(data) <NEW_LINE> av1 = self.freshen(self.av) <NEW_LINE> expected = "2016-... | the first unpublished VOR doesn't get a value until it's published | 625941e2435de62698dfe006 |
def run_plugin(self, plugin_id, plugin_input): <NEW_LINE> <INDENT> plugin, plugin_info = self.get_plugin(plugin_id) <NEW_LINE> Config._context._PluginContext__plugin_info = plugin_info <NEW_LINE> Config._context._PluginContext__ack_identity = None <NEW_LINE> try: <NEW_LINE> <INDENT> HTTP._initialize() <NEW_LINE> Netwo... | Run the requested plugin. You can test both data and messages.
It's the caller's resposibility to check the input message queue of
the Orchestrator instance if the plugin sends any messages.
:param plugin_id: ID of the plugin to test.
:type plugin_id: str
:param plugin_input: Plugin input.
Testing plugins accept... | 625941e299fddb7c1c9de747 |
def create_signatures(corpus): <NEW_LINE> <INDENT> for key, doc in corpus: <NEW_LINE> <INDENT> hashvalues=np.ones(NUM_PERM,dtype=np.int64) <NEW_LINE> hashvalues=hashvalues*MAX_HASH <NEW_LINE> for token in doc: <NEW_LINE> <INDENT> hashvalues = np.minimum(get_permuted_hashes(token), hashvalues) <NEW_LINE> <DEDENT> yield ... | Compute signatures of all documents
:param corpus: A dictionary of [doc ID, set of tokens]
:return: A generator of tuple (doc id, numpy array of minhash values) | 625941e291f36d47f21ac8af |
def get_song_url(self, song_id, bit_rate=320000): <NEW_LINE> <INDENT> url = 'http://music.163.com/weapi/song/enhance/player/url?csrf_token=' <NEW_LINE> csrf = '' <NEW_LINE> params = {'ids': [song_id], 'br': bit_rate, 'csrf_token': csrf} <NEW_LINE> result = self.post_request(url, params) <NEW_LINE> song_url = result['da... | Get a song's download address.
:params song_id: song id<int>.
:params bit_rate: {'MD 128k': 128000, 'HD 320k': 320000}
:return: a song's download address. | 625941e299fddb7c1c9de748 |
def find_config_file(): <NEW_LINE> <INDENT> for config_path in CONFIG_SEARCH_PATHS: <NEW_LINE> <INDENT> logger.debug("Searching for config file at: %s", config_path) <NEW_LINE> try: <NEW_LINE> <INDENT> config = read_config(config_path) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> els... | Search CONFIG_SEARCH_PATHS until config file is found; open and return it | 625941e291af0d3eaac9bdd4 |
def test_distortions_ex2(): <NEW_LINE> <INDENT> x0 = [1, 100, 1000, 1990] <NEW_LINE> y0 = [1200, 900, 200, 5] <NEW_LINE> p_x1 = [16.20132521, 110.97939823, 1000.22549019, 1962.80728145] <NEW_LINE> p_y1 = [1197.39342201, 901.47856688, 207.58843519, 33.71359561] <NEW_LINE> x1, y1 = exvp(p_x1, p_y1) <NEW_LINE> assert nump... | Inverse transformation, not very precise | 625941e2e1aae11d1e74a073 |
def extract_cols(i_dict, f_dict, cols): <NEW_LINE> <INDENT> i_cols, f_cols = OrderedDict(), OrderedDict() <NEW_LINE> for col in cols: <NEW_LINE> <INDENT> i_header, f_header = i_dict.get(col), f_dict.get(col) <NEW_LINE> if i_header: <NEW_LINE> <INDENT> i_cols.update({col: i_header}) <NEW_LINE> <DEDENT> if f_header and (... | Select the columns from INFO/FORMAT using list 'cols'
Input:
info and format dictionaries of header object
{column_name: header object}
cols, a list of column names specified by the user
Output:
new info and format dictionaries | 625941e2bf627c535bc13588 |
def admin_required(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def wrapped(*args, **kwargs): <NEW_LINE> <INDENT> if not current_user.is_admin: <NEW_LINE> <INDENT> abort(404) <NEW_LINE> <DEDENT> return func(*args, **kwargs) <NEW_LINE> <DEDENT> return wrapped | admin required decorator | 625941e28e71fb1e9831db60 |
def render(self, *args, **kwargs): <NEW_LINE> <INDENT> env = {} <NEW_LINE> stdout = [] <NEW_LINE> for dictarg in args: <NEW_LINE> <INDENT> env.update(dictarg) <NEW_LINE> <DEDENT> env.update(kwargs) <NEW_LINE> env['__main_file__'] = kwargs.get('__main_file__') or self.filename <NEW_LINE> self.execute(stdout, env) <NEW_L... | Render the template using keyword arguments as local variables. | 625941e2ec188e330fd5ab50 |
def main(vocab_path: str, elmo_config_path: str, elmo_weights_path: str, output_dir: str, batch_size: int, device: int, use_custom_oov_token: bool = False): <NEW_LINE> <INDENT> with open(vocab_path, 'r') as vocab_file: <NEW_LINE> <INDENT> tokens = vocab_file.read().strip().split('\n') <NEW_LINE> <DEDENT> if tokens[0] !... | Creates ELMo word representations from a vocabulary file. These
word representations are _independent_ - they are the result of running
the CNN and Highway layers of the ELMo model, but not the Bidirectional LSTM.
ELMo requires 2 additional tokens: <S> and </S>. The first token
in this file is assumed to be an unknown ... | 625941e28da39b475bd65330 |
def get_initial_condition_list(): <NEW_LINE> <INDENT> file_list = [] <NEW_LINE> initial_type = initial_condition_control['initial_condition_type'] <NEW_LINE> if initial_type == 'superMC': <NEW_LINE> <INDENT> nev = controlParameterList['numberOfEvents'] <NEW_LINE> file_list = [afile for afile in generateSuperMCInitialCo... | return a list of initial condition file | 625941e25166f23b2e1a5511 |
def post(self, request, local_backend, *args, format=None, **kwargs): <NEW_LINE> <INDENT> request._request.POST = request._request.POST.copy() <NEW_LINE> server_app = Application.objects.filter(name=f'{local_backend}_app') <NEW_LINE> if not server_app.exists(): <NEW_LINE> <INDENT> return Response( _({'error': 'Current ... | Get copy of the request.POST and add additional
body parameters to the given request.
Args:
request: common WSGI or ASGI request response
local_backend: app backend for the auth/registration
Returns:
Response: JSON response from the server | 625941e223e79379d52ee918 |
def upload_object( self, file_path, container, object_name, extra=None, verify_hash=True, headers=None, ): <NEW_LINE> <INDENT> if not os.path.exists(file_path): <NEW_LINE> <INDENT> raise LibcloudError( value="File %s does not exist" % (file_path), driver=self ) <NEW_LINE> <DEDENT> size = os.path.getsize(file_path) <NEW... | >>> driver = DummyStorageDriver('key', 'secret')
>>> container_name = 'test container 1'
>>> container = driver.create_container(container_name=container_name)
>>> container.upload_object(file_path='/tmp/inexistent.file',
... object_name='test') #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
... | 625941e2091ae35668667311 |
def create_menus(self): <NEW_LINE> <INDENT> new_menu = lambda name: self.menuBar().addMenu(name) <NEW_LINE> def populate_menu(menu, action_list, signal_handler): <NEW_LINE> <INDENT> for action in action_list: <NEW_LINE> <INDENT> if action == '/': <NEW_LINE> <INDENT> menu.addSeparator() <NEW_LINE> <DEDENT> else: <NEW_LI... | Creates the menus for the main app | 625941e2d164cc6175783108 |
def get_jge_llil(src): <NEW_LINE> <INDENT> def jge_llil(il, inst): <NEW_LINE> <INDENT> src_il = aluret_src_IL[src](il, inst) <NEW_LINE> cond = il.compare_unsigned_greater_equal(4, il.reg(4, 'a'), src_il) <NEW_LINE> return jc_il(il, inst, cond) <NEW_LINE> <DEDENT> return jge_llil | gets llil generator for jump greater or equal conditional jump
:param src: source for comparison BPF_K or BPF_X
:return: function to generate llil for jge | 625941e2046cf37aa974d0fd |
def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkSampleVF2.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj | New() -> itkSampleVF2
Create a new object of the class itkSampleVF2 and set the input and the parameters if some
named or non-named arguments are passed to that method.
New() tries to assign all the non named parameters to the input of the new objects - the
first non named parameter in the first input, etc.
The name... | 625941e26aa9bd52df03715e |
def loss(self, features, captions): <NEW_LINE> <INDENT> captions_in = captions[:, :-1] <NEW_LINE> captions_out = captions[:, 1:] <NEW_LINE> mask = (captions_out != self._null) <NEW_LINE> W_proj, b_proj = self.params['W_proj'], self.params['b_proj'] <NEW_LINE> W_embed = self.params['W_embed'] <NEW_LINE> Wx, Wh, b = self... | Compute training-time loss for the RNN. We input image features and
ground-truth captions for those images, and use an RNN (or LSTM) to compute
loss and gradients on all parameters.
Inputs:
- features: Input image features, of shape (N, D)
- captions: Ground-truth captions; an integer array of shape (N, T) where
eac... | 625941e20c0af96317bb85a0 |
def Click(self, ratioX = 0.5, ratioY = 0.5, simulateMove = True): <NEW_LINE> <INDENT> x, y = self.MoveCursor(ratioX, ratioY, simulateMove) <NEW_LINE> Win32API.MouseClick(x, y) | Click(0.5, 0.5): click center
Click(10, 10): click left+10, top+10
Click(-10, -10): click right-10, bottom-10
simulateMove:bool, if True, first move cursor to control smoothly | 625941e26e29344779a629c9 |
def to_native_str( text: StrOrBytes, encoding: Optional[str] = None, errors: str = "strict" ) -> str: <NEW_LINE> <INDENT> warn( "The w3lib.utils.to_native_str function is deprecated and " "will be removed in a future release. Please use " "w3lib.utils.to_unicode instead.", DeprecationWarning, stacklevel=2, ) <NEW_LINE>... | Return str representation of `text` | 625941e215baa723493c4331 |
def update_ble(now): <NEW_LINE> <INDENT> period = config[CONF_PERIOD] <NEW_LINE> _LOGGER.debug("update_ble called") <NEW_LINE> try: <NEW_LINE> <INDENT> discover_ble_devices(config, aeskeys) <NEW_LINE> <DEDENT> except RuntimeError as error: <NEW_LINE> <INDENT> _LOGGER.error("Error during Bluetooth LE scan: %s", error) <... | Lookup Bluetooth LE devices and update status. | 625941e25e10d32532c5f2de |
def test_extracted_mentions_invalid_input(self): <NEW_LINE> <INDENT> pc = PerformanceCalculator({'1':{},'2':{}}) <NEW_LINE> self.assertRaises(PerformanceCalculatorError, pc.calculate_extracted_mentions,{'1':{},'3':{}}) <NEW_LINE> self.assertRaises(PerformanceCalculatorError, pc.calculate_extracted... | PC: Extracted Mentions handles invalid input correctly
| 625941e2fbf16365ca6f6584 |
def test_get_title_versions_single_movie(self): <NEW_LINE> <INDENT> title = MovieTitle("Gone Girl", 2014, "tt2267998") <NEW_LINE> fake_version = Version(["identifier"], title) <NEW_LINE> titles_versions = self.provider.get_title_versions(title, fake_version) <NEW_LINE> self.assertEquals(len(titles_versions), 1) <NEW_LI... | Check the content of the movie page. | 625941e266656f66f7cbc565 |
def getPointSizeLimits(self, *args): <NEW_LINE> <INDENT> return _soqt.SoQtGLWidget_getPointSizeLimits(self, *args) | getPointSizeLimits(self, SbVec2f range, float granularity) | 625941e24428ac0f6e5babae |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): <NEW_LINE> <INDENT> new_rup = copy.deepcopy(rup) <NEW_LINE> new_rup.hypo_depth = 20. <NEW_LINE> mean, stddevs = super().get_mean_and_stddevs( sites, new_rup, dists, imt, stddev_types) <NEW_LINE> return mean, stddevs | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
Call super class method with hypocentral depth fixed at 20 km | 625941e2ab23a570cc25053e |
def execute_jafar_and_return_validated_test_keys( ooni_exe, outfile, experiment_args, tag, args ): <NEW_LINE> <INDENT> tk = common.execute_jafar_and_miniooni( ooni_exe, outfile, experiment_args, tag, args ) <NEW_LINE> return tk | Executes jafar and returns the validated parsed test keys, or throws
an AssertionError if the result is not valid. | 625941e28e71fb1e9831db61 |
def prime_key(P): <NEW_LINE> <INDENT> p = P.smallest_integer() <NEW_LINE> K = P.number_field() <NEW_LINE> try: <NEW_LINE> <INDENT> return K.psort_dict[p][P] <NEW_LINE> <DEDENT> except (AttributeError, KeyError): <NEW_LINE> <INDENT> make_keys(K,p) <NEW_LINE> return K.psort_dict[p][P] | Return the key (n,j,e,i) of a prime ideal P, where n is the norm, e
the ramification index, i the index in the sorted list of primes
with the same (n,e) and j the index in the sorted list or primes
with the same n.
The first time this is called for a prime P above a rational prime
p, all the keys for all primes above ... | 625941e216aa5153ce362831 |
def test_checkURLs_2(self): <NEW_LINE> <INDENT> self.restartAgent.errors = [] <NEW_LINE> self.restartAgent.accounting.clear() <NEW_LINE> self.restartAgent.csAPI.csModified = True <NEW_LINE> self.restartAgent.commitURLs = True <NEW_LINE> self.restartAgent.sysAdminClient.getOverallStatus.return_value = S_OK(dict(Services... | Test commit to CS. | 625941e2462c4b4f79d1da88 |
def __richcmp__(self, other, op): <NEW_LINE> <INDENT> if isinstance(other, KodairaSymbol_class): <NEW_LINE> <INDENT> if (self._n == "generic" and not other._n is None) or (other._n == "generic" and not self._n is None): <NEW_LINE> <INDENT> return richcmp(self._starred, other._starred, op) <NEW_LINE> <DEDENT> return ric... | Standard comparison function for Kodaira Symbols.
EXAMPLES::
sage: from sage.schemes.elliptic_curves.kodaira_symbol import KodairaSymbol_class
sage: KS1 = KodairaSymbol_class(15); KS1
I11
sage: KS2 = KodairaSymbol_class(-34); KS2
I30*
sage: KS1 < KS2
True
sage: KS2 < KS1
False
::
... | 625941e2fb3f5b602dac3a50 |
def showBacktestingResult(self): <NEW_LINE> <INDENT> d = self.calculateBacktestingResult() <NEW_LINE> self.output('-' * 30) <NEW_LINE> self.output(u'第一笔交易:\t%s' % d['timeList'][0]) <NEW_LINE> self.output(u'最后一笔交易:\t%s' % d['timeList'][-1]) <NEW_LINE> self.output(u'总交易次数:\t%s' % formatNumber(d['totalResult'])) <NEW_LINE... | 显示回测结果 | 625941e28a349b6b435e852c |
def __init__(self, target): <NEW_LINE> <INDENT> self.target = target | Construct a callback object, for use with the multicast client, that uses the target function
:param target: The function to execute when running the Callback. The function should take a message as argument and return a message as return value | 625941e25510c4643540f794 |
def groupAnagrams(self, strs): <NEW_LINE> <INDENT> hashmap = {} <NEW_LINE> for string in strs: <NEW_LINE> <INDENT> sorted_string = ''.join(sorted(string)) <NEW_LINE> if sorted_string not in hashmap: <NEW_LINE> <INDENT> hashmap[sorted_string] = [string] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hashmap[sorted_string... | :type strs: List[str]
:rtype: List[List[str]] | 625941e2099cdd3c635f1012 |
def infer(self, dim): <NEW_LINE> <INDENT> if dim is Dimension.Joker: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if dim in self.dimensions: <NEW_LINE> <INDENT> return self.dimensions[dim] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Infer the value of a dimension.
Parameters:
dim: Singleton class representing the dimension to lookup.
Returns:
None if no value has been deduced for the requested dimension.
Otherwise a tuple :code:`(value, who)` consisting of an integer
value :code:`value` representing the deduced value of the re... | 625941e2507cdc57c630709c |
@login_required <NEW_LINE> def game_error(request): <NEW_LINE> <INDENT> char = get_char(request) <NEW_LINE> data = {} <NEW_LINE> if len(char.message_set.all()): <NEW_LINE> <INDENT> return render_to_response("game/error.html", data, context_instance=RequestContext(request)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ... | Generic error page | 625941e226238365f5f0f22c |
def plotsim(self, steps=1000): <NEW_LINE> <INDENT> Y = util.varsim(self.coefs, self.exog, self.sigma_u, steps=steps) <NEW_LINE> plotting.plot_mts(Y) | Plot a simulation from the VAR(p) process for the desired number of
steps | 625941e2f548e778e58cd938 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, MediaFileMetadataSchema): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941e27d847024c06be678 |
def max_output_buffer(self, *args, **kwargs): <NEW_LINE> <INDENT> return _blocks_swig4.or_ii_sptr_max_output_buffer(self, *args, **kwargs) | max_output_buffer(or_ii_sptr self, int i) -> long | 625941e2a79ad161976cc4ff |
def processFile(wordList): <NEW_LINE> <INDENT> lenToWord = {} <NEW_LINE> for item in wordList: <NEW_LINE> <INDENT> item = item.strip().lower() <NEW_LINE> if len(item) in lenToWord: <NEW_LINE> <INDENT> lenToWord[len(item)].append(item) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lenToWord[len(item)] = [item] <NEW_LINE... | Create dicitonary with length as key and list of words with that specific length as values | 625941e24d74a7450ccd457e |
@register.filter(name='app_path') <NEW_LINE> def app_path(value): <NEW_LINE> <INDENT> splitted = value.split('/') <NEW_LINE> return '/'.join(splitted[3:]) | Return the app path (remove path)
:param value:
:return: | 625941e2a8ecb033257d3485 |
def test_30_hmmsearch_001(self): <NEW_LINE> <INDENT> xml_file = get_file('text_30_hmmsearch_001.out') <NEW_LINE> qresults = parse(xml_file, FMT) <NEW_LINE> counter = 0 <NEW_LINE> qresult = next(qresults) <NEW_LINE> counter += 1 <NEW_LINE> self.assertEqual('hmmsearch', qresult.program) <NEW_LINE> self.assertEqual('/home... | Test parsing hmmersearch 3.0 (text_30_hmmsearch_001) | 625941e2099cdd3c635f1013 |
def tanh(self, a, out): <NEW_LINE> <INDENT> self.ng.tanh(a, out=out) <NEW_LINE> return out | Elementwise tanh
Arguments:
a (GPUTensor): input tensor.
out (GPUTensor): where the result will be stored.
Returns:
GPUTensor: reference to out | 625941e2dd821e528d63b55f |
def calc_euclidean_metric(self, *args, **kwargs): <NEW_LINE> <INDENT> return _howto_swig.constellation_dqpsk_sptr_calc_euclidean_metric(self, *args, **kwargs) | calc_euclidean_metric(constellation_dqpsk_sptr self, gr_complex const * sample, float * metric)
Params: (sample, metric) | 625941e223849d37ff7b3446 |
def encode(self, dikt, payload=""): <NEW_LINE> <INDENT> return dikt, payload + struct.pack(self.fmt(), dikt[self.name]) | Lookup the value to be encoded via `self.name` from dikt, encode to
binary and append to payload. | 625941e2b7558d58953c52c6 |
def sine_events(pulsed_frac, Nevents, phase=0.0): <NEW_LINE> <INDENT> Nsrc = int(pulsed_frac*Nevents+0.5) <NEW_LINE> Nbak = Nevents - Nsrc <NEW_LINE> phases = Num.zeros(Nevents, dtype=Num.float) <NEW_LINE> phases[:Nsrc] += cosine_rand(Nsrc) + phase <NEW_LINE> phases[Nsrc:] += Num.random.random(Nbak) <NEW_LINE> phases =... | sine_events(pulsed_frac, Nevents, phase=0.0):
Return an array of 'Nevents' of phase values [0,1)
simulating a folded profile with a pulsed fraction
'pulsed_frac', a phase offset 'phase', and with a
sinusoidal pulse profile. | 625941e27d43ff24873a305c |
def get_wait_sec() -> int: <NEW_LINE> <INDENT> now = datetime.now() <NEW_LINE> future = datetime(now.year, now.month, now.day, now.hour, now.minute) + timedelta(minutes=1) <NEW_LINE> return (future - now).total_seconds() | Return the number of seconds to wait before the next minute | 625941e27b180e01f3dc4baf |
def p_while_act_1(p): <NEW_LINE> <INDENT> global index <NEW_LINE> index["while"] += 1 <NEW_LINE> index["while_stack"].append(index["while"]) <NEW_LINE> i = index["while_stack"][-1] <NEW_LINE> l = LLVMCodeBrUncond("%while.init.{}".format(str(i))) <NEW_LINE> functions[-1].codes.append(l) <NEW_LINE> l = LLVMCODELabel("whi... | while_act_1 : | 625941e23cc13d1c6d3c7732 |
def read(self, length): <NEW_LINE> <INDENT> if not self._opened: <NEW_LINE> <INDENT> raise FtdiError("read() on closed Device") <NEW_LINE> <DEDENT> if self.chunk_size != 0: <NEW_LINE> <INDENT> remaining = length <NEW_LINE> byte_data_list = [] <NEW_LINE> while remaining > 0: <NEW_LINE> <INDENT> rx_bytes = self._read(min... | read(length) -> bytes/string of up to `length` bytes.
read upto `length` bytes from the FTDI device
:param length: maximum number of bytes to read
:return: value read from device
:rtype: bytes if self.mode is 'b', else decode with self.encoding | 625941e2b5575c28eb68e3bd |
def to_json(self): <NEW_LINE> <INDENT> return json.dumps(self.__serialize()) | Serialize class to JSON | 625941e244b2445a3393244d |
def resolve(self): <NEW_LINE> <INDENT> raise NotImplementedError( "The base dependency class does not resolve to anything!" ) | Resolve Dependency
This function will attempt to resolve
a (possible) combination of multiple packages
into a single package. | 625941e23c8af77a43ae3b5e |
def check_jesd(self, silent_if_valid=False): <NEW_LINE> <INDENT> jesd_tx_enable = self.get_jesd_tx_enable() <NEW_LINE> jesd_tx_valid = self.get_jesd_tx_data_valid() <NEW_LINE> jesd_tx_ok = (jesd_tx_enable==jesd_tx_valid) <NEW_LINE> if not jesd_tx_ok: <NEW_LINE> <INDENT> self.log("JESD Tx DOWN", self.LOG_ERROR) <NEW_LIN... | Queries the Jesd tx and rx and compares the
data_valid and enable bits.
Opt Args:
---------
silent_if_valid (bool) : If True, does not print
anything if things are working. | 625941e2d268445f265b5228 |
def create_lines_table(self): <NEW_LINE> <INDENT> self.tables['lines'] = pd.DataFrame(['model_id', 'uffid', 'id', 'field_type', 'trace_num', 'color', 'n_nodes', 'trace_id', 'pos', 'node']) | Creates an empty lines table. | 625941e238b623060ff0b1a7 |
def auth(self, email, password): <NEW_LINE> <INDENT> url = '{api_url}/auth'.format(api_url=settings_loader.hubstaff_api_url) <NEW_LINE> r = requests.post(url, {'email': email, 'password': password}, headers=self.request_headers) <NEW_LINE> if r.status_code == requests.codes.ok: <NEW_LINE> <INDENT> return r.json()['user... | Hubstaff authentication with hubstaff api
:param email: User email
:param password: User password
:return: Hubstaff authentication token | 625941e230c21e258bdfa85a |
def validate_transcript(transcript): <NEW_LINE> <INDENT> if not valid_input_file(transcript): <NEW_LINE> <INDENT> LOGGER.error("Invalid transcript file %s", transcript) <NEW_LINE> sys.exit(1) | Exit if invalid transcript | 625941e23eb6a72ae02ec8a0 |
def test_return_all(self): <NEW_LINE> <INDENT> csv = CSVIntermediary() <NEW_LINE> csv.return_all() | Does return_all work? This checks to see if return_all crashes. | 625941e263f4b57ef00014c8 |
def read_xml_admin_messages(self): <NEW_LINE> <INDENT> paths = self.config["downloaders"]["read_xml_admin_messages"]["paths"] <NEW_LINE> tles = read_tles_from_mmam_xml_files(paths) <NEW_LINE> logging.info("Loaded %d TLEs from admin message XML files", len(tles)) <NEW_LINE> return tles | Read Eumetsat admin messages in XML format. | 625941e24e696a04525c9807 |
def test_zeros(): <NEW_LINE> <INDENT> assert_close(reconstruction(np.zeros((5, 7)), np.zeros((5, 7))), 0) | Test reconstruction with image and mask of zeros | 625941e210dbd63aa1bd2f5c |
def parse_var(line): <NEW_LINE> <INDENT> m = VAR_PATTERN.match(line) <NEW_LINE> if m: <NEW_LINE> <INDENT> exp = int(m.group('exp')) if m.group('exp') else 0 <NEW_LINE> return VarStats(index = int(m.group('parnum')), name = m.group('parname'), mean = float(m.group('mean')) * 10**exp, median = float(m.group('median')), b... | Parse a line returned by format_vars back into the statistics for the
variable on that line. | 625941e2e8904600ed9f22ec |
def _getType(self, tp, name, literal, local, namespaceURI): <NEW_LINE> <INDENT> ofwhat = [] <NEW_LINE> if not (tp.isDefinition() and tp.isComplex()): <NEW_LINE> <INDENT> raise EvaluateException('only supporting complexType definition') <NEW_LINE> <DEDENT> elif tp.content.isComplex(): <NEW_LINE> <INDENT> if hasattr(tp.c... | Returns a typecode instance representing the passed in type and name.
tp -- XMLSchema.TypeDefinition instance
name -- element name
literal -- literal encoding?
local -- is locally defined?
namespaceURI -- namespace | 625941e221a7993f00bc80b0 |
def itkDilateObjectMorphologyImageFilterID2ID2SE2_cast(*args): <NEW_LINE> <INDENT> return _itkDilateObjectMorphologyImageFilterPython.itkDilateObjectMorphologyImageFilterID2ID2SE2_cast(*args) | itkDilateObjectMorphologyImageFilterID2ID2SE2_cast(itkLightObject obj) -> itkDilateObjectMorphologyImageFilterID2ID2SE2 | 625941e2507cdc57c630709d |
def _translate_y_impl(pil_img, level): <NEW_LINE> <INDENT> level = int_parameter(level, 10) <NEW_LINE> if random.random() > 0.5: <NEW_LINE> <INDENT> level = -level <NEW_LINE> <DEDENT> return pil_img.transform((IMAGE_SIZE, IMAGE_SIZE), Image.AFFINE, (1, 0, 0, 0, 1, level)) | Applies PIL TranslateY to `pil_img`.
Translate the image in the vertical direction by `level`
number of pixels.
Args:
pil_img: Image in PIL object.
level: Strength of the operation specified as an Integer from
[0, `PARAMETER_MAX`].
Returns:
A PIL Image that has had TranslateY applied to it. | 625941e2627d3e7fe0d6920c |
def register_tasks(self, tasks, message='new task'): <NEW_LINE> <INDENT> for task in tasks: <NEW_LINE> <INDENT> assert task.id is None <NEW_LINE> self._db.register_task(task) <NEW_LINE> task._registrar = self <NEW_LINE> self.update_status(task, mahler.core.status.OnHold(message)) <NEW_LINE> self.add_tags(task, [task.na... | Notes
-----
There is no need to register a task again, only update moving parts | 625941e22c8b7c6e89b35b79 |
def denom(f): <NEW_LINE> <INDENT> return f.half_per(f.den) | Returns the denominator of ``f``. | 625941e221bff66bcd684d09 |
def tokens2n_grams(tokens, n): <NEW_LINE> <INDENT> if len(tokens) < n: <NEW_LINE> <INDENT> return list() <NEW_LINE> <DEDENT> grams = list() <NEW_LINE> if n <= 1: <NEW_LINE> <INDENT> for token in tokens: <NEW_LINE> <INDENT> if pu.findall(r'[a-zA-Z0-9]+', token) and not pu.is_stop_word(token, pu.my_stop_words): <NEW_LINE... | 从分词表中构造n-gram(bigram,trigram, ...);n=1时进行额外处理,包括去除停用词,判断单词是否含字母等
:param tokens: list,分词表,每个元素为str,表示一个分词
:param n: gram中分词的数量
:return: list,gram词表,每个元素为str,表示一个gram | 625941e2d4950a0f3b08c704 |
def identifyContent(img, chroma): <NEW_LINE> <INDENT> if chroma == 'alpha': <NEW_LINE> <INDENT> def column_is_empty(x): <NEW_LINE> <INDENT> for y in range(img.height()): <NEW_LINE> <INDENT> if QtGui.qAlpha(img.pixel(x, y)): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> de... | Taking a pixel at the give coord (or alpha), return the minimum rectangle containing content.
Args:
img: A Pixmap
chroma: Either a pixel representing the chromakey or 'alpha' to use the alpha channel. | 625941e2adb09d7d5db6cb47 |
def looper(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> for event in pygame.event.get(): <NEW_LINE> <INDENT> if event.type == pygame.QUIT: <NEW_LINE> <INDENT> pygame.quit() <NEW_LINE> quit() <NEW_LINE> <DEDENT> <DEDENT> glRotatef(1, 3, 1, 1) <NEW_LINE> glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) <N... | the while loop that is the application, listens for quit event, rotates
and redraws the cube | 625941e23346ee7daa2b3128 |
def hex_color(self): <NEW_LINE> <INDENT> return f'#{self.random_int(1, 16777215):06x}' | Generate a color formatted as a hex triplet. | 625941e255399d3f05588a70 |
def get_ctx() -> commands.Context: <NEW_LINE> <INDENT> frame = inspect.currentframe() <NEW_LINE> while frame: <NEW_LINE> <INDENT> _locals = dict(frame.f_locals) <NEW_LINE> for k, v in _locals.items(): <NEW_LINE> <INDENT> if isinstance(v, commands.Context): <NEW_LINE> <INDENT> return v <NEW_LINE> <DEDENT> <DEDENT> else:... | Attempts to retrieve discord context from the call stack. | 625941e2b830903b967e9cc1 |
def __SetTangentSpeed(self, *args, **kwargs): <NEW_LINE> <INDENT> return _Box2D.b2Contact___SetTangentSpeed(self, *args, **kwargs) | __SetTangentSpeed(b2Contact self, float32 speed) | 625941e21d351010ab855ed5 |
def _eq_delete_default_templates_contract(self): <NEW_LINE> <INDENT> _logger.info("** Deleting default email templates **") <NEW_LINE> email_templates = self.env['mail.template'].sudo().search([('eq_email_template_version', '=', False),('name','=','Email Contract Template')]) <NEW_LINE> for record in email_templates: <... | Wir löschen hier Default E-Mail Vorlage für die Sale, die wir durch unsere Version ersetzen | 625941e2d18da76e23532894 |
def recursive_aligned(symbol): <NEW_LINE> <INDENT> result = [] <NEW_LINE> next_symbol = symbol.next_aligned_symbol() <NEW_LINE> while next_symbol: <NEW_LINE> <INDENT> result.extend(generate(next_symbol)) <NEW_LINE> next_symbol = next_symbol.next_aligned_symbol() <NEW_LINE> <DEDENT> return result | Get the branch following symbol | 625941e24c3428357757c6e0 |
def test_clf(clf, X, y=empty): <NEW_LINE> <INDENT> pred = clf.predict(X) <NEW_LINE> if y != empty: <NEW_LINE> <INDENT> print('Accuracy: {0}'.format((y == pred).sum() / y.size)) <NEW_LINE> print('Confusion matrix:\n', confusion_matrix(y, pred)) <NEW_LINE> print('Classification report:\n', classification_report(y, pred))... | Tests the k-nearest neighbors classifier and evaluate its performance
using different metrics. | 625941e250485f2cf553d155 |
def on_state_changed(self, new_state: ApplicationState): <NEW_LINE> <INDENT> if new_state == ApplicationState.STARTUP: <NEW_LINE> <INDENT> self.save_button.Disable() <NEW_LINE> self.cancel_button.Disable() <NEW_LINE> self.pause_button.Disable() <NEW_LINE> self.convert_button.Disable() <NEW_LINE> <DEDENT> elif new_state... | A state change was passed to the ConversionPanel.
:param new_state: The recorded ApplicationState.
:return: None | 625941e2379a373c97cfaf01 |
def select_time(timeType = "下单时间",dateType = "全部"): <NEW_LINE> <INDENT> dateDict = {"今日":0, "昨日":1, "最近7日":2, "最近30日":3, "全部":4, "自定义":5} <NEW_LINE> Select(browser.find_element_by_name("time_type")).select_by_visible_text(timeType) <NEW_LINE> try: <NEW_LINE> <INDENT> browser.find_element_by_id("reservationtime").click(... | 时间选择
:param timeType: 1.下单时间 2.派单时间 3.付款时间 4.完成时间
:param userDefined: 0.今日 1.昨日 2.最近7日 3.最近30日 4.全部 5.自定义
:return: | 625941e2b5575c28eb68e3be |
def p_mathterm_single(p): <NEW_LINE> <INDENT> p[0] = ('mathterm', p[1]) | mathterm : NUMBER
| ID
| func
| binop
| condterm | 625941e271ff763f4b549a4c |
def input_fn(filenames, labels, batch_size, num_epochs=1): <NEW_LINE> <INDENT> filenames = tf.convert_to_tensor(filenames, dtype=tf.string) <NEW_LINE> labels = tf.convert_to_tensor(labels, dtype=tf.int32) <NEW_LINE> dataset = tf.data.Dataset.from_tensor_slices((filenames, labels)) <NEW_LINE> dataset = dataset.map(_pars... | Store image and label in tfrecor format.
Return: | 625941e25fc7496912cc3d38 |
def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> co_connected = getattr(context['object'], 'taken' if self.profile_type == 'student' else 'taught', object) <NEW_LINE> context['classoffers'] = co_connected.all() <NEW_LINE> context['resources'] = self.make_... | Modify the context | 625941e2377c676e91272562 |
def shunting_yard_ast(infix_string): <NEW_LINE> <INDENT> root = None <NEW_LINE> ops = [] <NEW_LINE> unprocessed = [] <NEW_LINE> for c in infix_string: <NEW_LINE> <INDENT> if c.isnumeric(): <NEW_LINE> <INDENT> unprocessed.append(Node(c)) <NEW_LINE> <DEDENT> elif c != ' ': <NEW_LINE> <INDENT> while not can_push_op_to_sta... | Return an AST representation (more specifically, a root of instance
anytree.Node of the infix input
expression (containing constants only). | 625941e291f36d47f21ac8b1 |
def get_gpu_info(idx=-1): <NEW_LINE> <INDENT> return a.get_gpu_info(idx) | Get GPU info.
:param idx: GPU index, or -1 for current device
:type idx: :class:`int`
:returns: :class:`str` -- GPU info | 625941e266673b3332b9244c |
def predict_many(data_source, saved_model_tag=None, ensemble=None, client=None, serialize=None, to_raster=True, elm_predict_path=None): <NEW_LINE> <INDENT> env = parse_env_vars() <NEW_LINE> elm_predict_path = elm_predict_path or env.get('ELM_PREDICT_PATH') <NEW_LINE> if serialize and elm_predict_path and not os.path.ex... | See elm.pipeline.Pipeline.predict_many method
| 625941e223849d37ff7b3447 |
def delete_isms_signature( self, req: typing.Optional[dict] = None, **kwargs ) -> dict: <NEW_LINE> <INDENT> d = { "ProjectId": self.config.project_id, } <NEW_LINE> req and d.update(req) <NEW_LINE> d = apis.DeleteISMSSignatureRequestSchema().dumps(d) <NEW_LINE> resp = self.invoke("DeleteISMSSignature", d, **kwargs) <NEW... | DeleteISMSSignature - 调用接口DeleteISMSSignature删除视频短信签名
**Request**
- **ProjectId** (str) - (Config) 项目ID,不填写为默认项目,子帐号必须填写。 请参考 `GetProjectList接口 <https://docs.ucloud.cn/api/summary/get_project_list>`_
- **SigIds** (list) - (Required) 签名ID,支持以数组的方式,举例,以SigIds.0、SigIds.1...SigIds.N方式传入
**Response**
- **Message** (str)... | 625941e299fddb7c1c9de749 |
def output_sql( self, sql: str, arg_list: List[SQL_CONTENT] = None ) -> Tuple: <NEW_LINE> <INDENT> if arg_list: <NEW_LINE> <INDENT> self.cur.execute(sql, arg_list) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.cur.execute(sql) <NEW_LINE> <DEDENT> result = self.cur.fetchall() <NEW_LINE> self.conn.commit() <NEW_LINE... | 输出查询内容,直接传入select的sql语句,用于查询
:param sql: select开头的sql语句
:param arg_list: 预处理参数,如果需要预处理查询,需要在sql语句中使用%s作为占位符
:return: 查询到的结果内容 | 625941e232920d7e50b2858e |
def _do_teardown(self, mode=None): <NEW_LINE> <INDENT> self.logger.info("Stopping all clusters...") <NEW_LINE> running_at_start = self.is_running() <NEW_LINE> if not running_at_start: <NEW_LINE> <INDENT> self.logger.warning("All clusters were expected to be running, but weren't.") <NEW_LINE> <DEDENT> teardown_handler =... | Shut down the clusters. | 625941e2be7bc26dc91cd9b4 |
def get_envelope(self, envelopeId): <NEW_LINE> <INDENT> if not self.account_url: <NEW_LINE> <INDENT> self.login_information() <NEW_LINE> <DEDENT> url = '/accounts/{accountId}/envelopes/{envelopeId}' .format(accountId=self.account_id, envelopeId=envelopeId) <NEW_LINE> return self.get(url) | GET {account}/envelopes/{envelopeId} and return JSON. | 625941e2596a897236089e76 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, DataStreamSummary): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941e2b57a9660fec33c44 |
def checkPermissions(self, projID, operation, flags = None): <NEW_LINE> <INDENT> if flags is None: <NEW_LINE> <INDENT> flags = self.getPermissions(projID) <NEW_LINE> <DEDENT> if operation in flags: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise DBAuthoritiesException('Denied operation ... | Checks permission to perform operation
Input:
projID - ID of project
operation - operation code
flags - permissions obtained earlier with getPermissions call
Output:
1 if permission granted, DBAuthoritiesException otherwise | 625941e2a219f33f34628d1f |
def statusMinimal() -> dict: <NEW_LINE> <INDENT> json = data().get(connexion.request.headers['Host']) <NEW_LINE> minimal = { 'open': json['state']['open'], 'icon': json['state']['icon']['open'] if json['state']['open'] else json['state']['icon']['closed'] } <NEW_LINE> return minimal | Response the request for /status-minimal.json with
a minimal status output.
Returns
-------
dict
Dictionary with minimal status data for the requested host | 625941e2c4546d3d9de72df2 |
def factorial(number): <NEW_LINE> <INDENT> if number == 0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return number*factorial(number-1) | this is a recursive function that can get the factorial(n!) of any
number. factorial is the multiplication of positive integers between
1 and the number n. i.e 3! = 1*2*3 the ans is 6 | 625941e2091ae35668667313 |
def parse_image_part(msg_part) : <NEW_LINE> <INDENT> imgtype = msg_part.get_content_subtype() <NEW_LINE> imgtype = imgtype.lower() <NEW_LINE> if imgtype not in ( "pjpeg", "jpeg", "gif" ) : <NEW_LINE> <INDENT> raise ImageTypeNotAllowed <NEW_LINE> <DEDENT> image = msg_part.get_payload(decode=1) <NEW_LINE> return (image,i... | Process part of a message known to be an image. | 625941e2d164cc617578310a |
def convertsigmatopres_mp(inTuple): <NEW_LINE> <INDENT> return convertsigmatopres(inTuple[0], inTuple[1], inTuple[2], modelid=inTuple[3], hCoeffs=inTuple[4], ) | Wrapper for multiprocessing of convertsigmatopres
Version Date: 2017-09-06 | 625941e2d8ef3951e32438f8 |
def plot_force_lvl1_angular(force, r, theta): <NEW_LINE> <INDENT> N_r = len(r)/2 <NEW_LINE> N_theta = len(theta)/2 <NEW_LINE> surface = force_matrix(force, N_r, N_theta) <NEW_LINE> fig = plt.figure() <NEW_LINE> ax = fig.add_subplot(111) <NEW_LINE> ax.set_title("force map (angular component)") <NEW_LINE> ax.set_xlabel('... | Plots the force on a r vs. theta plot | 625941e2d6c5a10208144408 |
def find_sr_by_uuid(session, sr_uuid): <NEW_LINE> <INDENT> for sr_ref, sr_rec in session.get_all_refs_and_recs('SR'): <NEW_LINE> <INDENT> if sr_rec['uuid'] == sr_uuid: <NEW_LINE> <INDENT> return sr_ref <NEW_LINE> <DEDENT> <DEDENT> return None | Return the storage repository given a uuid. | 625941e2046cf37aa974d0ff |
def get_perimeter(self): <NEW_LINE> <INDENT> perm = 0.0 <NEW_LINE> length = len(self.vertices) - 1 <NEW_LINE> for i in range(length): <NEW_LINE> <INDENT> point1 = self.vertices[i] <NEW_LINE> point2 = self.vertices[i + 1] <NEW_LINE> perm += point1.simple_distance(point2) <NEW_LINE> <DEDENT> perm += self.vertices[length]... | Finds the perimeter of the polygon
Returns
-------
float
The perimeter of the polygon | 625941e26e29344779a629cb |
def __init__(self, offset=None, length=None, location=None, content=None, context=None): <NEW_LINE> <INDENT> self.swagger_types = { 'offset': 'int', 'length': 'int', 'location': 'str', 'content': 'str', 'context': 'str' } <NEW_LINE> self.attribute_map = { 'offset': 'offset', 'length': 'length', 'location': 'location', ... | ContentMatch - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition. | 625941e2e5267d203edce053 |
def adapt_route_schema_for_activities(activities, field_list_type): <NEW_LINE> <INDENT> if not activities: <NEW_LINE> <INDENT> activities = [a for a in attributes.activities if a != 'paragliding'] <NEW_LINE> <DEDENT> fields = get_all_fields(fields_route, activities, field_list_type) <NEW_LINE> return restrict_schema(sc... | Get the schema for a set of activities.
`field_list_type` should be either "fields" or "listing". | 625941e23cc13d1c6d3c7733 |
def create_BasicRNN(hidden_dim, activation = 'sigmoid'): <NEW_LINE> <INDENT> if activation == 'sigmoid': <NEW_LINE> <INDENT> rnn_cell = tf.contrib.rnn.BasicRNNCell(num_units=hidden_dim, activation= tf.nn.sigmoid) <NEW_LINE> <DEDENT> elif activation == 'relu': <NEW_LINE> <INDENT> rnn_cell = tf.contrib.rnn.BasicRNNCell(n... | create BasicRNNCell object with specified activation function
input:
hidden_dim -- dimension of the last hidden layer
activation -- activation function used in the hidden layers i.e sigmoid/ relu/ elu/ leaky_relu/ tanh
output:
rnn_cell -- RNN cell object | 625941e267a9b606de4a8272 |
def average(a, b): <NEW_LINE> <INDENT> return (a + b) * 0.5 | Compute and return the arithmetic mean of a and b | 625941e25166f23b2e1a5514 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.