code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def parse_rule(rule): <NEW_LINE> <INDENT> pattern, fn = rule <NEW_LINE> token_list = pattern.split() <NEW_LINE> parsed_rule = [([], [])] <NEW_LINE> for pos, token in enumerate(token_list): <NEW_LINE> <INDENT> if not is_token_valid(token): <NEW_LINE> <INDENT> raise ValueError('Parser only accepts token composed of lette... | Parse a rule (pattern, function) by turning the pattern into a list of token and adjusts the function when the
pattern has optional token (? operator)
:param rule: A rule is a tuple with a pattern as string and a function
:return: | 625941de4a966d76dd551344 |
def pushQueue(self, elem): <NEW_LINE> <INDENT> tmp = Node(elem) <NEW_LINE> if self.is_empty(): <NEW_LINE> <INDENT> self.front = tmp <NEW_LINE> self.rear = tmp <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.rear.next = tmp <NEW_LINE> self.rear = tmp <NEW_LINE> <DEDENT> self.length += 1 | 入队 | 625941de6fb2d068a760f3d4 |
def test_check_file_signature_file_object(self): <NEW_LINE> <INDENT> test_source = unittest.source <NEW_LINE> if not test_source: <NEW_LINE> <INDENT> raise unittest.SkipTest("missing source") <NEW_LINE> <DEDENT> with open(test_source, "rb") as file_object: <NEW_LINE> <INDENT> result = pyolecf.check_file_signature_file_... | Tests the check_file_signature_file_object function. | 625941deab23a570cc2504b7 |
def test_rm(self): <NEW_LINE> <INDENT> self.assertTrue(os.path.exists(self.newfile)) <NEW_LINE> nix.rm(self.newfile) <NEW_LINE> self.assertFalse(os.path.exists(self.newfile)) | Remove a file | 625941de187af65679ca5452 |
def r(num, places=4): <NEW_LINE> <INDENT> precision = '1.{0}'.format('0' * places) <NEW_LINE> return Decimal(num or 0).quantize(Decimal(precision), rounding=ROUND_HALF_UP) | Rounds and returns a Decimal | 625941debe383301e01b57b3 |
def setup_method(self): <NEW_LINE> <INDENT> self.hmc, self.hmc_resources = standard_test_hmc() <NEW_LINE> self.uris = ( (r'/api/partitions/([^/]+)', PartitionHandler), (r'/api/partitions/([^/]+)/operations/start', PartitionStartHandler), (r'/api/partitions/([^/]+)/operations/stop', PartitionStopHandler), ) <NEW_LINE> s... | Called by pytest before each test method.
Creates a Faked HMC with standard resources, and with
PartitionStartHandler and PartitionStopHandler. | 625941de462c4b4f79d1da03 |
def _calc_V_R(self): <NEW_LINE> <INDENT> def objective_func(R): <NEW_LINE> <INDENT> V = self._calc_V_from_R(R) <NEW_LINE> reff = self._calc_reff(R,V) <NEW_LINE> return reff <NEW_LINE> <DEDENT> Rlow, Rhigh = bracket_root( objective_func,1.001*self.a,init_step=1e-3) <NEW_LINE> R = brentq(objective_func,Rlow,Rhigh) <NEW_L... | Calculate V and R such that the potential has zero effective range. | 625941de5fc7496912cc3cb1 |
def fit(self, data): <NEW_LINE> <INDENT> data = np.asarray(data, dtype=np.double) <NEW_LINE> if self.verbose: <NEW_LINE> <INDENT> logger.info("Initializing clusters") <NEW_LINE> <DEDENT> if self.init == 'random': <NEW_LINE> <INDENT> self.cluster_centers_ = np.random.random( (self.n_clusters, data.shape[1]), dtype=np.do... | Fit the current model with the inputted data.
:param data: Samples to fit model with
:type data: ndarray(double), shape = (n_samples, n_features)
:returns: Trained MiniBatch instance
:rtype: MiniBatch | 625941de99fddb7c1c9de6c2 |
def getordersfilstr(ordtype=None, side=None, touch=False, ticks=None): <NEW_LINE> <INDENT> s = '' <NEW_LINE> if ordtype == 'Cancelled': <NEW_LINE> <INDENT> s += '''reason = 'Cancelled' ''' <NEW_LINE> <DEDENT> elif ordtype == 'New': <NEW_LINE> <INDENT> s += '''(reason = 'New Order' OR reason = 'Changed')''' <NEW_LINE> <... | string for ordersdf.filter(string)
Args:
ordtype: one of [None, 'New', 'Cancelled', 'Executed']
side: one of [None, 'Buy', 'Sell']
touch: bool | 625941decc40096d61595c82 |
def seed(self, a=None, version=2): <NEW_LINE> <INDENT> if a is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> a = int.from_bytes(_urandom(2500), 'big') <NEW_LINE> <DEDENT> except NotImplementedError: <NEW_LINE> <INDENT> import time <NEW_LINE> a = int(time.time() * 256) <NEW_LINE> <DEDENT> <DEDENT> if version == 2: ... | Initialize internal state from hashable object.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
For version 2 (the default), all of the bits are used if *a* is a str,
bytes, or bytearray. For version 1, the hash() of *a* is used instead.
If *a* is an ... | 625941de31939e2706e4d198 |
def __len__(self): <NEW_LINE> <INDENT> return len(self._service.configFiles) | Return the number of configuration files. | 625941de796e427e537b08fb |
def get_broadcast_bad_options_report(bad_options, is_set=False): <NEW_LINE> <INDENT> if not bad_options: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if is_set: <NEW_LINE> <INDENT> msg = BAD_OPTIONS_TITLE_SET <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = BAD_OPTIONS_TITLE <NEW_LINE> <DEDENT> for key, value... | Return a string to report bad options for broadcast cancel/clear. | 625941defbf16365ca6f64fc |
def __init__(self, ioc=None): <NEW_LINE> <INDENT> super(AsyncModule, self).__init__(ioc=ioc) <NEW_LINE> self.status = NOT_STARTED | Sets the current status and calls the superclass' init | 625941de5e10d32532c5f259 |
def FetchLogs(log_filter=None, log_ids=None, order_by='DESC', limit=None): <NEW_LINE> <INDENT> client = apis.GetClientInstance('logging', 'v2beta1') <NEW_LINE> messages = apis.GetMessagesModule('logging', 'v2beta1') <NEW_LINE> project = properties.VALUES.core.project.Get(required=True) <NEW_LINE> if order_by.upper() ==... | Fetches log entries.
This method uses Cloud Logging V2 api.
https://cloud.google.com/logging/docs/api/introduction_v2
Entries are sorted on the timestamp field, and afterwards filter is applied.
If limit is passed, returns only up to that many matching entries.
It is recommended to provide a filter with resource.typ... | 625941defff4ab517eb2f770 |
def boolean(value): <NEW_LINE> <INDENT> if isinstance(value, str): <NEW_LINE> <INDENT> if value.lower() in ["0", "no", "n", "false", "f", "off"]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif value.lower() in ["1", "yes", "y", "true", "t", "on"]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NE... | Test truth value.
Convert the string representation of a truth value, such as '0',
'1', 'yes', 'no', 'true', or 'false' to :class:`bool`. This
function is suitable to be passed as type to
:meth:`icat.config.BaseConfig.add_variable`. | 625941ded268445f265b51a1 |
def start(self): <NEW_LINE> <INDENT> self.content_def = DataManagementGUI <NEW_LINE> self.manifest_def = DataManagementManifest <NEW_LINE> self.content = self.content_def() <NEW_LINE> manifest = self.manifest_def() <NEW_LINE> self._manifest_id = manifest.id <NEW_LINE> self.workbench.register(manifest) | Start the Worknode instance.
This method will create the container content and register the
provided plugin with the workbench. | 625941de30c21e258bdfa7d2 |
def getPassingTones(score, dictKey=None, partNumToIdentify=None, unaccentedOnly=True): <NEW_LINE> <INDENT> if dictKey == None and unaccentedOnly: <NEW_LINE> <INDENT> dictKey = 'unaccentedPassingTones' <NEW_LINE> <DEDENT> elif dictKey == None: <NEW_LINE> <INDENT> dictKey = 'accentedPassingTones' <NEW_LINE> <DEDENT> test... | returns a list of all passing tones present in the score, as identified by
:meth:`~music21.voiceLeading.VerticalSliceTriplet.hasPassingTone`
>>> sc = stream.Score()
>>> sc.insert(0, meter.TimeSignature('2/4'))
>>> part0 = stream.Part()
>>> p0measure1 = stream.Measure(number=1)
>>> p0measure1.append(note.Note('A4', ... | 625941de956e5f7376d7119f |
def load(self): <NEW_LINE> <INDENT> self.model.load_weights(self.model_weights) <NEW_LINE> return self | Loads the saved weights for the model.
Returns self. | 625941de44b2445a339323c7 |
def package(self): <NEW_LINE> <INDENT> cmake = self._configure_cmake() <NEW_LINE> cmake.install() | Create a package using "cmake --build . --target install"
All installation files are defined in the CMakeLists.txt file rather
than in the conan package. | 625941defb3f5b602dac39ca |
def test_createprojectconfigfile_format( storage: DiskFileStorage, projectconfig: ProjectConfig ) -> None: <NEW_LINE> <INDENT> file = createprojectconfigfile(PurePath(), projectconfig) <NEW_LINE> with storage: <NEW_LINE> <INDENT> storage.add(file) <NEW_LINE> <DEDENT> path = storage.resolve(file.path) <NEW_LINE> lines =... | It formats the JSON file in a standard way. | 625941de10dbd63aa1bd2ed5 |
def input_productType(self, productType): <NEW_LINE> <INDENT> self.send_keys(self.productType_loc, productType) | 输入产品类型 | 625941de091ae3566866728c |
def __init__(self, ira, final_depdict, input_depnodes): <NEW_LINE> <INDENT> self._ira = ira <NEW_LINE> self._depdict = final_depdict <NEW_LINE> self._input_depnodes = input_depnodes <NEW_LINE> self._graph = None <NEW_LINE> self._has_loop = None | Instance a DependencyResult
@ira: IRAnalysis instance
@final_depdict: DependencyDict instance
@input_depnodes: set of DependencyNode instance | 625941de99cbb53fe6792f19 |
def forward(self, key, value, query, mask, similarity=None): <NEW_LINE> <INDENT> batch_size, seq_length, hidden_size = key.size() <NEW_LINE> heads_num = self.heads_num <NEW_LINE> per_head_size = self.per_head_size <NEW_LINE> def shape(x): <NEW_LINE> <INDENT> return x. contiguous(). v... | Args:
key: [batch_size x seq_length x hidden_size]
value: [batch_size x seq_length x hidden_size]
query: [batch_size x seq_length x hidden_size]
mask: [batch_size x 1 x seq_length x seq_length]
Returns:
output: [batch_size x seq_length x hidden_size] | 625941de85dfad0860c3b18f |
def ensure_full_range( self, backup: FullRange, rng: FullRange | str | None = None ) -> FullRange: <NEW_LINE> <INDENT> if isinstance(rng, str): <NEW_LINE> <INDENT> rng = FullRange(rng) <NEW_LINE> <DEDENT> return rng if rng else backup | Convenience method for ensuring that a range argument that could be None
or a string is always a FullRange.
Args:
rng (FullRange | str, optional): A manually generated FullRange or
valid FullRange string, defaults to None.
Returns:
FullRange: The passed FullRange, or the backup FullRange. | 625941de7b25080760e3978b |
def fun(x): <NEW_LINE> <INDENT> return np.sum(x), np.exp(np.sum(x))/(np.exp(np.sum(x))+1) | Function returning the parameters of the normal sampler.
mean = sum of elements of x
variance = exp(|x|)/(1+exp(|x|)) | 625941de046cf37aa974d078 |
def _read_format_rows(rows, format): <NEW_LINE> <INDENT> if format.startswith("FT1"): <NEW_LINE> <INDENT> data = _read_FT1_rows(rows, format) <NEW_LINE> <DEDENT> elif format.startswith("STD1"): <NEW_LINE> <INDENT> data = _read_STD1_rows(rows, format) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Inval... | Read split rows of an input line of specified format. | 625941de96565a6dacc8f9fd |
def DeselectVnicForNicType(self, nicType, device): <NEW_LINE> <INDENT> return self.delegate("DeselectVnicForNicType")(nicType, device) | Deselect the VirtualNic to be a special type.
:param nicType: The type of VirtualNic that would be deselected
:param device: The device that uniquely identifies the VirtualNic. | 625941de435de62698dfdf80 |
def Probability(percentage): <NEW_LINE> <INDENT> num = randint(1,100) <NEW_LINE> if num <= percentage*100: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | arg:
percent: percentage in %
data:
num: 代表著從 1 - 100 中抽中哪個數字
return:
probability in decimal | 625941deb545ff76a8914148 |
def create_word(word_message): <NEW_LINE> <INDENT> attr = [j[0] for j in word_message] <NEW_LINE> v1 = [j[1] for j in word_message] <NEW_LINE> bar = Bar("中国地铁站最爱用的字", title_pos='center', title_top='18', width=800, height=400) <NEW_LINE> bar.add("", attr, v1, is_stack=True, is_label_show=True) <NEW_LINE> bar.render("中国地... | 生成柱状图 | 625941de97e22403b379d2ce |
def CreateStosTransformNode(self, ControlFilter, MappedFilter, OutputType, OutputPath): <NEW_LINE> <INDENT> MappedSectionNode = MappedFilter.FindParent("Section") <NEW_LINE> MappedChannelNode = MappedFilter.FindParent("Channel") <NEW_LINE> ControlSectionNode = ControlFilter.FindParent("Section") <NEW_LINE> ControlChann... | :param FilterNode ControlFilter: Filter for control image
:param FilterNode MappedFilter: Filter for mapped image
:param str OutputType: Type of stosNode
:Param str OutputPath: Full path to .stos file | 625941dea79ad161976cc478 |
def resize_photo(img): <NEW_LINE> <INDENT> from PIL import Image <NEW_LINE> from django.conf import settings <NEW_LINE> image = Image.open(settings.MEDIA_ROOT + '/' + str(img)) <NEW_LINE> image.thumbnail((200, 200), Image.ANTIALIAS) <NEW_LINE> image.save(settings.MEDIA_ROOT + '/' + str(img), "JPEG") | resize uploaded photo to 200x200 | 625941deff9c53063f47c525 |
def deserialize(self, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.goal is None: <NEW_LINE> <INDENT> self.goal = geometry_msgs.msg.Point() <NEW_LINE> <DEDENT> end = 0 <NEW_LINE> _x = self <NEW_LINE> start = end <NEW_LINE> end += 24 <NEW_LINE> (_x.goal.x, _x.goal.y, _x.goal.z,) = _get_struct_3d().unpack(st... | unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str`` | 625941ded7e4931a7ee9e252 |
def init_app(app): <NEW_LINE> <INDENT> app.cli.add_command(init_db_command) | Register init_db_command in the app | 625941de96565a6dacc8f9fe |
def _draw_breakpoint_icon(self, top, painter, icon_name): <NEW_LINE> <INDENT> rect = QRect(0, top, self.sizeHint().width(), self.sizeHint().height()) <NEW_LINE> try: <NEW_LINE> <INDENT> icon = self.icons[icon_name] <NEW_LINE> <DEDENT> except KeyError as e: <NEW_LINE> <INDENT> debug_print("Breakpoint icon doen't exist, ... | Draw the given breakpoint pixmap.
Args:
top (int): top of the line to draw the breakpoint icon.
painter (QPainter)
icon_name (srt): key of icon to draw (see: self.icons) | 625941de5f7d997b87174dce |
def parse(puzzle_input): <NEW_LINE> <INDENT> program = [line.split() for line in puzzle_input.split("\n")] <NEW_LINE> return find_constraints([minimize(subprogram) for subprogram in decompose(program)]) | Parse input | 625941de6fece00bbac2da75 |
def test_weichert_factor(self): <NEW_LINE> <INDENT> beta = 0.8 * np.log(10.) <NEW_LINE> end_year = 2006. <NEW_LINE> comp_table = np.array([[1933., 4.0], [1900., 5.0], [1850., 6.0], [1850., 7.0]]) <NEW_LINE> self.assertAlmostEqual(0.0124319686, utils.get_weichert_factor(beta, comp_table[:, 1], comp_table[:, 0], end_year... | Tests the Weichert adjustment factor to compensate for time varying
completeness | 625941de7d43ff24873a2fd5 |
def testHeatingFunctionality(self): <NEW_LINE> <INDENT> sim = self.simulation <NEW_LINE> currents = (2.0, 4.0, 2.0, 2.0, 8.0, 0.0, 6.0) <NEW_LINE> self.fakeTime.times = ([0.0] * 3 + sorted([15.0 * n for n in xrange(1, len(currents))] * 3) + [15.0 * len(currents)] * 2) <NEW_LINE> xT = 0.0 <NEW_LINE> self.assertEqual(sim... | Tests the functionality associated with heating:
:attr:`heatingCurrent`, :attr:`temperatureSensorVoltage`,
:attr:`temperature`, and :meth:`startHeatingWithCurrent`. | 625941de004d5f362079a665 |
def get_env(integration, variable, default=None): <NEW_LINE> <INDENT> key = '{}_{}'.format(integration, variable).upper() <NEW_LINE> legacy_env = 'OPENTELEMETRY_{}'.format(key) <NEW_LINE> env = 'OTEL_{}'.format(key) <NEW_LINE> value = os.getenv(env) <NEW_LINE> legacy = os.getenv(legacy_env) <NEW_LINE> if legacy: <NEW_L... | Retrieves environment variables value for the given integration. It must be used
for consistency between integrations. The implementation is backward compatible
with legacy nomenclature:
* `OPENTELEMETRY_` is a legacy prefix with lower priority
* `OTEL_` environment variables have the highest priority
* the... | 625941deb57a9660fec33bbc |
def process_resource(self, req, resp, resource, params): <NEW_LINE> <INDENT> if not isinstance(resource, BackendResource): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> prefer = req.context.prefer = Prefer(req) <NEW_LINE> prefer_time_zone = prefer.get('outlook.timezone', raw=True) <NEW_LINE> if prefer_time_zone: <NEW_... | Built-in Falcon middleware method. | 625941de097d151d1a22318b |
def doPLB(c, s): <NEW_LINE> <INDENT> tokens = s.split() <NEW_LINE> n = int(tokens[0]) <NEW_LINE> points = [float(t) for t in tokens[1:n * 2 + 1]] <NEW_LINE> didx = sum(len(t) for t in tokens[1:n * 2 + 1]) + n * 2 + 2 <NEW_LINE> npoints = nsplit(points, 2) <NEW_LINE> return didx, (c, npoints) | Parse polygon, polyline og B-spline | 625941de4527f215b584c787 |
def print_dict(my_dict): <NEW_LINE> <INDENT> for key,value in my_dict.items(): <NEW_LINE> <INDENT> print(key + ": ",value) | 打印字典 | 625941de5166f23b2e1a548c |
def generate_sbatch_scripts(options): <NEW_LINE> <INDENT> if options.read_from_file: <NEW_LINE> <INDENT> with open(options.read_from_file) as f: <NEW_LINE> <INDENT> query_files = [line.strip() for line in f.readlines()] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> query_files = options.query <NEW_LINE> <DEDEN... | Generate sbatch scripts.
The default Slurm job name is the name of the first query file name in the
produced job script. | 625941de92d797404e3044be |
def testDigestStable(self): <NEW_LINE> <INDENT> s1 = CoreCheckoutStep(nullPkg, ("script", "digest", [], []), [], Env({"a" : "asdf", "q": "qwer" }), Env({ "a" : "asdf" })) <NEW_LINE> s2 = CoreCheckoutStep(nullPkg, ("script", "digest", [], []), [], Env({"a" : "asdf", "q": "qwer" }), Env({ "a" : "asdf" })) <NEW_LINE> asse... | Same input should yield same digest | 625941de3617ad0b5ed6822a |
def convert_required_fields(data, required_fields, field_types, action=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> converted_data = convert_ui_data(data, required_fields, field_types) <NEW_LINE> valid_edit_phases = deployment_edit_phase_values() <NEW_LINE> if 'editPhase' not in converted_data: <NEW_LINE> <INDEN... | Verify for the supplied action, the required fields have been provided in the input data.
| 625941de31939e2706e4d199 |
def char_freq_table(file): <NEW_LINE> <INDENT> from operator import itemgetter <NEW_LINE> fileReader = open(file) <NEW_LINE> lineList = [] <NEW_LINE> letterList = [] <NEW_LINE> for line in fileReader: <NEW_LINE> <INDENT> lineList.append(line.strip()) <NEW_LINE> <DEDENT> fileReader.close() <NEW_LINE> for line in lineLis... | This function accepts a filename from the user,
and builds a frequency listing of the characters
in the file. It then prints a sorted and
nicely formatted character frequency table to
the screen.
It does this in 5 stepts. The first step is to read in
the file and initialize two lists used to quantify the
characte... | 625941de0a366e3fb873eb50 |
def update(self, i, val): <NEW_LINE> <INDENT> diff = val-self.nums[i] <NEW_LINE> self.nums[i] = val <NEW_LINE> self._set_bit(i, diff) | :type i: int
:type val: int
:rtype: void | 625941dea17c0f6771cbe383 |
def adjacent(self,index): <NEW_LINE> <INDENT> pass | Return the set of connecting rooms to room specified by index | 625941decc0a2c11143dd1c4 |
def cal(month, balance, mid, monthlyinterestrate): <NEW_LINE> <INDENT> while month < 12: <NEW_LINE> <INDENT> monthlyunpaidbalance = balance - mid <NEW_LINE> balance = monthlyunpaidbalance + (monthlyinterestrate * monthlyunpaidbalance) <NEW_LINE> month += 1 <NEW_LINE> <DEDENT> return balance | caluclate mid for each year | 625941de236d856c2ad44b12 |
def bitwise_or_2lists(list1, list2): <NEW_LINE> <INDENT> list_len = len(list2) <NEW_LINE> return_list = [None] * list_len <NEW_LINE> for i in range(list_len): <NEW_LINE> <INDENT> return_list[i] = list1[i] | list2[i] <NEW_LINE> <DEDENT> return return_list | Takes two bit patterns of equal length and performs the logical
inclusive OR operation on each pair of corresponding bits | 625941deaad79263cf390d79 |
def get_default_projects_config(): <NEW_LINE> <INDENT> return { 'git-config': { 'email': '', 'name': '' }, 'gerrit': { 'host': 'localhost', 'port': 29418, 'username': 'SomeUser', 'key_filename': None, 'timeout': 10, 'keepalive': 60 }, 'upstream': { 'host': '', 'port': 29418, 'username': 'SomeUser', 'key_filename': None... | Returns the default configuration.
@TODO - Maybe make this static and use the copy module
when grabbing the config?
@return - Dictionary | 625941de1b99ca400220ade6 |
def boundingRect(self): <NEW_LINE> <INDENT> if self.__dx is None: <NEW_LINE> <INDENT> xmin = min(self.__x) <NEW_LINE> xmax = max(self.__x) <NEW_LINE> <DEDENT> elif len(self.__dx.shape) in [0, 1]: <NEW_LINE> <INDENT> xmin = min(self.__x - self.__dx) <NEW_LINE> xmax = max(self.__x + self.__dx) <NEW_LINE> <DEDENT> else: <... | Return the bounding rectangle of the data, error bars included. | 625941de38b623060ff0b121 |
def _is_a_namedtuple(field_type: type) -> bool: <NEW_LINE> <INDENT> return hasattr(field_type, '_fields') | Determine whether or not a field type is a NamedTuple class. | 625941de6fb2d068a760f3d5 |
def refresh(self): <NEW_LINE> <INDENT> self._gen_stats(self._get_tweets()) <NEW_LINE> self.save() | Get new Tweets and generate new stats for current word.
Saves this to file. | 625941de4c3428357757c65a |
def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> self.clear_term() <NEW_LINE> return False | Context manager exit support.
Override in a concrete factory class if more cleanup than a simple
self.clear_term() is needed when the UIFactory is finished with. | 625941de4f88993c3716c398 |
def XgbModel(df_train,df_test,nround,alpha = 0.23): <NEW_LINE> <INDENT> models = [] <NEW_LINE> for i in range(LOOP): <NEW_LINE> <INDENT> print('LOOP',i) <NEW_LINE> dbuild, dvalid, watchlist = split_train_valid(df_train,test_size=0.1) <NEW_LINE> dtrain = xgb.DMatrix(df_train[features],label=df_train[label]) <NEW_LINE> m... | 参数:训练数据和测试数据
outputfile:输出文件的结果。
alpha设置是1的阈值,默认是0.23
return 数据文件的结果,三个不同seed的平均是的 | 625941dea8370b7717052bd2 |
def drawSquares(size): <NEW_LINE> <INDENT> turtle.down() <NEW_LINE> turtle.forward(size/2) <NEW_LINE> turtle.left(90) <NEW_LINE> turtle.forward(size) <NEW_LINE> turtle.left(90) <NEW_LINE> turtle.forward(size) <NEW_LINE> turtle.left(90) <NEW_LINE> turtle.forward(size) <NEW_LINE> turtle.left(90) <NEW_LINE> turtle.forward... | precondition: none
Draws small squares
postcondition: turtle pen is up, orientation and position are the same as upon entry | 625941de8a349b6b435e84a7 |
def enabled(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return bool(self.config[name]) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return None | Returns whether a setting has been enabled.
This just casts the configuration value to a boolean.
If the name is not found in the configuration, None is returned
so evaluating.
Args:
name (str): The name of the the configuration option
Returns:
boolean or None | 625941de3c8af77a43ae3ad7 |
def process_stream_results( iteration, stream_read, in_names, device_threshold=0, ljm_threshold=0 ): <NEW_LINE> <INDENT> data = stream_read[0] <NEW_LINE> device_num_backlog_scans = stream_read[1] <NEW_LINE> ljm_num_backlog_scans = stream_read[2] <NEW_LINE> num_addresses = len(in_names) <NEW_LINE> num_scans = len(data) ... | Print ljm.eStreamRead results and count the number of skipped samples. | 625941de379a373c97cfae7a |
def conv1x1(in_planes, out_planes, stride=1): <NEW_LINE> <INDENT> return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, padding=0, bias=False) | 3x3 convolution with padding | 625941de15baa723493c42ab |
def get_currency_value() -> int: <NEW_LINE> <INDENT> settings = shelve.open(filename) <NEW_LINE> if 'currency_value' not in settings: <NEW_LINE> <INDENT> settings['currency_value'] = 10200 <NEW_LINE> <DEDENT> value = settings['currency_value'] <NEW_LINE> settings.close() <NEW_LINE> return value | Get currency value
:return: currency value | 625941dea05bb46b383ecb54 |
def rtnl_route_nexthop_n(route, index): <NEW_LINE> <INDENT> _rtnl_route_get_nexthop_n = _libnl_route( 'rtnl_route_nexthop_n', c_void_p, c_void_p, c_int ) <NEW_LINE> return _rtnl_route_get_nexthop_n(route, index) | Return next hop of given route.
@arg route Route object
@arg index Index of next hop, within rtnl_route_get_nnexthops
@return Next hop object or None if there is None on given index. | 625941de85dfad0860c3b190 |
def is_fs_link(pathname): <NEW_LINE> <INDENT> return os.path.islink(pathname) | Test whether item is existing link in filesystem | 625941de8c0ade5d55d3ecf1 |
def test_get_tab_by_methods(self): <NEW_LINE> <INDENT> self.course.tabs = self.all_valid_tab_list <NEW_LINE> for tab in self.course.tabs: <NEW_LINE> <INDENT> self.assertEqual(xmodule_tabs.CourseTabList.get_tab_by_type(self.course.tabs, tab.type), tab) <NEW_LINE> self.assertEqual(xmodule_tabs.CourseTabList.get_tab_by_id... | Tests the get_tab methods in CourseTabList | 625941decdde0d52a9e53369 |
def n2w(rpm): <NEW_LINE> <INDENT> return f2w(n2f(rpm)) | convert the rotational speed to rad/s from rpm | 625941de7cff6e4e81117cb9 |
def interactive_fermat(): <NEW_LINE> <INDENT> print("\n To check Fermat's Last Theorem, enter values for a, b, c, n") <NEW_LINE> print(" a^n + b^n = c^n") <NEW_LINE> a = int(input(' Enter a value for a: ')) <NEW_LINE> b = int(input(' Enter a value for b: ')) <NEW_LINE> c = int(input(' Enter a value for c: ')) <N... | Prompts a user to enter values to check Fermat's Last Theorem | 625941de71ff763f4b5499c5 |
def main(): <NEW_LINE> <INDENT> datetime = time.strftime("%Y-%m-%d-%H-%M-%S_") <NEW_LINE> logging.basicConfig(filename='log/'+str(datetime)+'panda.log', level=logging.INFO) <NEW_LINE> df = retrieve_data() <NEW_LINE> colnames = list(df.columns.values) <NEW_LINE> if settings["amount_of_columns"] > len(colnames): <NEW_LIN... | Main functions orchestrating the major work | 625941de5f7d997b87174dcf |
def arcto(self, x, y, radius=1, clockwise=True, short=False): <NEW_LINE> <INDENT> x0, y0 = self[-1].x, self[-1].y <NEW_LINE> phi = geo.angle(x0, y0, x, y) <NEW_LINE> for p in arcto(x0, y0, radius, radius, phi, short, not clockwise, x, y): <NEW_LINE> <INDENT> f = len(p) == 2 and self.lineto or self.curveto <NEW_LINE> f(... | Add a number of Bezier-curves that draw an arc with the given radius to (x,y).
The short parameter selects either the "long way" around or the
"shortcut". | 625941de4428ac0f6e5bab28 |
def angularProy_SB(cos, frac, AFB, FH, coefsEff, fraction, paramsLeft, paramsRight): <NEW_LINE> <INDENT> signal = angularSignal(cos, AFB, FH, coefsEff) <NEW_LINE> background = angularBackground_SideBands(cos, fraction, paramsLeft, paramsRight) <NEW_LINE> return frac*signal + (1-frac)*background | NonExtended complete PDF on the angular varibale (Integrating the mass variable) | 625941de442bda511e8be748 |
def test_comment_others_activity_as_owner(self): <NEW_LINE> <INDENT> from max.tests.mockers import user_status as activity <NEW_LINE> from max.tests.mockers import user_comment as comment <NEW_LINE> username = 'sheldon' <NEW_LINE> self.create_user(username) <NEW_LINE> activity_id = self.create_activity(username, activi... | Given i'm the owner of the activity
When i try to post a comment on a contextless activity i own
I succeed | 625941dee8904600ed9f2265 |
def flatten_for_now(energy_stats: Dict[str, EnergySubtotal]): <NEW_LINE> <INDENT> flat = {} <NEW_LINE> for label, vals in energy_stats.items(): <NEW_LINE> <INDENT> energy_use_varname = "energy_use_%s" % label <NEW_LINE> primary_energy_varname = "primary_energy_%s" % label <NEW_LINE> emissions_varname = "emissions_%s" %... | Flatten the energy stats dict to fit the legacy format used in EPCTK
.. note::
in the future may prefer to keep subtotal results in nested format.
Args:
energy_stats: a dict of (label: _EnergySubtotal tuple) key-value pairs
Returns:
a new dict, flattened by appending label to the energy stat name.
e.g.... | 625941de0fa83653e46572ed |
def create_database(self, database_name: str) -> None: <NEW_LINE> <INDENT> if database_name is None: <NEW_LINE> <INDENT> raise AirflowBadRequest("Database name cannot be None.") <NEW_LINE> <DEDENT> existing_database = list( self.get_conn().QueryDatabases( { "query": "SELECT * FROM r WHERE r.id=@id", "parameters": [{"na... | Creates a new database in CosmosDB. | 625941def9cc0f698b14092d |
def check_query_string(): <NEW_LINE> <INDENT> query = self._qs(self.browser.current_url) <NEW_LINE> return 'code' in query | Checks that 'code' appears in the browser's current url. | 625941decad5886f8bd2730d |
def _count_spaces_startswith(line): <NEW_LINE> <INDENT> if line.split("#")[0].strip() == "": <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> spaces = 0 <NEW_LINE> for i in line: <NEW_LINE> <INDENT> if i.isspace(): <NEW_LINE> <INDENT> spaces += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return spaces | Count the number of spaces before the first character | 625941de8a43f66fc4b54396 |
def make_default_app(self): <NEW_LINE> <INDENT> self.formater.custom_message("OKCYAN", "", "Starting Django app...") <NEW_LINE> call_command("startapp", self.app_name) <NEW_LINE> os.remove(self._get_app_dir("views.py")) <NEW_LINE> self._create_dir(self.app_name, "views") <NEW_LINE> self._create_file(self._get_app_dir("... | Creates the django app, the views root folder and some example views. | 625941de91f36d47f21ac82a |
def isPalindrome(self, head): <NEW_LINE> <INDENT> fast, slow = head, head <NEW_LINE> while fast and fast.next: <NEW_LINE> <INDENT> fast = fast.next.next <NEW_LINE> slow = slow.next <NEW_LINE> <DEDENT> pre, cur, nex = None, slow, None <NEW_LINE> while cur: <NEW_LINE> <INDENT> nex = cur.next <NEW_LINE> cur.next = pre <NE... | :type head: ListNode
:rtype: bool | 625941defbf16365ca6f64fd |
def _update_linecache(self, path, data): <NEW_LINE> <INDENT> if PY24 and 'mitogen' in path: <NEW_LINE> <INDENT> linecache.cache[path] = ( len(data), 0.0, [line+'\n' for line in data.splitlines()], path, ) | The Python 2.4 linecache module, used to fetch source code for
tracebacks and :func:`inspect.getsource`, does not support PEP-302,
meaning it needs extra help to for Mitogen-loaded modules. Directly
populate its cache if a loaded module belongs to the Mitogen package. | 625941de0a50d4780f6671c9 |
def force_posdef(x, tol=0, maxiter=1000): <NEW_LINE> <INDENT> spacing = np.spacing(np.linalg.norm(x)) <NEW_LINE> mineig = np.min(np.real(np.linalg.eigvals(x))) <NEW_LINE> xh = x.copy() <NEW_LINE> i = np.eye(x.shape[0]) <NEW_LINE> k = 1 <NEW_LINE> while mineig < tol: <NEW_LINE> <INDENT> mineig = np.min(np.real(np.linalg... | Iteratively adjust a Hermitian matrix to find the closest positive
definite matrix.
From https://stackoverflow.com/questions/43238173/python-convert-matrix-to-positive-semi-definite/43244194 | 625941debf627c535bc13504 |
def test_import(): <NEW_LINE> <INDENT> from .. import K2ephem | Can we import k2ephem successfully? | 625941de091ae3566866728d |
def chunkiter(iterable, size): <NEW_LINE> <INDENT> def inneriter(first, iterator, size): <NEW_LINE> <INDENT> yield first <NEW_LINE> for _ in range(size - 1): <NEW_LINE> <INDENT> yield iterator.next() <NEW_LINE> <DEDENT> <DEDENT> it = iter(iterable) <NEW_LINE> while True: <NEW_LINE> <INDENT> yield inneriter(it.next(), i... | Iterates over an iterable in chunks of size size. Returns an iterator
that in turn returns iterators over the iterable that each iterate through
size objects in the iterable.
Note that since the inner and outer loops are pulling values from the same
iterator, continue and break don't necessarily behave exactly as one w... | 625941de7d847024c06be5f3 |
def check_config(self): <NEW_LINE> <INDENT> super(BCPRM, self).check_config() <NEW_LINE> if not self._recv: <NEW_LINE> <INDENT> self.raise_exception('No receiving blocks specified!', ValueError) <NEW_LINE> <DEDENT> first_blkdef = self._recv[0] <NEW_LINE> for i, blkdef in enumerate(self._recv): <NEW_LINE> <INDENT> blkde... | Check sanity of current configuration. | 625941de4a966d76dd551346 |
def apply_transform(i, x): <NEW_LINE> <INDENT> def brightness_foo(): <NEW_LINE> <INDENT> if brightness == 0: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return random_brightness(x, max_delta=brightness) <NEW_LINE> <DEDENT> <DEDENT> def contrast_foo(): <NEW_LINE> <INDENT> if contrast == 0:... | Apply the i-th transformation. | 625941de377c676e912724dc |
def devise_setup(**kwargs): <NEW_LINE> <INDENT> install_devise_dependencies() <NEW_LINE> setup(**kwargs) | Install prerequisites first then run the rest | 625941de73bcbd0ca4b2c3ab |
def parse_sumstats(inf, chrom, start, end, rsid_col, chrom_col, pos_col, beta_col, se_col, effal_col, n_col, sep): <NEW_LINE> <INDENT> iter_csv = pd.read_csv(inf, sep=sep, header=0, iterator=True, chunksize=100000) <NEW_LINE> iter_chunks = [] <NEW_LINE> for chunk in iter_csv: <NEW_LINE> <INDENT> chunk[chrom_col] = chun... | Parse a summary stat file and return zscores
Args:
inf (str): input summary stat file
chrom (str): chrom to extract
start (int): position to extract from
end (int): position to extract to
...column names
Returns:
zscores (Series), effect alleles (dict), n (int) | 625941dee5267d203edcdfce |
def suite(): <NEW_LINE> <INDENT> suite = unittest.TestSuite() <NEW_LINE> classes = [ ChannelManagerUnitTests ] <NEW_LINE> for _class in classes: <NEW_LINE> <INDENT> _object = _class() <NEW_LINE> for methode_name in dir( _object ): <NEW_LINE> <INDENT> if methode_name.lower().startswith( "test" ): <NEW_LINE> <INDENT> s... | Problem with sys.argv[1] when unittest module is in a script
https://stackoverflow.com/questions/2812218/problem-with-sys-argv1-when-unittest-module-is-in-a-script
Is there a way to loop through and execute all of the functions in a Python class?
https://stackoverflow.com/questions/2597827/is-there-a-way-to-loop-throu... | 625941de796e427e537b08fc |
def _get_logits(images, model_options, weight_decay=0.0001, reuse=None, is_training=False, fine_tune_batch_norm=False): <NEW_LINE> <INDENT> features, end_points = extract_features( images, model_options, weight_decay=weight_decay, reuse=reuse, is_training=is_training, fine_tune_batch_norm=fine_tune_batch_norm) <NEW_LIN... | 通过ASPP获得logits
Args:
:param images:tensor, [batch, height, width, channels]
:param model_options: 配置模型
:param weight_decay: 模型变量的权重衰减
:param reuse: 是否重用模型变量
:param is_training: 是否训练
:param fine_tune_batch_norm:是否微调BN参数
:return:
outputs_to_logits:输出类型到logits的映射 | 625941def8510a7c17cf9a33 |
@composite <NEW_LINE> def get_player_names(draw, suitor_pool, reviewer_pool): <NEW_LINE> <INDENT> suitor_names = draw( lists( sampled_from(suitor_pool), min_size=1, max_size=len(suitor_pool), unique=True, ) ) <NEW_LINE> reviewer_names = draw( lists( sampled_from(reviewer_pool), min_size=len(suitor_names), max_size=len(... | A custom strategy for drawing lists of suitor and reviewer names of
equal size from their respective pools. | 625941de76e4537e8c3519a9 |
def translation(language): <NEW_LINE> <INDENT> global _translations <NEW_LINE> t = _translations.get(language, None) <NEW_LINE> if t is not None: <NEW_LINE> <INDENT> return t <NEW_LINE> <DEDENT> from django.conf import settings <NEW_LINE> globalpath = os.path.join(os.path.dirname(upath(sys.modules[settings.__module__].... | Returns a translation object.
This translation object will be constructed out of multiple GNUTranslations
objects by merging their catalogs. It will construct a object for the
requested language and add a fallback to the default language, if it's
different from the requested language. | 625941de004d5f362079a666 |
def trim_from_authority(self): <NEW_LINE> <INDENT> return self.trim_from_path().trim_path() | If this URI has a not empty path and or query and or fragment, returns the URI
formed by removing them; this URI unchanged, otherwise. | 625941de379a373c97cfae7b |
def __init__(self, title, desc): <NEW_LINE> <INDENT> self._title = title <NEW_LINE> self._desc = desc | *title* and *desc* are callables, which, when get invoked,
should return the translated description message in the current
locale. Instances of this class will be associated to permission
enumeration items defined in this module. | 625941de1f037a2d8b946532 |
def update(self, tasks): <NEW_LINE> <INDENT> rl_losses_agg = {} <NEW_LINE> for update in range(self.args.rl_updates_per_iter): <NEW_LINE> <INDENT> obs, actions, rewards, next_obs, terms = self.sample_rl_batch(tasks, self.args.batch_size) <NEW_LINE> t, b, _ = obs.size() <NEW_LINE> obs = obs.view(t * b, -1) <NEW_LINE> ac... | Meta-update
:param tasks: list/array of task indices. perform update based on the tasks
:return: | 625941de442bda511e8be749 |
def __init__(self, GLONASSNavigationFile): <NEW_LINE> <INDENT> if not type(GLONASSNavigationFile)==str: <NEW_LINE> <INDENT> raise Exception("La ruta del fichero introducido no es de tipo str.") <NEW_LINE> <DEDENT> if not exists(GLONASSNavigationFile): <NEW_LINE> <INDENT> raise Exception("La ruta del fichero introducido... | !
Constructor | 625941de5e10d32532c5f25b |
def get_profile_model_resource_custom_fields(): <NEW_LINE> <INDENT> _fields = ["telephone", "donor"] <NEW_LINE> _fields.extend(get_preference_model_fields()) <NEW_LINE> result = {} <NEW_LINE> for field in _fields: <NEW_LINE> <INDENT> result[field] = fields.Field() <NEW_LINE> <DEDENT> return result | Get profile model resource custom fields | 625941de26238365f5f0f1a7 |
def update_Qtable(self, r, action, next_state): <NEW_LINE> <INDENT> if self.learning: <NEW_LINE> <INDENT> self.Qtable[self.state][action] += self.alpha * (r + self.gamma * float(max(self.Qtable[next_state].values())) - self.Qtable[self.state][action]) | Update the qtable according to the given rule. | 625941de5510c4643540f711 |
def info(self): <NEW_LINE> <INDENT> if not self.started(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> isp = self.is_process() <NEW_LINE> actor = {'name': self.name, 'state': self.info_state, 'actor_id': self.aid, 'uptime': self._loop.time() - self._started, 'thread_id': self.tid, 'process_id': self.pid, 'is_proces... | Return a nested dictionary of information related to the actor
status and performance. The dictionary contains the following entries:
* ``actor`` a dictionary containing information regarding the type of
actor and its status.
* ``events`` a dictionary of information about the
:ref:`event loop <asyncio-event-loop>`... | 625941de6e29344779a62945 |
def __init__(self, waveform=N.ones(32), sample_rate=16000.0, horizon=100.0, **kwargs): <NEW_LINE> <INDENT> super(WaveformND, self).__init__(**kwargs) <NEW_LINE> self.intra_v = waveform.copy() <NEW_LINE> self.extra_v = waveform.copy() <NEW_LINE> self.horizon = horizon <NEW_LINE> self.sample_rate = sample_rate | :Parameters:
waveform : ndarray
The single-channel waeform as a one-dimensional ndarray.
Default=ones(32)
sample_rate : float
Sample rate of the waveform in Hz.
Default=16000.0
:Keywords:
see NeuronData
:Exceptions:
see NeuronData | 625941defb3f5b602dac39cc |
def get_language_from_request(request, check_path=False): <NEW_LINE> <INDENT> global _accepted <NEW_LINE> from yweb.conf import settings <NEW_LINE> supported = SortedDict(settings.LANGUAGES) <NEW_LINE> if check_path: <NEW_LINE> <INDENT> lang_code = get_language_from_path(request.path_info, supported) <NEW_LINE> if lang... | Analyzes the request to find what language the user wants the system to
show. Only languages listed in settings.LANGUAGES are taken into account.
If the user requests a sublanguage where we have a main language, we send
out the main language.
If check_path is True, the URL path prefix will be checked for a language
co... | 625941debe8e80087fb20f73 |
def translate_solution(self, n, solution): <NEW_LINE> <INDENT> return map(lambda ind: "." * ind + "Q" + "." * (n - ind - 1), solution) | :param solution: list[int]
:return: List[str] | 625941dedd821e528d63b4dc |
@app.route('/api/v1/products') <NEW_LINE> def get_all_products(): <NEW_LINE> <INDENT> all_products = a.get_products() <NEW_LINE> if all_products: <NEW_LINE> <INDENT> return make_response(jsonify({'product_list':all_products}), 200) | implements get all products api | 625941dede87d2750b8600ca |
def _solve_conn_curs(conn_or_curs): <NEW_LINE> <INDENT> if conn_or_curs is None: <NEW_LINE> <INDENT> raise psycopg2.ProgrammingError("no connection or cursor provided") <NEW_LINE> <DEDENT> if hasattr(conn_or_curs, 'execute'): <NEW_LINE> <INDENT> conn = conn_or_curs.connection <NEW_LINE> curs = conn.cursor(cursor_factor... | Return the connection and a DBAPI cursor from a connection or cursor. | 625941de435de62698dfdf82 |
def process_filemanager(filemanager_list): <NEW_LINE> <INDENT> lines = 0 <NEW_LINE> src_path = __src_dir + "FileManager.cpp" <NEW_LINE> strings_processed = 0 <NEW_LINE> file_in = open(src_path, 'r') <NEW_LINE> for line_in in file_in: <NEW_LINE> <INDENT> lines += 1 <NEW_LINE> line = line_in.strip() <NEW_LINE> if len(lin... | Generate suppressions for FileManager.
| 625941de5fcc89381b1e19f6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.