code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def group_names(self): <NEW_LINE> <INDENT> group_list=[] <NEW_LINE> for gname, info in self.xps.groups.items(): <NEW_LINE> <INDENT> group_list.append(gname) <NEW_LINE> count = 1 <NEW_LINE> self.dict_groupnames = {} <NEW_LINE> <DEDENT> for i in group_list: <NEW_LINE> <INDENT> self.dict_groupnames[count] = i <NEW_LINE> c... | Create dictionary of group names.
Default names are Group1, Group2, etc... | 625941d27b25080760e39603 |
def get_img_by_date(day, month, year): <NEW_LINE> <INDENT> garfield_page = get("https://garfield.com/comic/%s/%s/%s" % (year, month, day)) <NEW_LINE> bsoup = BeautifulSoup(garfield_page.content, "lxml") <NEW_LINE> status = garfield_page.status_code <NEW_LINE> if status == 200: <NEW_LINE> <INDENT> comic = bsoup.find('di... | Get the image by date
Return the url of the Garfield comic image for the desired date.
:param day: the day when the comic was published
:param month: the month when the comic was published
:param year: the year when the comic was published
:returns: url of the comic
:rtype: string | 625941d2091ae35668667107 |
@then('I should find that the {property_name} property has numeric value greater than or equal ' 'to {expected:d}') <NEW_LINE> def check_numeric_property_value(context, property_name, expected): <NEW_LINE> <INDENT> value = read_property_value_from_gremlin_response(context, property_name) <NEW_LINE> numeric = convert_to... | Check if the property has assigned numeric value that is greater than or equal to X. | 625941d226068e7796caee8a |
def get_actual_version(self): <NEW_LINE> <INDENT> return fs.youngest_rev(self.fs_ptr) | Get the actual version of the repostory
@return: youngest_rev | 625941d257b8e32f52483646 |
def test_get_allowed_rfids_has_null_terminator(self): <NEW_LINE> <INDENT> response = self.client.get('/door/1/getallowed/') <NEW_LINE> actual_rfids = response.content <NEW_LINE> self.assertEqual('\0', actual_rfids[-1:]) | Does get_allowed_rfids() return a rfids separated by spaces, with a
null terminator? | 625941d2283ffb24f3c55aaa |
def download_file(self, file_name: str, dest_path: str): <NEW_LINE> <INDENT> logger.info("Trying to download %s to %s", file_name, dest_path) <NEW_LINE> download_addr = urllib.parse.urljoin(self.download_url, 'file/{}/{}'.format(self.bucket_name, self._url_encode(file_name))) <NEW_LINE> headers = { 'Authorization': sel... | Download a file by name. | 625941d25e10d32532c5f0d1 |
def hash_password(plaintext, scheme = "pbkdf2"): <NEW_LINE> <INDENT> if scheme is None or scheme == "" or scheme == "plain": <NEW_LINE> <INDENT> return "plain:%s" % plaintext <NEW_LINE> <DEDENT> elif scheme == "pbkdf2": <NEW_LINE> <INDENT> PBKDF2_ITERATIONS = 10000 <NEW_LINE> PBKDF2_ALGORITHM = "sha1" <NEW_LINE> salt =... | Returns a one-way hash of a password string.
plaintext: The password to hash
scheme: md5, md5java, pbkdf2 or plain (no hash) | 625941d20fa83653e4657165 |
def get_order_dict(self): <NEW_LINE> <INDENT> return self.order_dict | Return all order variables as a dict for DB storage. | 625941d2f7d966606f6aa1af |
def get_hba_wwns(self, port_id, host_group_number): <NEW_LINE> <INDENT> url = '%(url)s/host-wwns' % { 'url': self.object_url, } <NEW_LINE> params = {"portId": port_id, "hostGroupNumber": host_group_number} <NEW_LINE> return self._get_objects(url, params=params) | Get a list of wwn information. | 625941d2f9cc0f698b1407a5 |
def __eq__(self, other): <NEW_LINE> <INDENT> if other == None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if (self.diatonic == other.diatonic and self.chromatic == other.chromatic): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | >>> a = Interval('a4')
>>> b = Interval('d5')
>>> c = Interval('m3')
>>> d = Interval('d5')
>>> a == b
False
>>> b == d
True
>>> a == c
False
>>> b in [a, c, d]
True | 625941d2656771135c3eba1a |
def _on_support(self): <NEW_LINE> <INDENT> QtGui.QDesktopServices.openUrl(QtCore.QUrl(self._bundle.support_url)) | Launch support url | 625941d266673b3332b9223c |
def vector3_init_xyz(vector, x, y, z): <NEW_LINE> <INDENT> vector.x = x <NEW_LINE> vector.y = y <NEW_LINE> vector.z = z <NEW_LINE> return | Redefine al vector "vector" como un punto en las coordenadas cartesianas
"x", "y" y "z". | 625941d226068e7796caee8b |
def add(self, state, action, reward, next_state, done): <NEW_LINE> <INDENT> self.memory.append( self.experience(state=state, action=int(action), reward=reward, done=int(done), next_state=next_state)) | Add a new experience into memory. | 625941d2851cf427c661a6b8 |
def normal_entropy(std): <NEW_LINE> <INDENT> var = std.pow(2) <NEW_LINE> entropy = 0.5 + 0.5 * torch.log(2 * var * math.pi) <NEW_LINE> return entropy.sum(1, keepdim=True) | entropy = log(sqrt(2 * e * pi) * std)
variables needed:
std: [batch_size x state_dim]
returns:
entropy: [batch_size x 1] | 625941d2a05bb46b383ec9cb |
def encipher_message(self, input_text, key, cipher_function): <NEW_LINE> <INDENT> key_index = 0 <NEW_LINE> output_text = "" <NEW_LINE> for char in input_text: <NEW_LINE> <INDENT> in_index = self.alphabet.find(char) <NEW_LINE> if in_index == -1: <NEW_LINE> <INDENT> output_text += char <NEW_LINE> <DEDENT> else: <NEW_LINE... | Manages calling cipher_function() repeatedly on entire input
to either encrypt of decrypt it. | 625941d229b78933be1e5855 |
def appendListItem(options, name, value): <NEW_LINE> <INDENT> if 'list' not in options: <NEW_LINE> <INDENT> options['list'] = dict() <NEW_LINE> <DEDENT> if name not in options['list']: <NEW_LINE> <INDENT> options['list'][name] = list() <NEW_LINE> <DEDENT> options['list'][name].append(value) | Add a list item to UCI options.
The way we store lists for UCI options is rather bizarre, so this function
takes care of that.
options: dictionary of options for a UCI section
name: string name of the list option
value: string value to append | 625941d263f4b57ef00012c1 |
def svn_repos_fs_get_inherited_props(*args): <NEW_LINE> <INDENT> return _repos.svn_repos_fs_get_inherited_props(*args) | svn_repos_fs_get_inherited_props(svn_fs_root_t root, char path, char propname, svn_repos_authz_func_t authz_read_func,
apr_pool_t result_pool,
apr_pool_t scratch_pool) -> svn_error_t | 625941d291f36d47f21ac69e |
def test_cli_xvfb(): <NEW_LINE> <INDENT> runner = CliRunner(echo_stdin=True) <NEW_LINE> xvfb_result = runner.invoke( jobautomate.commandline.cli, ['--debug', '--xvfb', 'Homer', 'Simpson', 'Chunkylover53@aol.com', 'Nuclear Technician', '.travis.yml'], input='no') <NEW_LINE> assert not xvfb_result.exception | Test the CLI with the --xvfb flag. | 625941d23eb6a72ae02ec68a |
def GetValue(self, primSpec): <NEW_LINE> <INDENT> raise NotImplementedError | Parameters
----------
primSpec : Sdf.PrimSpec
Returns
-------
Any | 625941d21f037a2d8b9463a8 |
def test_get_corporations_corporation_id_structures(self, api): <NEW_LINE> <INDENT> pass | Test case for get_corporations_corporation_id_structures
Get corporation structures | 625941d2b57a9660fec33a2f |
def save(self, delete_zip_import=True, *args, **kwargs): <NEW_LINE> <INDENT> super(Gallery, self).save(*args, **kwargs) <NEW_LINE> if self.zip_import: <NEW_LINE> <INDENT> zip_file = ZipFile(self.zip_import) <NEW_LINE> for name in zip_file.namelist(): <NEW_LINE> <INDENT> data = zip_file.read(name) <NEW_LINE> try: <NEW_L... | If a zip file is uploaded, extract any images from it and add
them to the gallery, before removing the zip file. | 625941d250485f2cf553cf45 |
def test_fs_volume_erase(basedir): <NEW_LINE> <INDENT> store = FileSystemStorage(basedir=basedir) <NEW_LINE> store.erase() <NEW_LINE> assert not os.path.isdir(basedir) | Test erasing the file system storage volume. | 625941d266656f66f7cbc356 |
def message_update(self, cr, uid, ids, msg, update_vals=None, context=None): <NEW_LINE> <INDENT> if isinstance(ids, (str, int, long)): <NEW_LINE> <INDENT> ids = [ids] <NEW_LINE> <DEDENT> if update_vals is None: <NEW_LINE> <INDENT> update_vals = {} <NEW_LINE> <DEDENT> update_vals.update({ 'email_from': msg.get('from'), ... | Override mail_thread message_update that is called by the mailgateway
through message_process.
This method updates the document according to the email. | 625941d2627d3e7fe0d68ffb |
def upsert(self, key, vals, buffer=False): <NEW_LINE> <INDENT> statements_and_parameters = [ (self._stmt_upsert, (self._ts(), self._key_encoder(key), self._val_encoder(val))) for val in vals ] <NEW_LINE> if buffer: <NEW_LINE> <INDENT> self._buffer(statements_and_parameters) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>... | Upsert an iterable of values with the same key.
Note: this is used when treating a Cassandra partition as a set. Since we upsert data
we never store duplicates. In this case the timestamp loses its meaning as we
are not interested in sorting records anymore (it is a set after all) and we can
safely overwri... | 625941d2a934411ee375183e |
def get_object_content(event): <NEW_LINE> <INDENT> dict_event = event['Records'][0] <NEW_LINE> s_object_name = dict_event['s3']['object']['key'] <NEW_LINE> s_bucket = dict_event['s3']['bucket']['name'] <NEW_LINE> s_content = s3_download_to_string(s_bucket, s_object_name) <NEW_LINE> return s_content | 從 s3產生出來的event 取出我們需要處理的那個檔案 | 625941d23317a56b86939e01 |
def plotAllData(self, allF=True, orientation='horizontal', outname=None, show=False, figsize=(11, 6)): <NEW_LINE> <INDENT> if self.x is None: <NEW_LINE> <INDENT> raise Exception("No measurement position array x given") <NEW_LINE> <DEDENT> freq = self.freq() <NEW_LINE> np = 2 <NEW_LINE> if self.ERR is not None: <NEW_LIN... | Plot data along a profile as image plots for IP and OP | 625941d24f6381625f114be6 |
def __init__(self, channel): <NEW_LINE> <INDENT> self.isPublicIfl = channel.unary_unary( '/interface.PublicIflService/isPublicIfl', request_serializer=dcd__service__pb2.InterfaceLogicalConfig.SerializeToString, response_deserializer=dcd__service__pb2.PublicIflResp.FromString, ) | Constructor.
Args:
channel: A grpc.Channel. | 625941d255399d3f0558885f |
def createObjects(self): <NEW_LINE> <INDENT> self.bno055 = BNO055() <NEW_LINE> self.logger = logging.getLogger("robot") <NEW_LINE> self.sd = NetworkTable.getTable('SmartDashboard') <NEW_LINE> self.joystick = wpilib.Joystick(0) <NEW_LINE> self.gamepad = wpilib.Joystick(1) <NEW_LINE> self.pressed_buttons_js = set() <NEW_... | Create motors and stuff here | 625941d25166f23b2e1a5304 |
def _update_sig(self, m, key): <NEW_LINE> <INDENT> if self.sig_alg is None: <NEW_LINE> <INDENT> self.sig_val = key.sign(m, t='pkcs', h='tls') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> h = _tls_hash_sig[self.sig_alg].split('+')[0] <NEW_LINE> self.sig_val = key.sign(m, t='pkcs', h=h) | Sign 'm' with the PrivKey 'key' and update our own 'sig_val'.
Note that, even when 'sig_alg' is not None, we use the signature scheme
of the PrivKey (neither do we care to compare the both of them). | 625941d25510c4643540f58d |
def str_entropies(counts, joint_counts, n_angles): <NEW_LINE> <INDENT> entropies = np.zeros(n_angles) <NEW_LINE> joint_entropies = np.zeros((n_angles,n_angles)) <NEW_LINE> for i in range(n_angles): <NEW_LINE> <INDENT> entropies[i] = occurences_to_entropies(counts[i]) <NEW_LINE> joint_entropies[i,i] = entropies[i] <NEW_... | STRUCTURAL CORRELATION METHOD: Given the counts, jointcounts, and n_angles values, computes the entropies for each diehdral
Parameters
-----------------
counts - the counts matrices for each dihedral, output of
str_states_to_counts
joint_counts - joint count matrices for each pair of dihedrals, each
matrix i... | 625941d282261d6c526ab64b |
def unpack(self, buf, offset): <NEW_LINE> <INDENT> element_hdr = unpack_from("<LLLLL", buf, offset) <NEW_LINE> type_class = element_hdr[0] <NEW_LINE> self.element_type = type_class & 0x000000ff <NEW_LINE> self.element_class = (type_class >> 8) & 0x00ffffff <NEW_LINE> self.element_id = element_hdr[1] <NEW_LINE> self.ele... | Unpack an element header from an FFFF header buffer
Unpacks an element header from an FFFF header buffer at the specified
offset. Returns a flag indicating if the unpacked element is an
end-of-table marker | 625941d2be383301e01b562f |
def items(testid: str) -> List[str]: <NEW_LINE> <INDENT> langs = BeautifulSoup(search_page(), "html.parser").find_all(testid=testid) <NEW_LINE> return [el.get("value") for el in langs[0].find_all("option")] | Retrieve all search options for a San Mateo Public Library search page | 625941d276e4537e8c35181e |
def get_all_combinations(attr, include_empty = False): <NEW_LINE> <INDENT> if include_empty: <NEW_LINE> <INDENT> yield () <NEW_LINE> <DEDENT> seen = set() <NEW_LINE> for index in range(1, len(attr) + 1): <NEW_LINE> <INDENT> product_arg = [attr for _ in range(index)] <NEW_LINE> for item in itertools.product(*product_arg... | Provides an iterator for all combinations of a set of attributes. For
instance...
::
>>> list(test.get_all_combinations(['a', 'b', 'c']))
[('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]
:param list attr: attributes to provide combinations for
:param bool include_empty: includes an e... | 625941d2dc8b845886cb56e0 |
def __init__( self, system_tags: List[str], opt_filename: str = "test.opt" ) -> None: <NEW_LINE> <INDENT> self.opt_filename = opt_filename <NEW_LINE> self.system_tags = system_tags | Initialize a OptfileTestControlCreator instance.
:param system_tags: Tags to forward to OptFileParse().
:param opt_filename: Name of the file to parse, relative to the test
directory. | 625941d2bd1bec0571d907db |
def __init__(self, assembly): <NEW_LINE> <INDENT> assert isinstance(assembly, Assembly), 'Invalid assembly %s' % assembly <NEW_LINE> self.assembly = assembly <NEW_LINE> self.contextsUsing = {} | Construct the included branch.
@param assembly: Container
The processors assembly to be included. | 625941d22ae34c7f2600d2dc |
def create_subexon_table(transcript_data, merge_non_redundant=True): <NEW_LINE> <INDENT> subexon_data_frames = [] <NEW_LINE> for _, gene_df in transcript_data.groupby('GeneID'): <NEW_LINE> <INDENT> exon_df = gene_df.drop_duplicates(subset='ExonID') <NEW_LINE> exon_df.set_index('ExonID', inplace=True) <NEW_LINE> exon_df... | Return a subexon table.
If merge_non_redundant is True (default), contiguous subexons that
appear together in only one exon are merged/joint. This happens
because subexons are defined using coordinates at the genomic level
to reduce redundancy.
However, some subexons does not have the same protein sequence because
of ... | 625941d2fbf16365ca6f6372 |
def new(self, obj): <NEW_LINE> <INDENT> string = obj.__class__.__name__ + '.' + obj.id <NEW_LINE> FileStorage.__objects[string] = obj | adds new object to the __object dict | 625941d2e5267d203edcde47 |
def all_keys_for_types(self) -> Iterator[StorageKey]: <NEW_LINE> <INDENT> for key_type in sorted(self.constructors.key_types): <NEW_LINE> <INDENT> yield from self.keys_for_type(key_type) <NEW_LINE> <DEDENT> for key_type in sorted(self.constructors.key_types_from_curve): <NEW_LINE> <INDENT> for curve in sorted(self.cons... | Generate test keys covering key types and their representations. | 625941d201c39578d7e74fe6 |
def post(self): <NEW_LINE> <INDENT> input_username = self.request.get("username") <NEW_LINE> input_password = self.request.get("password") <NEW_LINE> input_verify = self.request.get("verify") <NEW_LINE> input_email = self.request.get("email") <NEW_LINE> params = dict( username=input_username, email=input_email ) <NEW_L... | POST method for the /signup action.
Validates the inputs and redirects the user to the welcome page if
validations are ok.
If not, render the signup page, keeping the username and email values,
and show error messages. | 625941d20a50d4780f66703e |
def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, VehicleStatsFuelPercent): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | Returns true if both objects are not equal | 625941d2099cdd3c635f0e06 |
def test_no_response(self): <NEW_LINE> <INDENT> middleware = self.create_simple_middleware() <NEW_LINE> url = 'http://admin_host:8774/v2/' + self.project_id + '/servers' <NEW_LINE> req = webob.Request.blank(url, environ=self.get_environ_header('GET'), remote_addr='192.168.0.1') <NEW_LINE> req.environ['audit.context'] =... | Ensure event is created even for missing response. | 625941d23617ad0b5ed680a2 |
def wq_sample_parameter_list(base_url, hts, site): <NEW_LINE> <INDENT> url = build_url(base_url, hts, 'GetData', site, 'WQ Sample') <NEW_LINE> with urllib.request.urlopen(url) as req: <NEW_LINE> <INDENT> tree1 = ET.parse(req) <NEW_LINE> <DEDENT> if tree1.find('Error') is not None: <NEW_LINE> <INDENT> raise ValueError('... | Function to query a Hilltop server for the WQ sample parameter summary of a site.
Parameters
----------
base_url : str
root url str. e.g. http://wateruse.ecan.govt.nz
hts : str
hts file name including the .hts extension. Even if the file to be accessed is a dsn file, it must still have an hts extension for the... | 625941d216aa5153ce362623 |
def t_NIL(t): <NEW_LINE> <INDENT> t.value = None <NEW_LINE> return t | nil | 625941d2167d2b6e31218d41 |
def increment(self, minor=False): <NEW_LINE> <INDENT> major = self.major <NEW_LINE> if minor: <NEW_LINE> <INDENT> minor = self.minor + 1 <NEW_LINE> patch = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> minor = self.minor <NEW_LINE> patch = self.patch + 1 <NEW_LINE> <DEDENT> return self.__class__(major, minor, patch) | Returns a new object | 625941d2b5575c28eb68e1ac |
def available_with_http_info(self, **kwargs): <NEW_LINE> <INDENT> all_params = [] <NEW_LINE> all_params.append('callback') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> params = locals() <NEW_LINE> for key, val in iteritems(params['kwargs']): <NEW_LINE> <INDENT> if key not in all_params: <NEW_LINE> ... | Get all available output modules
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.available_with_http_info(cal... | 625941d2507cdc57c6306e88 |
def setDigitalOutput(self, bitNumber: int, state: int): <NEW_LINE> <INDENT> firstArgLimits = [0, 4] <NEW_LINE> if bitNumber > 3: <NEW_LINE> <INDENT> secondArgLimits = [0, 15] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> secondArgLimits = [0, 1] <NEW_LINE> <DEDENT> self.__sendCommand('setDigitalOutput', bitNumber, stat... | Sends command which sets digital inputs defined with the bitNumber argument to the desired state
Args:
bitNumber: Number of the bit (0, 1, 2, 3). If > 3, state argument sets multiple bits
state: State of the bit defined with bitNumber
Returns:
N/A | 625941d2293b9510aa2c3440 |
def handleSimulation( self ) : <NEW_LINE> <INDENT> self.__handleSimulation( self, None ) | handles simulation | 625941d23617ad0b5ed680a3 |
def legacy_search_user_by_email(self, email): <NEW_LINE> <INDENT> assert isinstance(email, (str, unicode)), email <NEW_LINE> headers, data = self.__requester.requestJsonAndCheck( "GET", "/legacy/user/email/" + email ) <NEW_LINE> return github.NamedUser.NamedUser(self.__requester, headers, Legacy.convertUser(data["user"... | :calls: `GET /legacy/user/email/:email <http://developer.github.com/v3/search/legacy>`_
:param email: string
:rtype: :class:`github.NamedUser.NamedUser` | 625941d27d43ff24873a2e4c |
def createUUT(): <NEW_LINE> <INDENT> return MainSequence('') | Returns an initialized object to test (no directory-path required for testing) | 625941d2925a0f43d254a023 |
def validateSourceDocuments(self): <NEW_LINE> <INDENT> isValid = True <NEW_LINE> if self.rbPrivateProperty.isChecked(): <NEW_LINE> <INDENT> if self.gpPrivateTaxInfo.isChecked(): <NEW_LINE> <INDENT> self.notifSourceDoc.clear() <NEW_LINE> if str(self.txtCFBPAmount.text()) == "": <NEW_LINE> <INDENT> self.txtCFBPAmount.set... | Basically validates the entry of tax information. | 625941d25fdd1c0f98dc03df |
def _head_package(self, safe_name, filename): <NEW_LINE> <INDENT> package_key = '{0}{1}/{2}'.format(self.prefix, safe_name, filename) <NEW_LINE> logger.info('Checking {0}'.format(package_key)) <NEW_LINE> try: <NEW_LINE> <INDENT> return self.client.head_object(Bucket=self.bucket, Key=package_key) <NEW_LINE> <DEDENT> exc... | Upload a single package to S3 | 625941d28c0ade5d55d3eb67 |
def count_ways2(n): <NEW_LINE> <INDENT> if n < 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> elif n == 0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return count_ways2(n - 3) + count_ways2(n - 2) + count_ways2(n - 1) | Recursive, O(3^n) time | 625941d215baa723493c4121 |
def output_setup(self, action, output_id): <NEW_LINE> <INDENT> return self.mycodo.output_setup(action, output_id) | Add, delete, or modify a output in the running output controller | 625941d221bff66bcd684afd |
def findDisappearedNumbers2(self, nums): <NEW_LINE> <INDENT> l = [i for i in range (1, len(nums) + 1)] <NEW_LINE> s = set(l) <NEW_LINE> numsSet = set(nums) <NEW_LINE> return list(s - numsSet) <NEW_LINE> return nums | :type nums: List[int]
:rtype: List[int] | 625941d2097d151d1a223004 |
def SetATime(self, st_atime): <NEW_LINE> <INDENT> self.st_atime = st_atime | Set the self.st_atime attribute.
Args:
st_atime: The desired atime. | 625941d2c4546d3d9de72be0 |
def mie_internal(self, k, lmin, lmax, r): <NEW_LINE> <INDENT> eps_e, mu_e = self.mat2.epsilon(k), self.mat2.mu(k) <NEW_LINE> ne = np.sqrt(eps_e*mu_e) <NEW_LINE> eps_i, mu_i = self.mat1.epsilon(k), self.mat1.mu(k) <NEW_LINE> ni = np.sqrt(eps_i*mu_i) <NEW_LINE> kr = k*r <NEW_LINE> iv_i, kv_i = bessel_sk.mie_bessels(kr*ni... | Scaled TE and TM Mie coefficients for imaginary wavenumbers k
are returned together with the logarithm of the scaling factor.
The scaling is necessary since Mie-coefficients are numerically
ill-behaved at imaginary arguments.
k has to be a one-dimensional numpy nd.array, lmin, lmax integers
and is generally supposed ... | 625941d24527f215b584c601 |
def __init__( self, aPCA, aIndex, aRange ): <NEW_LINE> <INDENT> super(extension, self).__init__() <NEW_LINE> self._pca = aPCA <NEW_LINE> self._index = aIndex <NEW_LINE> self._range = aRange <NEW_LINE> self.speed = 0.0 | aPCA = pca9685, pin index for pca, rate in range/second and tuple of ranges (min, center, max). | 625941d2442bda511e8be5c3 |
def bandshift(m,s,Nmax=10): <NEW_LINE> <INDENT> return np.sum(vecOverlap(rangeNot2(0,Nmax,m),s)/(rangeNot2(0,Nmax,m)-m)) | This function calculates the contribution of |Psi^(1)> to <G|mu|Psi> for
1-particle states. See "derivation.pdf"
Inputs
m: Integer specifying the vibrational quanta of the unperturbed
1-particle state |Psi^(0)>
s: Float holding the HR factor of the molecule
Nmax: Integer specifyin... | 625941d2187af65679ca52cb |
def subnetwork(ntwk, ports, offby=1): <NEW_LINE> <INDENT> subntwk_name = (ntwk.name or 'p') + ''.join([str(index+offby) for index in ports]) <NEW_LINE> subntwk = Network(frequency=ntwk.frequency, z0=ntwk.z0[:,ports], name=subntwk_name) <NEW_LINE> subntwk.s = ntwk.s[npy.ix_(npy.arange(ntwk.s.shape[0]), ports, ports)] <N... | Returns a subnetwork of a given Network from a list of port numbers.
A subnetwork is Network which S-parameters corresponds to selected ports,
with all non-selected ports considered matched.
The resulting subNetwork is given a new Network.name property
from the initial name and adding the kept ports indices
(ex: 'dev... | 625941d28e71fb1e9831d954 |
def check_output(*popenargs, **kwargs): <NEW_LINE> <INDENT> process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) <NEW_LINE> output, unused_err = process.communicate() <NEW_LINE> retcode = process.poll() <NEW_LINE> if retcode: <NEW_LINE> <INDENT> cmd = kwargs.get("args") <NEW_LINE> if cmd is None: <N... | Minimal py 2.6 compatible version of subprocess.check_output()
Py2.6 does not have check_output.
Taken from https://gist.github.com/edufelipe/1027906 | 625941d2435de62698dfddf9 |
def inference(self, inputs): <NEW_LINE> <INDENT> with tf.variable_scope('lstm') as scope: <NEW_LINE> <INDENT> cells = rnn.MultiRNNCell( [self.lstm_cell() for _ in range(self.rnn_layers)]) <NEW_LINE> lstm_input = tf.unstack(inputs, num=self.num_steps, axis=1) <NEW_LINE> outputs, states = rnn.static_rnn( cell=cells, inpu... | Param: | 625941d2d4950a0f3b08c4f9 |
def interesting_train_type(self): <NEW_LINE> <INDENT> full_list = ['Meridian', 'EuroCity', 'EC', 'IC', 'InterCity'] <NEW_LINE> short_list = ['Meridian'] <NEW_LINE> if self.train_type in short_list: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | we are only interested in a few "products" / "train types", so let's just work on them | 625941d29c8ee82313fbb922 |
def test_US_01(self): <NEW_LINE> <INDENT> repository = Repository('../GedcomFiles/US_01.ged') <NEW_LINE> expected = ['Birthdate on Line: 21\nUS_01: Birthdate "2022-01-01" for individual id @I1@ is illeagal', 'Birthdate on Line: 156\nUS_01: Birthdate "2020-12-06" for individual id @I13@ is illeagal', 'On Line: 158\nUS_0... | The function is to test US_01 function | 625941d2d18da76e23532683 |
def api_get_available_dates(request): <NEW_LINE> <INDENT> json_obj = {} <NEW_LINE> if request.method == 'GET': <NEW_LINE> <INDENT> date_options = get_times() <NEW_LINE> dates = [] <NEW_LINE> for date in date_options: <NEW_LINE> <INDENT> dates.append(date[0]) <NEW_LINE> <DEDENT> json_obj = {"date_options":dates} <NEW_LI... | Return a JSON object that contains the list of all the available dates. Needs to be changed to be more dynamic. | 625941d28e05c05ec3eea521 |
def query_data(db_location,sql_cmd): <NEW_LINE> <INDENT> conn = None <NEW_LINE> try: <NEW_LINE> <INDENT> conn = create_connection(db_location) <NEW_LINE> cursor = conn.cursor() <NEW_LINE> cursor.execute(sql_cmd) <NEW_LINE> return cursor.fetchall() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> if conn: <NEW_LINE> <IN... | Insert data into a table
:param: db_location: location of the database file
:type: db_location: string
:param: sql_cmd: sql command to write it into the table
:type: sql_cmd: string
:return: rows that have returned from the queries | 625941d24e696a04525c95f7 |
def set_shift_week(self): <NEW_LINE> <INDENT> rule = r'([上下]+)(\d+)?个?(?:周|星期)([1-7天日]?)' <NEW_LINE> match = re.search(rule, self.key) <NEW_LINE> current_week = self.time.isoweekday() <NEW_LINE> if match: <NEW_LINE> <INDENT> count = match.group(1) <NEW_LINE> number = match.group(2) <NEW_LINE> day = match.group(3) <NEW_... | 替换日期
比如: 上个星期6、上两个星期3 | 625941d2796e427e537b0772 |
def get_object(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.request.user | 重写get_object方法,获取当前用户对象
update()中需要get_object获
:param args:
:param kwargs:
:return: | 625941d2090684286d50ee92 |
def getChecksByUser(self, sid, userId, date): <NEW_LINE> <INDENT> date = self.date.parse(date).date() <NEW_LINE> con = self._getDatabase() <NEW_LINE> try: <NEW_LINE> <INDENT> cs = self.checks._getCheckData(con, userId, date) <NEW_LINE> logging.debug(cs) <NEW_LINE> return cs <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDE... | obtener checks de un usuario a partir de cierta fecha
@param sid Identificacion de Session
@param userId Identificacion de usuario
@param date String con la fecha, en formato "Y-m-d", por ejemplo "2000-12-31" | 625941d207d97122c4178a39 |
def listen_serial_port( ser: serial.Serial, set_time_amount: int = 4, set_time: int = 5, set_reverse_time: bool = False, set_sum_time: bool = False, controller=remote_controller_one, *args, **kwargs ): <NEW_LINE> <INDENT> if not ser.is_open: <NEW_LINE> <INDENT> ser.open() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s... | Get data stream and write current time in json file.
params: serial.Serial obj.
return: None. | 625941d23cc13d1c6d3c7525 |
def get(self, *args, **kwargs): <NEW_LINE> <INDENT> results = self.search(*args, **kwargs) <NEW_LINE> num_results = len(results) <NEW_LINE> if num_results == 1: <NEW_LINE> <INDENT> return results[0] <NEW_LINE> <DEDENT> if num_results > 1: <NEW_LINE> <INDENT> raise MultipleObjectsFound() <NEW_LINE> <DEDENT> raise Object... | Get a single object.
This is a convenience wrapper for the search method that checks that
only one object was returned, and returns that single object instead
of a list. This method takes the exact same arguments as search. | 625941d229b78933be1e5856 |
def assertBondLength(self, positions, bond_length): <NEW_LINE> <INDENT> for p in positions: <NEW_LINE> <INDENT> distances = np.linalg.norm(p[1:] - p[:-1], axis=1) <NEW_LINE> max_deviation = np.max(abs(distances - bond_length)) <NEW_LINE> self.assertLess(max_deviation, 1e-10) | Assert that distance between monomers is bond_length. | 625941d210dbd63aa1bd2d4f |
def gen_sample_data(app): <NEW_LINE> <INDENT> with app.app_context(): <NEW_LINE> <INDENT> admin_role = Role(role_id='admin', description='Administrators') <NEW_LINE> user_role = Role(role_id='users', description='users') <NEW_LINE> admin_user = User( user_id='admin', name='The Administrator', password='admin', roles=[a... | Populate database with sample data | 625941d250812a4eaa59c4cc |
def __call__(self, sim): <NEW_LINE> <INDENT> if self.interval is not None and self.calls is None: <NEW_LINE> <INDENT> return (sim.current_step // self.interval + 1) * self.interval <NEW_LINE> <DEDENT> elif self.calls is not None: <NEW_LINE> <INDENT> interval = sim.steps // self.calls <NEW_LINE> return (sim.current_step... | Given a simulation instance `sim`, return the next step at which
the observer will be called. | 625941d245492302aab5e470 |
def add_action_level(self, level): <NEW_LINE> <INDENT> print('Action level add, level {}'.format(level)) <NEW_LINE> self.a_levels.append(set()) <NEW_LINE> for node in self.s_levels[level]: <NEW_LINE> <INDENT> node.show() <NEW_LINE> literal = None <NEW_LINE> print('- literal', node.literal, node.is_pos, node.symbol) <NE... | add an A (action) level to the Planning Graph
:param level: int
the level number alternates S0, A0, S1, A1, S2, .... etc the level number is also used as the
index for the node set lists self.a_levels[] and self.s_levels[]
:return:
adds A nodes to the current level in self.a_levels[level] | 625941d24a966d76dd5511bc |
def current_tab_changed(self, tab_index): <NEW_LINE> <INDENT> if tab_index == 0: <NEW_LINE> <INDENT> tab_widget = self.widget(1) <NEW_LINE> if isinstance(tab_widget, UserModuleAuthUI): <NEW_LINE> <INDENT> self.module_auth.current_user_id = None <NEW_LINE> self.module_auth.module_auth_table.cellChanged.disconnect() <NEW... | 当前标签改变去除新增加出来的标签 | 625941d263d6d428bbe4469b |
def shell_command(self,cmd): <NEW_LINE> <INDENT> self.__clean__() <NEW_LINE> self.run_cmd('shell %s' % cmd) <NEW_LINE> return self.__output | Executes a shell command
adb shell <cmd> | 625941d226238365f5f0f01b |
def get_community_names(): <NEW_LINE> <INDENT> ret = dict() <NEW_LINE> current_values = __salt__['reg.list_values']( _HKEY, _COMMUNITIES_KEY, include_default=False) <NEW_LINE> if isinstance(current_values, list): <NEW_LINE> <INDENT> for current_value in current_values: <NEW_LINE> <INDENT> if not isinstance(current_valu... | Get the current accepted SNMP community names and their permissions.
Returns:
dict: A dictionary of community names and permissions.
CLI Example:
.. code-block:: bash
salt '*' win_snmp.get_community_names | 625941d221a7993f00bc7e9d |
def gen(width, height, bg_color, fg_color, type_, n): <NEW_LINE> <INDENT> result = {'Screen': {'width': width, 'height': height, 'bg_color': bg_color, 'fg_color': fg_color}} <NEW_LINE> figures = [] <NEW_LINE> if n < 1: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif type_ == 'point': <NEW_LINE> <INDENT> gen_points(fi... | Generate file content: Screen and Figures specifications. | 625941d25fdd1c0f98dc03e0 |
def read_next(self): <NEW_LINE> <INDENT> if self.__dataset is None: <NEW_LINE> <INDENT> raise IOError <NEW_LINE> <DEDENT> file_path = self.__dataset[self.__data_pointer][0] <NEW_LINE> label = self.__dataset[self.__data_pointer][1] <NEW_LINE> with wave.open(file_path, 'rb') as wavFile: <NEW_LINE> <INDENT> params = wavFi... | Return the next wave array.
The function cycles the data set specified in construction function.
:return: Return a tuple, consists of a 1-D numpy array containing wave data
and a scalar of ground truth. | 625941d285dfad0860c3b007 |
def log_context_counts(self, it): <NEW_LINE> <INDENT> _logger.debug('Context counts: %-10s: %s', quote(prefixfor(it)), self.s[it.value.id]) <NEW_LINE> return True | Visitor function to be used in traversal
to log context counts. | 625941d2627d3e7fe0d68ffc |
def set_allow_external(self, allow): <NEW_LINE> <INDENT> self._real_http = allow | Set flag to authorize external calls when no matching mock.
Will raise a ConnectionError otherwhise. | 625941d266656f66f7cbc357 |
def wait_for_metadata_service(self): <NEW_LINE> <INDENT> metadata_url = "{}/{}/meta-data/instance-id".format( self.metadata_url, self.api_version) <NEW_LINE> url, _response = url_helper.wait_for_url( urls=[metadata_url], max_wait=self.url_max_wait, timeout=self.url_timeout, status_cb=LOG.critical) <NEW_LINE> return boo... | Wait for the metadata service to be reachable. | 625941d2eab8aa0e5d26dd04 |
def utility(board): <NEW_LINE> <INDENT> winner_value = winner(board) <NEW_LINE> if winner_value == 'X': <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> elif winner_value == 'O': <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 | Returns 1 if X has won the game, -1 if O has won, 0 otherwise. | 625941d273bcbd0ca4b2c222 |
def __array_finalize__(self, obj): <NEW_LINE> <INDENT> objdict = getattr(obj, '__dict__', None) <NEW_LINE> if obj is None or objdict is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> objaxes = getattr(obj, 'axes', None) <NEW_LINE> objslic = getattr(obj, '_slic', None) <NEW_LINE> for key in iter(objdict): <NEW_LIN... | see https://docs.scipy.org/doc/numpy/user/basics.subclassing.html
self is the new object; obj is the original object
type(self) is always Signal subclass
type(obj) is None for explicit constructor like a = Signal(...)
is ndarray for "view casting"
is type(self) for slicing or copy | 625941d2be7bc26dc91cd7aa |
def load_method(state, arg): <NEW_LINE> <INDENT> o = state.stack.pop() <NEW_LINE> name = state.get_name(arg) <NEW_LINE> if isinstance(o, Const): <NEW_LINE> <INDENT> method = Const(getattr(o.value, name)) <NEW_LINE> <DEDENT> elif isinstance(o, typehints.AnyTypeConstraint): <NEW_LINE> <INDENT> method = typehints.Any <NEW... | Like load_attr. Replaces TOS object with method and TOS. | 625941d20a50d4780f66703f |
def check_send_data_unit(self, data_unit): <NEW_LINE> <INDENT> if not data_unit.consistent: <NEW_LINE> <INDENT> self.logger.warning( 'Sending data unit with internal inconsistency: {}' .format(data_unit) ) <NEW_LINE> self.sender_counter['warning_inconsistent'] += 1 <NEW_LINE> <DEDENT> data_unit.buffer | Check the buffer of the data unit to be sent. | 625941d2fbf16365ca6f6373 |
def serve_forever(self, poll_interval=0.5): <NEW_LINE> <INDENT> self.__ws_serving = True <NEW_LINE> self.__ws_is_shut_down.clear() <NEW_LINE> handle_request = self.handle_request <NEW_LINE> if hasattr(self, '_handle_request_noblock'): <NEW_LINE> <INDENT> handle_request = self._handle_request_noblock <NEW_LINE> <DEDENT>... | Override socketserver.BaseServer.serve_forever. | 625941d2f548e778e58cd72a |
def cautaNota(self,studID,nrLab_nrPb): <NEW_LINE> <INDENT> for nota in self._listaNote: <NEW_LINE> <INDENT> if nota.getStudentID()==studID and nota.getNrLab_nrPb==nrLab_nrPb: <NEW_LINE> <INDENT> return nota | READ | 625941d226068e7796caee8c |
def agents_with_type(agents, agent_type='organization'): <NEW_LINE> <INDENT> agent_type = decode_utf8(agent_type) <NEW_LINE> for _agent in agents: <NEW_LINE> <INDENT> agent_name = _agent.findtext(premis_ns('agentName')) <NEW_LINE> _agent_type = _agent.findtext(premis_ns('agentType')) <NEW_LINE> if _agent_type == agent_... | Return all agents from list of `agents` with given `agent_type`.
:task_report: Report to search from
:returns: Generator object which iterates all (agent_type, agent_name) | 625941d2d8ef3951e32436ea |
def spring_mass_system(mbk): <NEW_LINE> <INDENT> m,b,k = mbk <NEW_LINE> return signal.lti([1.], mbk) | transfer function representation | 625941d28a43f66fc4b54210 |
def verify_version(required, version, name): <NEW_LINE> <INDENT> if version < required: <NEW_LINE> <INDENT> logger = logging.getLogger(name=__name__) <NEW_LINE> logger.error("Clang version is not compatible! " "Version required: %s", required) <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> return version, name | Verifies that version is at least required. | 625941d257b8e32f52483648 |
def backup_CSV(): <NEW_LINE> <INDENT> clear() <NEW_LINE> try: <NEW_LINE> <INDENT> with open('a.csv', mode='w', newline='') as csv_file: <NEW_LINE> <INDENT> fieldnames = ['product_id', 'product_name', 'product_quantity', 'product_price', 'date_updated'] <NEW_LINE> writer = csv.DictWriter(csv_file, fieldnames=fieldnames)... | Create a backup of the CSV file | 625941d2091ae35668667109 |
def run(self,frame=None): <NEW_LINE> <INDENT> import sys <NEW_LINE> if frame is None: <NEW_LINE> <INDENT> frame = sys._getframe().f_back <NEW_LINE> <DEDENT> self.n = 0 <NEW_LINE> while frame: <NEW_LINE> <INDENT> frame = frame.f_back <NEW_LINE> self.n += 1 <NEW_LINE> <DEDENT> sys.settrace(self.dispatch) | Trace from the given frame or the caller's frame. | 625941d26fece00bbac2d8ec |
def __iter__(self): <NEW_LINE> <INDENT> for x in range(len(self)): <NEW_LINE> <INDENT> yield self[x] | Iterate through the set of macros associated with the current archive. | 625941d28a43f66fc4b54211 |
def get(self, key, default=None): <NEW_LINE> <INDENT> already_present = False <NEW_LINE> if self._last_data: <NEW_LINE> <INDENT> if key in self._last_data: <NEW_LINE> <INDENT> default = self._last_data[key] <NEW_LINE> already_present = True <NEW_LINE> <DEDENT> <DEDENT> if key not in self._ns: <NEW_LINE> <INDENT> if sel... | Get Cell for a ``key``. During a computation cycle create
one if it doesn't exist yet. | 625941d2046cf37aa974cef3 |
def __init__(self, deep = False, pos = np.array([50., HEIGHT-50.]), direction = np.array([0.,-1.]), mode = None): <NEW_LINE> <INDENT> self.pos = pos <NEW_LINE> self.ang = 0 <NEW_LINE> self.dir = direction <NEW_LINE> self.isAlive = True <NEW_LINE> self.fitness = 0 <NEW_LINE> gene = [] <NEW_LINE> for i in range(GENE): <N... | constructor
pos : cartesian coordinate of center position
dir : norm vector from the center
ang : the turning angle of the agent [0,-1](North) is 0, positive if clockwise
isAlive : true if the agent is alive
fitness : the score of the agent, updates when it's dead
gene : the sequence of the commands that dictate the mo... | 625941d2be8e80087fb20dee |
def __init__(self, *, domain: str | None, identifier: str | None, **kwargs) -> None: <NEW_LINE> <INDENT> media_content_id = f"{URI_SCHEME}{domain or ''}" <NEW_LINE> if identifier: <NEW_LINE> <INDENT> media_content_id += f"/{identifier}" <NEW_LINE> <DEDENT> super().__init__(media_content_id=media_content_id, **kwargs) <... | Initialize media source browse media. | 625941d25e10d32532c5f0d3 |
def reconstruct(self, session, x): <NEW_LINE> <INDENT> return np.array(session.run(self.xr, {self.x: x})) | Reconstruct data.
:param session: The current tensorflow session holding the trained graph.
:return: A sample of generated data. | 625941d2596a897236089c6c |
def unhighlight(self, cr): <NEW_LINE> <INDENT> if not self.highlighted: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._draw(cr) <NEW_LINE> self.highlighted = False | Unhighilght this RingChartItem. | 625941d20383005118ecf78f |
def test_topic_one_queues_multiple_exchange(self): <NEW_LINE> <INDENT> conn = self.rpc.create_connection(FLAGS) <NEW_LINE> message = 'topic test message' <NEW_LINE> self.received_message_1 = None <NEW_LINE> self.received_message_2 = None <NEW_LINE> def _callback1(message): <NEW_LINE> <INDENT> self.received_message_1 = ... | Test sending to a topic exchange with one queues and several
exchanges | 625941d2851cf427c661a6ba |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.