code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
def optimize_open_file(self): <NEW_LINE> <INDENT> self.__fptr = open(self.file_name,"rb") | Opens the vlsv file for reading
Files are opened and closed automatically upon reading and in the case of reading multiple times it will help to keep the file open with this command
.. code-block: python
#Example usage:
variables = []
vlsvReader.optimize_open_file()
for i in range(1000):
variables.append(vlsvReader.read_variable("rho", cellids=i))
vlsvReader.optimize_close_file()
.. note:: This should only be used for optimization purposes. | 625941b70a366e3fb873e652 |
def inverse_transform(self, Y, threshold=None): <NEW_LINE> <INDENT> check_is_fitted(self, 'classes_') <NEW_LINE> if threshold is None: <NEW_LINE> <INDENT> threshold = (self.pos_label + self.neg_label) / 2. <NEW_LINE> <DEDENT> if self.y_type_ == "multiclass": <NEW_LINE> <INDENT> y_inv = _inverse_binarize_multiclass(Y, self.classes_) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> y_inv = _inverse_binarize_thresholding(Y, self.y_type_, self.classes_, threshold) <NEW_LINE> <DEDENT> if self.sparse_input_: <NEW_LINE> <INDENT> y_inv = sp.csr_matrix(y_inv) <NEW_LINE> <DEDENT> elif sp.issparse(y_inv): <NEW_LINE> <INDENT> y_inv = y_inv.toarray() <NEW_LINE> <DEDENT> return y_inv | Transform binary labels back to multi-class labels
Parameters
----------
Y : numpy array or sparse matrix with shape [n_samples, n_classes]
Target values. All sparse matrices are converted to CSR before
inverse transformation.
threshold : float or None
Threshold used in the binary and multi-label cases.
Use 0 when ``Y`` contains the output of decision_function
(classifier).
Use 0.5 when ``Y`` contains the output of predict_proba.
If None, the threshold is assumed to be half way between
neg_label and pos_label.
Returns
-------
y : numpy array or CSR matrix of shape [n_samples] Target values.
Notes
-----
In the case when the binary labels are fractional
(probabilistic), inverse_transform chooses the class with the
greatest value. Typically, this allows to use the output of a
linear model's decision_function method directly as the input
of inverse_transform. | 625941b776d4e153a657e96b |
def fill_data_structure(self): <NEW_LINE> <INDENT> dir_src = const.DIR_RAW_DATA_TRANSFORM <NEW_LINE> if not os.path.exists(dir_src): <NEW_LINE> <INDENT> print("You should clean files first!") <NEW_LINE> return -1 <NEW_LINE> <DEDENT> filenames = listdir(dir_src) <NEW_LINE> for file in filenames: <NEW_LINE> <INDENT> if file.endswith(".csv"): <NEW_LINE> <INDENT> data = file.split("_") <NEW_LINE> if data[2] not in self.tm: <NEW_LINE> <INDENT> self.tm.append(data[2]) <NEW_LINE> <DEDENT> if data[1] not in self.users: <NEW_LINE> <INDENT> self.users.append(data[1]) <NEW_LINE> <DEDENT> f = open(os.path.join(dir_src, file)) <NEW_LINE> reader = csv.reader(f, delimiter=",") <NEW_LINE> for row in reader: <NEW_LINE> <INDENT> if row[1] not in self.sensors and not row[1] == "": <NEW_LINE> <INDENT> self.sensors.append(row[1]) <NEW_LINE> <DEDENT> <DEDENT> f.close() <NEW_LINE> <DEDENT> <DEDENT> self.header_with_features = {0: "time", 1: "activityrecognition#0", 2: "activityrecognition#1"} <NEW_LINE> header_index = 3 <NEW_LINE> for s in self.sensors: <NEW_LINE> <INDENT> if s != "activityrecognition": <NEW_LINE> <INDENT> for feature_key in self.EXTRACTED_FEATURE_KEYS: <NEW_LINE> <INDENT> self.header_with_features[header_index] = s + feature_key <NEW_LINE> header_index += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.header = {0: "time", 1: "activityrecognition#0", 2: "activityrecognition#1"} <NEW_LINE> header_index = 3 <NEW_LINE> for s in self.sensors: <NEW_LINE> <INDENT> if s != "activityrecognition": <NEW_LINE> <INDENT> self.header[header_index] = s + "#0" <NEW_LINE> header_index += 1 | Fill travel modes, users, sensors data structures
:return: | 625941b723e79379d52ee3a3 |
def _escape(txt): <NEW_LINE> <INDENT> txt = txt.replace('&', '&') <NEW_LINE> txt = txt.replace('<', '<') <NEW_LINE> txt = txt.replace('>', '>') <NEW_LINE> return txt | Basic html escaping. | 625941b74e696a04525c9290 |
def _save(self) -> None: <NEW_LINE> <INDENT> if not self._path: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> with io.open(self._path, "w", encoding="utf8") as f: <NEW_LINE> <INDENT> yaml.dump(self._data, f, default_flow_style=False, allow_unicode=True) | Persist the configuration to the file system | 625941b7eab8aa0e5d26d99a |
def twoSum(self, nums, target): <NEW_LINE> <INDENT> d = dict() <NEW_LINE> for i, value in enumerate(nums): <NEW_LINE> <INDENT> if target - value in d: <NEW_LINE> <INDENT> return [d[target - value], i] <NEW_LINE> <DEDENT> d[value] = i | :type nums: List[int]
:type target: int
:rtype: List[int] | 625941b721a7993f00bc7b25 |
def optimization(empire, gamma, ProblemParam): <NEW_LINE> <INDENT> num_colonies = len(empire.colonies_position) <NEW_LINE> if num_colonies == 0: <NEW_LINE> <INDENT> best = gamma <NEW_LINE> <DEDENT> for i in range(num_colonies): <NEW_LINE> <INDENT> distance_vector = empire.imperialist_position - empire.colonies_position[i] <NEW_LINE> distance = np.linalg.norm(distance_vector) <NEW_LINE> if i == 0: <NEW_LINE> <INDENT> best = distance <NEW_LINE> <DEDENT> if best > distance: <NEW_LINE> <INDENT> best = distance <NEW_LINE> <DEDENT> <DEDENT> delta = gamma * best <NEW_LINE> potential_position = np.zeros(len(empire.imperialist_position)) <NEW_LINE> for i in range(len(empire.imperialist_position)): <NEW_LINE> <INDENT> potential_position[i] = empire.imperialist_position[i] + np.random.uniform(-1, 1) * delta <NEW_LINE> <DEDENT> potential_fit = test_function.test_function(potential_position, ProblemParam.test_function_index, ProblemParam.dimention) <NEW_LINE> if potential_fit < empire.imperialist_fitness: <NEW_LINE> <INDENT> empire.imperialist_position = potential_position <NEW_LINE> empire.imperialist_fitness = potential_fit <NEW_LINE> <DEDENT> return empire | Функция оптимизации положения империалиста (столицы).
optization(empire, gamma, ProblemParam) -> empire
Оптимизация осуществляется в небольшой окрестности.
Окрестность (delta) расчитывается как gamma * best,
где gamma - настраеваемый параметр алгоритма (gamma < 1)
best - евклидово расстояние до ближайшей колонии.
В случае, если у империалиста отсутствуют колонии область поиска определяется как gamma * gamma.
Потенциальная позиция для перемещения выбирается случаынйм образом в данной окрестности:
potential_position[i] = empire.imperialist_position[i] + np.random.uniform(-1, 1) * delta.
Пригодность потенциального положения определяется путем расчета значения функции качества в этой точке,
если оно [значение функции качества] меньше значения функции качества в текущей точке
происходит передвижение империалиста, в противном случае империалист не перемещается.
--------------------------------------------------------
Параметры:
@param empire - объект класса "Empires",
необходимы поля - imperialist_position, colonies_position и imperialist_fitness
@param gamma - настраеваемый параметр алгоритма (0 < gamma < 1), число.
@param ProblemParam - объект класса "ProblemParams"
Возвращаемые значения:
@return empire - объект класса "Empires" | 625941b763d6d428bbe4432b |
def MakeHistFromList(t, name=''): <NEW_LINE> <INDENT> hist = Hist(name=name) <NEW_LINE> [hist.Incr(x) for x in t] <NEW_LINE> return hist | Makes a histogram from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this histogram
Returns:
Hist object | 625941b721bff66bcd684791 |
def primeFactorization(number): <NEW_LINE> <INDENT> assert isinstance(number, int) and number >= 0, "'number' must been an int and >= 0" <NEW_LINE> ans = [] <NEW_LINE> factor = 2 <NEW_LINE> quotient = number <NEW_LINE> if number == 0 or number == 1: <NEW_LINE> <INDENT> ans.append(number) <NEW_LINE> <DEDENT> elif not isPrime(number): <NEW_LINE> <INDENT> while quotient != 1: <NEW_LINE> <INDENT> if isPrime(factor) and (quotient % factor == 0): <NEW_LINE> <INDENT> ans.append(factor) <NEW_LINE> quotient /= factor <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> factor += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> ans.append(number) <NEW_LINE> <DEDENT> assert isinstance(ans, list), "'ans' must been from type list" <NEW_LINE> return ans | input: positive integer 'number'
returns a list of the prime number factors of 'number' | 625941b77b25080760e39296 |
def handle(self, request, exception, tb): <NEW_LINE> <INDENT> def get_data(queue): <NEW_LINE> <INDENT> client = self.gdata.projecthosting.client.ProjectHostingClient() <NEW_LINE> client.client_login( settings.ERROR_CAPTURE_GOOGLE_CODE_LOGIN, settings.ERROR_CAPTURE_GOOGLE_CODE_PASSWORD, source='error-capture-middleware', service='code', ) <NEW_LINE> title_tpl = loader.get_template( 'django_error_capture_middleware/googlecode/title.txt') <NEW_LINE> body_tpl = loader.get_template( 'django_error_capture_middleware/googlecode/body.txt') <NEW_LINE> result = client.add_issue( settings.ERROR_CAPTURE_GOOGLE_CODE_PROJECT, title_tpl.render(self.context), body_tpl.render(self.context), settings.ERROR_CAPTURE_GOOGLE_CODE_LOGIN, 'open', labels=[settings.ERROR_CAPTURE_GOOGLE_CODE_TYPE]) <NEW_LINE> issue_url = result.find_html_link() <NEW_LINE> id = issue_url.split('=')[-1] <NEW_LINE> queue.put_nowait([id, issue_url]) <NEW_LINE> <DEDENT> queue, process = self.background_call(get_data) <NEW_LINE> try: <NEW_LINE> <INDENT> self.context['id'], self.context['bug_url'] = self.get_data(queue) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> pass | Pushes the traceback to a github ticket system.
:Parameters:
- `request`: request causing the exception
- `exception`: actual exception raised
- `tb`: traceback string | 625941b70fa83653e4656df9 |
def max_duffel_bag_value(inventory,capacity,value=0,memo={}): <NEW_LINE> <INDENT> if (capacity in memo): <NEW_LINE> <INDENT> return [memo[capacity]]; <NEW_LINE> <DEDENT> elif (True if 0 in [x for x,y in inventory] else False): <NEW_LINE> <INDENT> return float("inf") <NEW_LINE> <DEDENT> elif capacity == 0: <NEW_LINE> <INDENT> return [value] <NEW_LINE> <DEDENT> elif capacity < 0: <NEW_LINE> <INDENT> return [0]; <NEW_LINE> <DEDENT> possible_values = [] <NEW_LINE> for cake in inventory: <NEW_LINE> <INDENT> possible_values += max_duffel_bag_value(inventory, capacity=capacity-cake[0], value=value + cake[1], memo=memo); <NEW_LINE> <DEDENT> if value == 0: <NEW_LINE> <INDENT> print(memo) <NEW_LINE> return max(possible_values) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> memo[capacity] = max(possible_values); <NEW_LINE> return [memo[capacity]]; | Use dynamic programming | 625941b7283ffb24f3c55748 |
def test_request_invalid_name(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> self.miner.request = 'SomeName' | Неверный формат запроса, имя
| 625941b7460517430c393fcb |
def do_version(self, line): <NEW_LINE> <INDENT> import version <NEW_LINE> logging.info('pyraxshell version: %s' % version.VERSION) | display pyraxshell version | 625941b730c21e258bdfa2d9 |
def right_left_rotate(node): <NEW_LINE> <INDENT> node.right = left_left_rotate(node.right) <NEW_LINE> return right_right_rotate(node) | AVL right left
:param node: operate node -- |height|>1
:return: None | 625941b73c8af77a43ae35da |
def main(): <NEW_LINE> <INDENT> readme_fullpath = os.path.join(os.path.expanduser("~"), readme_file) <NEW_LINE> ip_addr = cmd_output("ifconfig | grep -A 1 eth0 | grep inet | sed -nr 's/.*?addr:([0-9\\.]+).*/\\1/p'") <NEW_LINE> with open(readme_fullpath, "wb") as f: <NEW_LINE> <INDENT> f.write(readme_text.format( ip_address = ip_addr, username = getpass.getuser() )) | Body of script. | 625941b755399d3f055884ef |
def _get_start_pose(self): <NEW_LINE> <INDENT> if self.real_robot: <NEW_LINE> <INDENT> start_pose = self.client.get_state_msg().state[3:6] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = self.np_random.uniform(low= -2.0, high= 2.0) <NEW_LINE> y = self.np_random.uniform(low= -2.0, high= 2.0) <NEW_LINE> yaw = self.np_random.uniform(low= -np.pi, high= np.pi) <NEW_LINE> start_pose = [x,y,yaw] <NEW_LINE> <DEDENT> return start_pose | Get initial robot coordinates.
For the real robot the initial coordinates are its current coordinates
whereas for the simulated robot the initial coordinates are
randomly generated.
Returns:
numpy.array: [x,y,yaw] robot initial coordinates. | 625941b77b25080760e39297 |
def test_render_admin_panel(self): <NEW_LINE> <INDENT> req = MockRequest(self.env, path_info='/admin/general/logging', method='GET') <NEW_LINE> mod = AdminModule(self.env) <NEW_LINE> self.assertTrue(mod.match_request(req)) <NEW_LINE> data = mod.process_request(req)[1] <NEW_LINE> self.assertEqual('none', data['log']['type']) <NEW_LINE> self.assertEqual(['none', 'stderr', 'file', 'syslog', 'eventlog'], [t['name'] for t in data['log']['types']]) <NEW_LINE> self.assertEqual('DEBUG', data['log']['level']) <NEW_LINE> self.assertEqual(['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'], data['log']['levels']) <NEW_LINE> self.assertEqual('trac.log', data['log']['file']) <NEW_LINE> self.assertEqual(self.env.log_dir, data['log']['dir']) | GET request for admin panel. | 625941b76fb2d068a760eede |
def txt(self): <NEW_LINE> <INDENT> link = "{}.{}".format(self.link, 'txt') <NEW_LINE> df = pd.read_csv(link, delim_whitespace=True, na_values='MM', parse_dates=[[0,1,2,3,4]], index_col=0) <NEW_LINE> try: <NEW_LINE> <INDENT> df.drop(df.index[0], inplace=True) <NEW_LINE> df.index = pd.to_datetime(df.index,format="%Y %m %d %H %M") <NEW_LINE> cols = ['WDIR','WSPD','GST','WVHT','DPD','APD','MWD', 'PRES','ATMP','WTMP','DEWP','VIS','PTDY','TIDE'] <NEW_LINE> df[cols] = df[cols].astype(float) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> df.index = pd.to_datetime(df.index,format="%Y %m %d %H %M") <NEW_LINE> cols = ['WD','WSPD','GST','WVHT','DPD','APD','MWD','BARO', 'ATMP','WTMP','DEWP','VIS','PTDY','TIDE'] <NEW_LINE> df[cols] = df[cols].astype(float) <NEW_LINE> <DEDENT> df.index.name='Date' <NEW_LINE> return df | Retrieve standard Meteorological data. NDBC seems to be updating
the data with different column names, so this metric can return
two possible data frames with different column names:
Returns
-------
df : pandas dataframe
Index is the date and the columns can be:
['WDIR','WSPD','GST','WVHT','DPD','APD','MWD',
'PRES','ATMP','WTMP','DEWP','VIS','PTDY','TIDE']
or
['WD','WSPD','GST','WVHT','DPD','APD','MWD','BARO',
'ATMP','WTMP','DEWP','VIS','PTDY','TIDE'] | 625941b75510c4643540f234 |
def __init__(self, num_layers, hidden_dim): <NEW_LINE> <INDENT> super(TimitMelClassifier, self).__init__() <NEW_LINE> embedding_dim = 80 <NEW_LINE> output_dim = 61 <NEW_LINE> self.input_layer = nn.Linear(embedding_dim, hidden_dim) <NEW_LINE> self.net = nn.ModuleList([ nn.Linear(hidden_dim, hidden_dim) for _ in range(num_layers)]) <NEW_LINE> self.output_layer = nn.Linear(hidden_dim, output_dim) <NEW_LINE> self.relu = nn.ReLU() | Initialize layers.
Args:
num_layers (int): number of layers to use in the network.
hidden_dim (int): dimension of data passing between layers. | 625941b7a17c0f6771cbde90 |
def decks_expired(decks, expired=timedelta(days=1)): <NEW_LINE> <INDENT> if os.path.isfile(decks.json_path): <NEW_LINE> <INDENT> m_time = os.path.getmtime(decks.json_path) <NEW_LINE> if datetime.fromtimestamp(m_time) < (datetime.today() - expired): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True | 检查 Decks 是否已过期
:param decks: Decks 对象
:param expired: 有效期长度
:return: 若已过期则返回True | 625941b78e05c05ec3eea1ad |
def test_project_upload_session_status_get(self): <NEW_LINE> <INDENT> pass | Test case for project_upload_session_status_get
| 625941b7293b9510aa2c30d5 |
def get_ClosestNode_in_FingerTable(self, KID): <NEW_LINE> <INDENT> for i in range(M)[::-1]: <NEW_LINE> <INDENT> curr = (self.NID+2**i) % MAX_SIZE <NEW_LINE> if self.FingerTable[curr] is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif (self.in_interval(self.FingerTable[curr].NID, self.NID, KID)): <NEW_LINE> <INDENT> return self.FingerTable[curr] | find_successor的辅助函数:寻找在FingerTable中距离某个ID最近的节点
| 625941b74e4d5625662d4219 |
def plot_pauli_weight(weights,var, pnames, n): <NEW_LINE> <INDENT> fig1 = plt.figure(figsize=(12,11)) <NEW_LINE> x = np.arange(0,2**(2*n)); <NEW_LINE> z = weights.copy() <NEW_LINE> z1 = z - abs(var) <NEW_LINE> z2 = 2*abs(var) <NEW_LINE> z1[0] = 0 <NEW_LINE> z2[0] = 0 <NEW_LINE> ax1 = fig1.gca() <NEW_LINE> ax1.bar(x,z1) <NEW_LINE> ax1.bar(x,z2,bottom=z1) <NEW_LINE> plt.xticks(np.arange(0,2**(2*n)),pnames) | Make a bar plot of the elements in pauli weights in 'weights'. The xticks should be provided in pnames.
The first bar, corresponding to the weight on the identity matrix, is intentionally left out.
The error in 'var' is plotted over the normal bars, as in plot_city_with_var | 625941b7b830903b967e9753 |
def test_parse_kml_url(self): <NEW_LINE> <INDENT> url = 'http://code.google.com/apis/kml/documentation/kmlfiles/altitudemode_reference.kml' <NEW_LINE> fileobject = urllib2.urlopen(url) <NEW_LINE> tree = parse(fileobject, schema=Schema('kml22gx.xsd')) <NEW_LINE> self.assertEquals( etree.tostring(tree)[:185], '<kml xmlns="http://www.opengis.net/kml/2.2" ' 'xmlns:gx="http://www.google.com/kml/ext/2.2">' '<!-- required when using gx-prefixed elements -->' '<Placemark>' '<name>gx:altitudeMode Example</name>' ) | Tests the parsing of a KML URL | 625941b701c39578d7e74c80 |
def do_stdout(self, role): <NEW_LINE> <INDENT> self.get_log(role, log_type="stdout") | Download stdout file for role
Usage:
> stdout <role> Download stdout | 625941b7a79ad161976cbf82 |
def just_table(generator, kira_object): <NEW_LINE> <INDENT> if JTABLE_SEPARATOR in generator.settings: <NEW_LINE> <INDENT> separator = generator.settings[JTABLE_SEPARATOR] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> separator = DEFAULT_SEPARATOR <NEW_LINE> <DEDENT> if JTABLE_TEMPLATE in generator.settings: <NEW_LINE> <INDENT> table_template = generator.settings[JTABLE_TEMPLATE] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> table_template = DEFAULT_TEMPATE <NEW_LINE> <DEDENT> template = Template(table_template) <NEW_LINE> for match in MAIN_REGEX.findall(kira_object._content): <NEW_LINE> <INDENT> all_match_str, props, table_data = match <NEW_LINE> param = {"ai": 0, "th": 1, "caption": "", "sep": separator} <NEW_LINE> if AUTO_INCREMENT_REGEX.search(props): <NEW_LINE> <INDENT> param["ai"] = 1 <NEW_LINE> <DEDENT> if CAPTION_REGEX.search(props): <NEW_LINE> <INDENT> param["caption"] = CAPTION_REGEX.findall(props)[0] <NEW_LINE> <DEDENT> if TABLE_HEADER_REGEX.search(props): <NEW_LINE> <INDENT> param["th"] = 0 <NEW_LINE> <DEDENT> if SEPARATOR_REGEX.search(props): <NEW_LINE> <INDENT> param["sep"] = SEPARATOR_REGEX.findall(props)[0] <NEW_LINE> <DEDENT> table_data_list = table_data.strip().split("\n") <NEW_LINE> if len(table_data_list) >= 1: <NEW_LINE> <INDENT> heads = table_data_list[0].split( param["sep"]) if param["th"] else None <NEW_LINE> if heads: <NEW_LINE> <INDENT> bodies = [ n.split(param["sep"], len(heads) - 1) for n in table_data_list[1:] ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bodies = [n.split(param["sep"]) for n in table_data_list] <NEW_LINE> <DEDENT> context = generator.context.copy() <NEW_LINE> context.update({"heads": heads, "bodies": bodies}) <NEW_LINE> context.update(param) <NEW_LINE> replacement = template.render(context) <NEW_LINE> kira_object._content = kira_object._content.replace( "".join(all_match_str), replacement ) | Generate table. | 625941b74527f215b584c297 |
def emd(x, nIMF=3, stoplim=.001): <NEW_LINE> <INDENT> r = x <NEW_LINE> t = np.arange(len(r)) <NEW_LINE> imfs = np.zeros(nIMF, dtype=object) <NEW_LINE> for i in range(nIMF): <NEW_LINE> <INDENT> r_t = r <NEW_LINE> is_imf = False <NEW_LINE> while is_imf == False: <NEW_LINE> <INDENT> pks = sp.signal.argrelmax(r_t)[0] <NEW_LINE> trs = sp.signal.argrelmin(r_t)[0] <NEW_LINE> pks_r = r_t[pks] <NEW_LINE> fip = sp.interpolate.InterpolatedUnivariateSpline(pks, pks_r, k=3) <NEW_LINE> pks_t = fip(t) <NEW_LINE> trs_r = r_t[trs] <NEW_LINE> fitr = sp.interpolate.InterpolatedUnivariateSpline(trs, trs_r, k=3) <NEW_LINE> trs_t = fitr(t) <NEW_LINE> mean_t = (pks_t + trs_t) / 2 <NEW_LINE> mean_t = _emd_complim(mean_t, pks, trs) <NEW_LINE> sdk = _emd_comperror(r_t, mean_t, pks, trs) <NEW_LINE> if sdk < stoplim: <NEW_LINE> <INDENT> is_imf = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r_t = r_t - mean_t <NEW_LINE> <DEDENT> <DEDENT> imfs[i] = r_t <NEW_LINE> r = r - imfs[i] <NEW_LINE> <DEDENT> return imfs | Perform empirical mode decomposition to extract 'niMF' components out of the signal 'x'. | 625941b7cad5886f8bd26e1e |
def parse_item_page(self, response): <NEW_LINE> <INDENT> raw_text_path = '//div[contains(@class, "txt-box")]/pre[contains(@class, "styled")]' <NEW_LINE> linked_text_path = '//div[contains(@class, "txt-box")]/pre[contains(@class, "styled")]/a/text()' <NEW_LINE> date_path = '//div[contains(@class, "cr-issue")]/h3/text()' <NEW_LINE> blurb_path = '//div[contains(@class, "cr-issue")]/h4/text()' <NEW_LINE> title_path = '//div[contains(@class, "wrapper_std")]/h2/text()' <NEW_LINE> linked_text = response.xpath(linked_text_path).extract() <NEW_LINE> raw_date = response.xpath(date_path).extract_first() <NEW_LINE> date = arrow.get(raw_date, 'MMMM D, YYYY ').datetime <NEW_LINE> blurb = response.xpath(blurb_path).extract() <NEW_LINE> title = response.xpath(title_path).extract_first() <NEW_LINE> nth_congress_session = blurb[0] <NEW_LINE> issue_vol = blurb[1] <NEW_LINE> def get_nth_congress_session(the_string): <NEW_LINE> <INDENT> regex_string = '([0-9]+).* Congress, ([0-9]+).* Session' <NEW_LINE> match = re.search(regex_string, the_string) <NEW_LINE> if match: <NEW_LINE> <INDENT> (congress, session) = match.groups() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (congress, session) = (None, None) <NEW_LINE> <DEDENT> return (congress, session) <NEW_LINE> <DEDENT> def get_volume_issue(the_string): <NEW_LINE> <INDENT> regex_string = '([0-9]+).* Congress, ([0-9]+).* Session' <NEW_LINE> regex_string = 'Issue: Vol\. ([0-9]+), No\. ([0-9]+)' <NEW_LINE> match = re.search(regex_string, the_string) <NEW_LINE> if match: <NEW_LINE> <INDENT> (volume, issue) = match.groups() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (volume, issue) = (None, None) <NEW_LINE> <DEDENT> return (volume, issue) <NEW_LINE> <DEDENT> (congress, session) = get_nth_congress_session(nth_congress_session) <NEW_LINE> (volume, issue) = get_volume_issue(issue_vol) <NEW_LINE> def get_page_range(linked_text): <NEW_LINE> <INDENT> regex_string = 'Page[s]* ([A-Z][0-9]+)\-?([A-Z][0-9]+)?' <NEW_LINE> for text in linked_text: <NEW_LINE> <INDENT> match = re.search(regex_string, text) <NEW_LINE> if match: <NEW_LINE> <INDENT> (first, last) = match.groups() <NEW_LINE> if last is None: <NEW_LINE> <INDENT> last = first <NEW_LINE> <DEDENT> return (first, last) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> (start, end) = get_page_range(linked_text) <NEW_LINE> def get_clean_text(raw_text): <NEW_LINE> <INDENT> clean = '' <NEW_LINE> for text in raw_text.xpath('.//text()').extract(): <NEW_LINE> <INDENT> clean += text <NEW_LINE> <DEDENT> return clean <NEW_LINE> <DEDENT> text = get_clean_text(response.xpath(raw_text_path)) <NEW_LINE> item = CongressItem( url=response.url, title=title, date=date, congress=congress, session=session, issue=issue, volume=volume, start_page=start, end_page=end, text=text ) <NEW_LINE> return item | Parse and item page to scrape individual CongressItem's | 625941b732920d7e50b28008 |
def pass_on_change_section(context): <NEW_LINE> <INDENT> document = context.cur.document <NEW_LINE> if document is not None: <NEW_LINE> <INDENT> context.passOn(document) | pass the change event directly to the document in question
don't go through all parents | 625941b7956e5f7376d70cb7 |
def prime_num_gen(n): <NEW_LINE> <INDENT> if n < 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif n == 2: <NEW_LINE> <INDENT> return [2] <NEW_LINE> <DEDENT> elif n ==1 or n == 0: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if isinstance(n, str): <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> if isinstance(n, float): <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> if isinstance(n, list): <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> prime_nums = [2] <NEW_LINE> for i in range(3,n+1): <NEW_LINE> <INDENT> factor_count=0 <NEW_LINE> for x in range (2,i): <NEW_LINE> <INDENT> if i % x == 0: <NEW_LINE> <INDENT> factor_count+=1 <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if factor_count==0: <NEW_LINE> <INDENT> prime_nums.append(i) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except TypeError as e: <NEW_LINE> <INDENT> raise(e) <NEW_LINE> <DEDENT> except NameError as e: <NEW_LINE> <INDENT> raise(e) <NEW_LINE> <DEDENT> return prime_nums | This function takes a given number n as an argument
and generates prime numbers ranging from zero to n
Prime Numbers: A number with only two factors - one and itself | 625941b71f5feb6acb0c4991 |
def test_input_coordinates(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError) as raised_exception: <NEW_LINE> <INDENT> square.input_coordinates() <NEW_LINE> <DEDENT> self.assertEqual('Type wrong', raised_exception.exception.args[0]) | Тестирует выброс ошибки (в любом случае) в функции input_coordinates (ввод данных) модуля square.py | 625941b75fdd1c0f98dc006e |
def _query(self, query_string, to_numeric): <NEW_LINE> <INDENT> result = self._query_platform(query_string) <NEW_LINE> output = self._bindings_to_dataframe( bindings=result['data']['results']['bindings'], to_numeric=to_numeric) <NEW_LINE> return output | Helper to perform a data query for named objects.
NOTE: All queries MUST return an object name. If this is too
restrictive it can be modified later.
:param query_string: Fully formatted SPARQL query.
:param to_numeric: True/False, whether or not to attempt to
convert DataFrame columns to numeric values. Set to True if
some columns will be numeric, set to False if no columns
will be numeric. | 625941b755399d3f055884f0 |
def test_duplicate(self, filename='test_duplicate.csv'): <NEW_LINE> <INDENT> self.deduplicate = True <NEW_LINE> self.command(filename, expected_errs = ['Imported 3 rows to Item']) <NEW_LINE> items = Item.objects.all().order_by('code_share') <NEW_LINE> self.assertEqual(len(items), 3) <NEW_LINE> codes = (u'bucket', u'tent', u'watercan') <NEW_LINE> for i, item in enumerate(items): <NEW_LINE> <INDENT> self.assertEqual(item.code_share, codes[i]) <NEW_LINE> <DEDENT> self.command(filename, expected_errs = ['Imported 6 rows to Item'], deduplicate=False) <NEW_LINE> items = Item.objects.all().order_by('code_share') <NEW_LINE> self.assertEqual(len(items), 3 + 6) <NEW_LINE> Item.objects.all().delete() | Use custom command to upload file and parse it into Items | 625941b715fb5d323cde0946 |
def _query_account_rg(cli_ctx, account_name): <NEW_LINE> <INDENT> scf = storage_client_factory(cli_ctx) <NEW_LINE> acc = next((x for x in scf.storage_accounts.list() if x.name == account_name), None) <NEW_LINE> if acc: <NEW_LINE> <INDENT> from msrestazure.tools import parse_resource_id <NEW_LINE> return parse_resource_id(acc.id)['resource_group'], scf <NEW_LINE> <DEDENT> raise ValueError("Storage account '{}' not found.".format(account_name)) | Query the storage account's resource group, which the mgmt sdk requires. | 625941b7c4546d3d9de7286d |
def _reduced_kernel_size_for_small_input(input_tensor, kernel_size): <NEW_LINE> <INDENT> shape = input_tensor.get_shape().as_list() <NEW_LINE> if shape[1] is None or shape[2] is None: <NEW_LINE> <INDENT> kernel_size_out = kernel_size <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> kernel_size_out = [shape[1],shape[2]] <NEW_LINE> <DEDENT> return kernel_size_out | Define kernel size which is automatically reduced for small input.
If the shape of the input images is unknown at graph construction time this
function assumes that the input images are is large enough.
Args:
input_tensor: input tensor of size [batch_size, height, width, channels].
kernel_size: desired kernel size of length 2: [kernel_height, kernel_width]
Returns:
a tensor with the kernel size.
TODO(jrru): Make this function work with unknown shapes. Theoretically, this
can be done with the code below. Problems are two-fold: (1) If the shape was
known, it will be lost. (2) inception.slim.ops._two_element_tuple cannot
handle tensors that define the kernel size.
shape = tf.shape(input_tensor)
return = tf.stack([tf.minimum(shape[1], kernel_size[0]),
tf.minimum(shape[2], kernel_size[1])]) | 625941b78e7ae83300e4ae08 |
def _wait_for(obj, target_state, poll_sec=1.5, wait_sec=600): <NEW_LINE> <INDENT> def _state(x): <NEW_LINE> <INDENT> return x.state if hasattr(x, 'state') else x.status <NEW_LINE> <DEDENT> def _logstate(x): <NEW_LINE> <INDENT> logging.debug('{} state={}'.format(x.id, repr(_state(x)))) <NEW_LINE> <DEDENT> clock = 0 <NEW_LINE> logging.info('Waiting for ' + obj.id) <NEW_LINE> _logstate(obj) <NEW_LINE> while _state(obj) != target_state and clock < wait_sec: <NEW_LINE> <INDENT> _logstate(obj) <NEW_LINE> time.sleep(poll_sec) <NEW_LINE> clock += poll_sec <NEW_LINE> obj.update() <NEW_LINE> <DEDENT> if _state(obj) != target_state: <NEW_LINE> <INDENT> raise _TimeoutError('timeout while waiting for ' + repr(obj.id)) | Wait for object to change state.
Raise _TimeoutError on failure. | 625941b73346ee7daa2b2ba6 |
def showGame(): <NEW_LINE> <INDENT> print('-------------------------------------') <NEW_LINE> print("| ", end='') <NEW_LINE> for i in Game: <NEW_LINE> <INDENT> print(i, end=' | ' ) <NEW_LINE> <DEDENT> print('\n-------------------------------------') <NEW_LINE> return None | Affiche le plateau de jeux
:return: None | 625941b7f7d966606f6a9e45 |
def set_initial_state(self): <NEW_LINE> <INDENT> self.board = [[Rook(1), Pawn(1), 0, 0, 0, 0, Pawn(0), Rook(0)], [Knight(1), Pawn(1), 0, 0, 0, 0, Pawn(0), Knight(0)], [Bishop(1), Pawn(1), 0, 0, 0, 0, Pawn(0), Bishop(0)], [Queen(1), Pawn(1), 0, 0, 0, 0, Pawn(0), Queen(0)], [King(1), Pawn(1), 0, 0, 0, 0, Pawn(0), King(0)], [Bishop(1), Pawn(1), 0, 0, 0, 0, Pawn(0), Bishop(0)], [Knight(1), Pawn(1), 0, 0, 0, 0, Pawn(0), Knight(0)], [Rook(1), Pawn(1), 0, 0, 0, 0, Pawn(0), Rook(0)]] | Creates and initializes the board | 625941b7d8ef3951e324337a |
def test_send(self): <NEW_LINE> <INDENT> contact = PeerNode(PUBLIC_KEY, self.version, 'http://192.168.0.1:80') <NEW_LINE> msg = OK('uuid', 'recipient', 'sender', 9999, 'version', 'seal') <NEW_LINE> msg_json = json.dumps(to_dict(msg)) <NEW_LINE> headers = {'content-type': 'application/json'} <NEW_LINE> connector = HttpConnector(self.event_loop) <NEW_LINE> @asyncio.coroutine <NEW_LINE> def faux_request(*args, **kwargs): <NEW_LINE> <INDENT> return 'foo' <NEW_LINE> <DEDENT> with mock.patch.object(aiohttp, 'request', return_value=faux_request()) as request: <NEW_LINE> <INDENT> result = connector.send(contact, msg) <NEW_LINE> self.assertIsInstance(result, asyncio.Task) <NEW_LINE> request.assert_called_once_with('post', contact.uri, data=msg_json, headers=headers) | Test the good case. We should end up with a task wrapping an
appropriate call to aiohttp.request. | 625941b773bcbd0ca4b2beba |
def update_test_plan(self, plan_update_model, project, plan_id): <NEW_LINE> <INDENT> route_values = {} <NEW_LINE> if project is not None: <NEW_LINE> <INDENT> route_values['project'] = self._serialize.url('project', project, 'str') <NEW_LINE> <DEDENT> if plan_id is not None: <NEW_LINE> <INDENT> route_values['planId'] = self._serialize.url('plan_id', plan_id, 'int') <NEW_LINE> <DEDENT> content = self._serialize.body(plan_update_model, 'PlanUpdateModel') <NEW_LINE> response = self._send(http_method='PATCH', location_id='51712106-7278-4208-8563-1c96f40cf5e4', version='4.0', route_values=route_values, content=content) <NEW_LINE> return self._deserialize('TestPlan', response) | UpdateTestPlan.
:param :class:`<PlanUpdateModel> <test.v4_0.models.PlanUpdateModel>` plan_update_model:
:param str project: Project ID or project name
:param int plan_id:
:rtype: :class:`<TestPlan> <test.v4_0.models.TestPlan>` | 625941b7e1aae11d1e749af0 |
def step(self, epoch=None): <NEW_LINE> <INDENT> if epoch is None: <NEW_LINE> <INDENT> epoch = self.last_epoch + 1 <NEW_LINE> self.T_cur = self.T_cur + 1 <NEW_LINE> if self.T_cur >= self.T_i: <NEW_LINE> <INDENT> self.T_cur = self.T_cur - self.T_i <NEW_LINE> self.T_i = self.T_i * self.T_mult <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if epoch < 0: <NEW_LINE> <INDENT> raise ValueError("Expected non-negative epoch, but got {}".format(epoch)) <NEW_LINE> <DEDENT> if epoch >= self.T_0: <NEW_LINE> <INDENT> if self.T_mult == 1: <NEW_LINE> <INDENT> self.T_cur = epoch % self.T_0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> n = int(math.log((epoch / self.T_0 * (self.T_mult - 1) + 1), self.T_mult)) <NEW_LINE> self.T_cur = epoch - self.T_0 * (self.T_mult ** n - 1) / (self.T_mult - 1) <NEW_LINE> self.T_i = self.T_0 * self.T_mult ** (n) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.T_i = self.T_0 <NEW_LINE> self.T_cur = epoch <NEW_LINE> <DEDENT> <DEDENT> self.last_epoch = math.floor(epoch) <NEW_LINE> for param_group, lr in zip(self.optimizer.param_groups, self.get_lr()): <NEW_LINE> <INDENT> param_group['lr'] = lr | Step could be called after every batch update
Example:
>>> scheduler = CosineAnnealingWarmRestarts(optimizer, T_0, T_mult)
>>> iters = len(dataloader)
>>> for epoch in range(20):
>>> for i, sample in enumerate(dataloader):
>>> inputs, labels = sample['inputs'], sample['labels']
>>> scheduler.step(epoch + i / iters)
>>> optimizer.zero_grad()
>>> outputs = net(inputs)
>>> loss = criterion(outputs, labels)
>>> loss.backward()
>>> optimizer.step()
This function can be called in an interleaved way.
Example:
>>> scheduler = CosineAnnealingWarmRestarts(optimizer, T_0, T_mult)
>>> for epoch in range(20):
>>> scheduler.step()
>>> scheduler.step(26)
>>> scheduler.step() # scheduler.step(27), instead of scheduler(20) | 625941b707d97122c41786c8 |
def add_new_urls(self, urls): <NEW_LINE> <INDENT> if urls is None or len(urls) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for url in urls: <NEW_LINE> <INDENT> self.add_new_url(url) | 把新的url添加到未爬取的url集合中
:param urls: url集合
:return: | 625941b7aad79263cf390877 |
def deserialize(self, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> end = 0 <NEW_LINE> start = end <NEW_LINE> end += 4 <NEW_LINE> (length,) = _struct_I.unpack(str[start:end]) <NEW_LINE> start = end <NEW_LINE> end += length <NEW_LINE> if python3: <NEW_LINE> <INDENT> self.belief = str[start:end].decode('utf-8') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.belief = str[start:end] <NEW_LINE> <DEDENT> start = end <NEW_LINE> end += 1 <NEW_LINE> (self.value,) = _struct_b.unpack(str[start:end]) <NEW_LINE> return self <NEW_LINE> <DEDENT> except struct.error as e: <NEW_LINE> <INDENT> raise genpy.DeserializationError(e) | unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str`` | 625941b766673b3332b91ed4 |
def __init__(self, master_window): <NEW_LINE> <INDENT> self._ok_clicked = False <NEW_LINE> self._sidebar = tkinter.Frame( master = master_window, background = DEFAULT_GRAY) <NEW_LINE> self._sidebar.grid( row = 0, column = 1, padx = 30, pady = 10, sticky = tkinter.N + tkinter.S + tkinter.E + tkinter.W) <NEW_LINE> self.display_score() <NEW_LINE> self.get_game_input() <NEW_LINE> self._sidebar.rowconfigure(0, weight = 1) <NEW_LINE> self._sidebar.rowconfigure(2, weight = 1) <NEW_LINE> self._sidebar.rowconfigure(3, weight = 1) <NEW_LINE> self._sidebar.rowconfigure(4, weight = 1) <NEW_LINE> self._sidebar.rowconfigure(5, weight = 1) <NEW_LINE> self._sidebar.rowconfigure(6, weight = 1) <NEW_LINE> self._sidebar.rowconfigure(7, weight = 1) <NEW_LINE> self._sidebar.rowconfigure(8, weight = 1) <NEW_LINE> self._sidebar.rowconfigure(9, weight = 1) <NEW_LINE> self._sidebar.rowconfigure(10, weight = 1) <NEW_LINE> self._sidebar.columnconfigure(0, weight = 1) | Starts the popup window and displays score and toggles settings | 625941b79b70327d1c4e0c10 |
def syllabify(self, hierarchy): <NEW_LINE> <INDENT> if len(self.long_lines) == 0: <NEW_LINE> <INDENT> logger.error("No text was imported") <NEW_LINE> self.syllabified_text = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> syllabifier = Syllabifier(language="old_norse", break_geminants=True) <NEW_LINE> syllabifier.set_hierarchy(hierarchy) <NEW_LINE> syllabified_text = [] <NEW_LINE> for i, long_line in enumerate(self.long_lines): <NEW_LINE> <INDENT> syllabified_text.append([]) <NEW_LINE> for short_line in long_line: <NEW_LINE> <INDENT> assert isinstance(short_line, ShortLine) or isinstance(short_line, LongLine) <NEW_LINE> short_line.syllabify(syllabifier) <NEW_LINE> syllabified_text[i].append(short_line.syllabified) <NEW_LINE> <DEDENT> <DEDENT> self.syllabified_text = syllabified_text | Syllables may play a role in verse classification. | 625941b71f037a2d8b94603c |
def is_number_or_english(text): <NEW_LINE> <INDENT> judge = False <NEW_LINE> try: <NEW_LINE> <INDENT> sentence_punctuation_clear = get_syboml(text) <NEW_LINE> sentence_punctuation_clear = sentence_punctuation_clear.replace(' ', '').strip() <NEW_LINE> for words in sentence_punctuation_clear: <NEW_LINE> <INDENT> judge_number = is_total_number(words) <NEW_LINE> judge_english = is_total_english(words) <NEW_LINE> judge = judge_number or judge_english <NEW_LINE> if not judge: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return judge <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False | 不为数字不为字母 | 625941b7099cdd3c635f0a99 |
def add_bot_commands_formatting(self, commands, heading): <NEW_LINE> <INDENT> if commands: <NEW_LINE> <INDENT> joined = '\u2002'.join(c.name for c in commands) <NEW_LINE> self.paginator.add_line('__**%s**__' % heading) <NEW_LINE> self.paginator.add_line('%s\n' % joined) | Adds the minified bot heading with commands to the output.
The formatting should be added to the :attr:`paginator`.
The default implementation is a bold underline heading followed
by commands separated by an EN SPACE (U+2002) in the next line.
Parameters
-----------
commands: Sequence[:class:`Command`]
A list of commands that belong to the heading.
heading: :class:`str`
The heading to add to the line. | 625941b766656f66f7cbbfe7 |
def A7int_function(radius): <NEW_LINE> <INDENT> return radius**2. * density(radius)**(GAMMA + 1.) | Voir equation A.7 in Labrosse 2015, this is the function inside the integrale | 625941b7cdde0d52a9e52e6c |
def testMandChar(t, env): <NEW_LINE> <INDENT> _try_mand(env, env.opts.usechar) | VERIFY mandatory attributes against getattr
FLAGS: verify char all
DEPEND: LOOKCHAR
CODE: VF1c | 625941b724f1403a926009a7 |
def get_trader_instruments(self): <NEW_LINE> <INDENT> response = self.make_authorized_request(self.get_path, interface.ApiPath.GET_TRADER_INSTRUMENTS.value) <NEW_LINE> if response.status_code == interface.SUCCESS: <NEW_LINE> <INDENT> instruments = response.json() <NEW_LINE> for instrument in instruments: <NEW_LINE> <INDENT> convert_instrument_numbers(instrument) <NEW_LINE> <DEDENT> return instruments <NEW_LINE> <DEDENT> message_raiser('Failed to get the trader instruments. {error_message}', error_message=get_error_message(response)) | Gets the available instruments for the trader.
:returns: The list of instruments.
:rtype: list of dicts. Each element has the following data:
id (int)
description (string)
name (string)
baseCurrencyID (int) - The currency you bid for, i.e. for the
Bitcoin/Euro base currency is the Bitcoin.
quoteCurrencyID (int) - The currency you pay with, i.e. for the
Bitcoin/Euro quote currency is the Euro.
minOrderAmount (float) - The minimum order amount for an order.
Every order having an amount less than that, will be rejected.
commissionFeePercent (float) - The percent of the commission
fee when trading this instrument. The value is a decimal between 0 and 1.
:raises: requests.RequestException | 625941b707f4c71912b112c4 |
def get_current_player(self): <NEW_LINE> <INDENT> return self.__current_player | This method returns the current player as a string 'black' or
'white'. | 625941b7377c676e91271fe7 |
def test_days_left_returns_none_if_no_expiration(self): <NEW_LINE> <INDENT> self.userplan.expire = None <NEW_LINE> self.assertIsNone(self.userplan.days_left()) | If expiration is none, days left should return None | 625941b7d10714528d5ffb1c |
def create_sprint(template_sprint_name, start_date, end_date): <NEW_LINE> <INDENT> new_sprint_name = get_new_sprint_name(template_sprint_name, start_date, end_date) <NEW_LINE> sprint = get_sprint_from_name(new_sprint_name) <NEW_LINE> delete_sprint(sprint) <NEW_LINE> time.sleep(1) <NEW_LINE> try: <NEW_LINE> <INDENT> sprint = get_client_instance().version.create( project_id='admin_project', name=new_sprint_name, status='open', sharing='system', description=CREATED_BY, sprint_start_date=start_date, effective_date=end_date) <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> abort("Unable to save sprint due: ".format(exc)) <NEW_LINE> <DEDENT> return sprint | Create a sprint with a specified name.
:param template_sprint_name: string representing the template to be copied
:return sprint: the new object | 625941b767a9b606de4a7cfa |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> from werkzeug.datastructures import MultiDict <NEW_LINE> args = [ MultiDict((k, l) for (k, l) in i.iteritems(True) if l != '') for i in list(args)] <NEW_LINE> super(FilterMsgMESSAGEForm, self).__init__(*args, **kwargs) <NEW_LINE> for n, f in iteritems(self._fields): <NEW_LINE> <INDENT> if hasattr(f, 'alias') and f.alias: <NEW_LINE> <INDENT> new = args[0].getlist(f.alias, None) <NEW_LINE> if new is not None: <NEW_LINE> <INDENT> new.reverse() <NEW_LINE> f.raw_data = new <NEW_LINE> <DEDENT> f.name = f.alias | Init. | 625941b7cc40096d61595790 |
def isPalindrome(self, s): <NEW_LINE> <INDENT> r = len(s) -1 <NEW_LINE> l = 0 <NEW_LINE> while l<r: <NEW_LINE> <INDENT> if not s[l].isalnum(): <NEW_LINE> <INDENT> l+=1 <NEW_LINE> <DEDENT> if not s[r].isalnum(): <NEW_LINE> <INDENT> r-=1 <NEW_LINE> <DEDENT> while l<r and s[l].isalnum() and s[r].isalnum(): <NEW_LINE> <INDENT> if s[l].lower()!=s[r].lower(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> l+=1 <NEW_LINE> r-=1 <NEW_LINE> <DEDENT> <DEDENT> return True | :type s: str
:rtype: bool | 625941b71d351010ab85595b |
def slugify(func): <NEW_LINE> <INDENT> def wrapped(*args, **kwargs): <NEW_LINE> <INDENT> if 'slug' in kwargs: <NEW_LINE> <INDENT> kwargs['original_slug'] = kwargs['slug'] <NEW_LINE> kwargs['slug'] = models.slugify(kwargs['slug']) <NEW_LINE> <DEDENT> return func(*args, **kwargs) <NEW_LINE> <DEDENT> return wrapped | Applies custom slugify to the slug and stashes original slug
| 625941b75e10d32532c5ed6c |
def test_help_commands_same_output(self): <NEW_LINE> <INDENT> outLong, errLong = run_jar_command(['--help']) <NEW_LINE> outShort, errShort = run_jar_command(['-h']) <NEW_LINE> self.assertEqual(outLong, outShort, "-h and --help returns different result!") | --help and -h return the same help menu
| 625941b763b5f9789fde6f22 |
@trollius.coroutine <NEW_LINE> def run(conf): <NEW_LINE> <INDENT> conf.evaluation_time = 5.0 <NEW_LINE> conf.output_directory = 'output' <NEW_LINE> world = yield From(World.create(conf)) <NEW_LINE> yield From(world.pause(True)) <NEW_LINE> for i in range(3): <NEW_LINE> <INDENT> ta, _, _ = yield From(world.generate_valid_robot()) <NEW_LINE> tb, _, _ = yield From(world.generate_valid_robot()) <NEW_LINE> ra = yield From(wait_for(world.insert_robot(ta, pose=Pose(position=Vector3(0, 3*i, 0.5))))) <NEW_LINE> rb = yield From(wait_for(world.insert_robot(tb, pose=Pose(position=Vector3(0, 3*i + 1, 0.5))))) <NEW_LINE> while True: <NEW_LINE> <INDENT> mate = yield From(world.attempt_mate(ra, rb)) <NEW_LINE> if mate: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> tree, bbox = mate <NEW_LINE> yield From(wait_for(world.insert_robot(tree, pose=Pose(position=Vector3(0, 3*i + 2, 0.5))))) | :param conf:
:return: | 625941b7a17c0f6771cbde91 |
def test_change_list_sorting_callable_query_expression(self): <NEW_LINE> <INDENT> tests = [ ('order_by_expression', 9), ('order_by_f_expression', 12), ('order_by_orderby_expression', 13), ] <NEW_LINE> for admin_order_field, index in tests: <NEW_LINE> <INDENT> with self.subTest(admin_order_field): <NEW_LINE> <INDENT> response = self.client.get( reverse('admin:admin_views_article_changelist'), {'o': index}, ) <NEW_LINE> self.assertContentBefore( response, 'Oldest content', 'Middle content', 'Results of sorting on callable are out of order.' ) <NEW_LINE> self.assertContentBefore( response, 'Middle content', 'Newest content', 'Results of sorting on callable are out of order.' ) | Query expressions may be used for admin_order_field. | 625941b70a50d4780f666ccc |
def jsonify(obj): <NEW_LINE> <INDENT> return flask.json.dumps(obj) | Turns an object into a json.
Return:
string: The json content that will be displayed in the template. | 625941b763f4b57ef0000f5f |
def derivativeD(Theta, r, c): <NEW_LINE> <INDENT> n,_ = Theta.shape <NEW_LINE> D = calcD(Theta) <NEW_LINE> P = toP(Theta) <NEW_LINE> Pi = ErgodicProjector(Theta) <NEW_LINE> derivP = derivativeP(Theta, r, c) <NEW_LINE> derivPi = derivativePi(Theta, r, c) <NEW_LINE> inv_term = np.linalg.inv((np.identity(n) - P + Pi)) <NEW_LINE> derivD = -inv_term@(-derivP + derivPi)@inv_term - derivPi <NEW_LINE> return derivD | Purpose:
Calculate the derivative of the deviation matrix of P(Theta) w.r.t. Theta(r,c)
Input:
Theta - a (nx(n-1))-matrix of angles
r - indicates the row of the theta element we differentiate to, i.e., for Theta(r,c).
c - indicates the column of the theta element we differentiate to, i.e., for Theta(r,c).
Output:
derivD - (nxn)-matrix of the derivative of the D(Theta) matrix | 625941b7fbf16365ca6f5ff9 |
def sanitized_shortid(self): <NEW_LINE> <INDENT> return self.shortid().translate(str.maketrans('($[]/ ','______', ')')) | Return a name that is suitable for creating file system names.
In particular, names with scenarios look like
'test_file.test_file.test_funcname(scen1.scen2.scen3)'.
So transform '(', but remove final ')'. | 625941b7a4f1c619b28afe7f |
def _set_context_to_file_resources(file_extension): <NEW_LINE> <INDENT> resource_search_action = tk.get_action('resource_search') <NEW_LINE> context = {'model': base.model, 'session': base.model.Session, 'user': tk.c.user or tk.c.author, 'for_view': True} <NEW_LINE> data_dict = {'query': ['format:' + file_extension]} <NEW_LINE> shape_file_resources = resource_search_action(context, data_dict)['results'] <NEW_LINE> file_resources = [] <NEW_LINE> resource = {'id': 0, 'name': 'Select a file ..'} <NEW_LINE> file_resources.append(resource) <NEW_LINE> for file_resource in shape_file_resources: <NEW_LINE> <INDENT> resource = {} <NEW_LINE> active_resource = _get_resource(file_resource['id']) <NEW_LINE> if not active_resource: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if file_resource['resource_type'] == 'file.link': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> user_owns_resource = uebhelper.is_user_owns_resource(file_resource['id'], tk.c.user) <NEW_LINE> if user_owns_resource: <NEW_LINE> <INDENT> resource['id'] = file_resource['id'] <NEW_LINE> resource['name'] = file_resource['name'] <NEW_LINE> file_resources.append(resource) <NEW_LINE> <DEDENT> <DEDENT> return file_resources | This will create a list of all files that has
extension of file_extension and return the matching list of
resources | 625941b763f4b57ef0000f60 |
def replace_vars_in_overlay(overlay_configs, values): <NEW_LINE> <INDENT> retval = [] <NEW_LINE> for o in overlay_configs: <NEW_LINE> <INDENT> retval.append(replace_vars_in_dict(o, values)) <NEW_LINE> <DEDENT> return retval | Replace all occurrences of variables in the configs with the values. | 625941b78c0ade5d55d3e7fd |
def get_partial_waves_for_atomic_orbitals(self): <NEW_LINE> <INDENT> if not hasattr(self, 'pseudo_partial_waves_j'): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> phit_j = [] <NEW_LINE> for n, phit in zip(self.n_j, self.pseudo_partial_waves_j): <NEW_LINE> <INDENT> if n > 0: <NEW_LINE> <INDENT> phit_j.append(phit) <NEW_LINE> <DEDENT> <DEDENT> return phit_j | Get those states phit that represent a real atomic state.
This typically corresponds to the (truncated) partial waves (PAW) or
a single-zeta basis. | 625941b7379a373c97cfa988 |
def send_many(kwargs_list): <NEW_LINE> <INDENT> emails = [] <NEW_LINE> for kwargs in kwargs_list: <NEW_LINE> <INDENT> emails.append(send(commit=False, **kwargs)) <NEW_LINE> <DEDENT> if len(emails) > 0: <NEW_LINE> <INDENT> Email.objects.bulk_create(emails) <NEW_LINE> email_queued.send(sender=Email, emails=emails) | Similar to mail.send(), but this function accepts a list of kwargs.
Internally, it uses Django's bulk_create command for efficiency reasons.
Currently send_many() can't be used to send emails with priority = 'now'. | 625941b796565a6dacc8f512 |
def test_area_of_circle_sanity(self): <NEW_LINE> <INDENT> result = math_functions.area_of_circle(1) <NEW_LINE> expected = 1 <NEW_LINE> self.assertEqual(expected, result) | area_of_circle(1) | 625941b7046cf37aa974cb88 |
def override_config_data(self, args): <NEW_LINE> <INDENT> if args.rhost is not None: <NEW_LINE> <INDENT> self.config_vars["target_system"] = args.rhost <NEW_LINE> <DEDENT> if args.user is not None: <NEW_LINE> <INDENT> self.config_vars["username"] = args.user <NEW_LINE> <DEDENT> if args.password is not None: <NEW_LINE> <INDENT> self.config_vars["password"] = args.password <NEW_LINE> <DEDENT> if args.token is not None: <NEW_LINE> <INDENT> self.config_vars["token"] = args.token <NEW_LINE> <DEDENT> if args.secure is not None: <NEW_LINE> <INDENT> self.config_vars["https"] = args.secure <NEW_LINE> self.config_vars["scheme"] = "http" if args.secure == "Never" else "https" <NEW_LINE> <DEDENT> if args.directory is not None: <NEW_LINE> <INDENT> self.config_vars["output_subdir"] = args.directory <NEW_LINE> <DEDENT> if args.interpreter is not None: <NEW_LINE> <INDENT> self.config_vars["interpreter"] = args.interpreter <NEW_LINE> <DEDENT> if args.scheme is not None: <NEW_LINE> <INDENT> self.config_vars["scheme"] = args.scheme <NEW_LINE> <DEDENT> if args.base_url is not None: <NEW_LINE> <INDENT> self.config_vars["base_url"] = args.base_url <NEW_LINE> <DEDENT> elif args.secure is not None or args.rhost is not None: <NEW_LINE> <INDENT> self.config_vars["base_url"] = (self.config_vars["scheme"] + '://' + self.config_vars["target_system"]) | :param args: Namespace of command-line args (from argparse) | 625941b7796e427e537b0400 |
def trim(im): <NEW_LINE> <INDENT> bg = Image.new(im.mode, im.size, im.getpixel((0, 0))) <NEW_LINE> diff = ImageChops.difference(im, bg) <NEW_LINE> diff = ImageChops.add(diff, diff, 2.0, -100) <NEW_LINE> bbox = diff.getbbox() <NEW_LINE> if bbox: <NEW_LINE> <INDENT> im = im.crop(bbox) <NEW_LINE> <DEDENT> return im | Trim image and remove white space
| 625941b70383005118ecf422 |
@real_memoize <NEW_LINE> def is_aarch64(): <NEW_LINE> <INDENT> return platform.machine().startswith("aarch64") | Simple function to return if host is AArch64 or not | 625941b74428ac0f6e5ba62f |
def serialize_for_api(data): <NEW_LINE> <INDENT> if hasattr(data, 'to_api'): <NEW_LINE> <INDENT> return serialize_for_api(data.to_api()) <NEW_LINE> <DEDENT> elif isinstance(data, Response): <NEW_LINE> <INDENT> return serialize_for_api(data.hits._l_) <NEW_LINE> <DEDENT> elif isinstance(data, (AttrDict, ObjectBase)): <NEW_LINE> <INDENT> return data.to_dict() <NEW_LINE> <DEDENT> elif isinstance(data, AttrList): <NEW_LINE> <INDENT> return data._l_ <NEW_LINE> <DEDENT> elif isinstance(data, dict): <NEW_LINE> <INDENT> return {k: serialize_for_api(v) for k, v in data.items()} <NEW_LINE> <DEDENT> elif isinstance(data, (list, tuple)): <NEW_LINE> <INDENT> return list(map(serialize_for_api, data)) <NEW_LINE> <DEDENT> elif isinstance(data, BaseSearchResults): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return data | Transform complex types that we use into simple ones recursively.
Note: recursion isn't followed when we know that transformed types aren't
supposed to contain any more complex types.
TODO: this is rather ugly, would look better if views/models defined
transformations explicitly. This is hard to achieve with function-based
views, so it's pending a CBV move. | 625941b74e696a04525c9292 |
def GetTruth(self, node): <NEW_LINE> <INDENT> if node.nt == 'CONST': <NEW_LINE> <INDENT> return lslfuncs.cond(node.value) <NEW_LINE> <DEDENT> min = getattr(node, 'min', None) <NEW_LINE> max = getattr(node, 'max', None) <NEW_LINE> if min is None or max is None: <NEW_LINE> <INDENT> if node.nt == 'FNCALL': <NEW_LINE> <INDENT> min = self.symtab[0][node.name].get('min', min) <NEW_LINE> max = self.symtab[0][node.name].get('max', max) <NEW_LINE> <DEDENT> <DEDENT> if min is not None and min > 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if max is not None and max < 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if min == max == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return None | Decode truth value of node when possible.
Returns True if it's always true, False if it's always false, and None
if it can't be determined. | 625941b7925a0f43d2549cb1 |
def __init__(self): <NEW_LINE> <INDENT> self.serverHosts = {} | Initialize with empy server list. | 625941b72eb69b55b151c6e8 |
def devide_text_into_words(text): <NEW_LINE> <INDENT> sentences = nlp100_50.devide_text_into_sentences(text) <NEW_LINE> words_list = devide_sentences_into_words(sentences) <NEW_LINE> return words_list | Args:
text(str):
Returns:
words_list(list of list of str): | 625941b7097d151d1a222c9a |
def Free(self): <NEW_LINE> <INDENT> pass | Free(self: IPointSetIterator)
Use this method to discard any resources consumed by the iterator. Revit will
call it when done using the iterator. | 625941b7a219f33f346287b3 |
def _getTimeStamp(self, index): <NEW_LINE> <INDENT> if self._n_cset: <NEW_LINE> <INDENT> if index is None: <NEW_LINE> <INDENT> return self._timestamps[self._acsi] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._timestamps[index] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return None | Returns time stamp showing when coordinates were last changed. | 625941b7bde94217f3682c3a |
def package(name, category=None, filename=None, info=None, notes=None): <NEW_LINE> <INDENT> j = _get_jss() <NEW_LINE> ret = {'name': name, 'result': False, 'changes': {'old': {}, 'new': {}}, 'comment': ''} <NEW_LINE> try: <NEW_LINE> <INDENT> pkg = j.Package(name) <NEW_LINE> <DEDENT> except jss.GetError as e: <NEW_LINE> <INDENT> pkg = jss.Package(j, name) <NEW_LINE> <DEDENT> if category is not None and category != pkg.category.text: <NEW_LINE> <INDENT> ret['changes']['old']['category'] = pkg.category.text <NEW_LINE> pkg.category.text = category <NEW_LINE> ret['changes']['new']['category'] = category <NEW_LINE> <DEDENT> if filename is not None and filename != pkg.filename.text: <NEW_LINE> <INDENT> ret['changes']['old']['filename'] = pkg.filename.text <NEW_LINE> pkg.filename.text = filename <NEW_LINE> ret['changes']['new']['filename'] = filename <NEW_LINE> <DEDENT> if info is not None and info != pkg.info.text: <NEW_LINE> <INDENT> ret['changes']['old']['info'] = pkg.info.text <NEW_LINE> pkg.info.text = info <NEW_LINE> ret['changes']['new']['info'] = info <NEW_LINE> <DEDENT> if notes is not None and notes != pkg.notes.text: <NEW_LINE> <INDENT> ret['changes']['old']['notes'] = pkg.notes.text <NEW_LINE> pkg.notes.text = notes <NEW_LINE> ret['changes']['new']['notes'] = notes <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> pkg.save() <NEW_LINE> ret['comment'] = 'Package updated successfully.' <NEW_LINE> ret['result'] = True <NEW_LINE> return ret <NEW_LINE> <DEDENT> except jss.PostError as e: <NEW_LINE> <INDENT> ret['comment'] = 'Failed to save Package: {0}'.format(e.message) <NEW_LINE> return ret <NEW_LINE> <DEDENT> except jss.PutError as e: <NEW_LINE> <INDENT> ret['comment'] = 'Failed to update Package: {0}'.format(e.message) <NEW_LINE> return ret | Ensure that the given package object is present.
Does not upload the package. | 625941b78a43f66fc4b53ea7 |
def _BuildTokens(self): <NEW_LINE> <INDENT> supported_tokens, _ = super(CloudArmor, self)._BuildTokens() <NEW_LINE> supported_tokens -= {'destination_address', 'destination_address_exclude', 'destination_port', 'expiration', 'icmp_type', 'stateless_reply', 'option', 'protocol', 'platform', 'platform_exclude', 'source_address_exclude', 'source_port', 'verbatim'} <NEW_LINE> supported_sub_tokens = {'action': {'accept', 'deny'}} <NEW_LINE> return supported_tokens, supported_sub_tokens | Build supported tokens for platform.
Returns:
tuple containing both supported tokens and sub tokens | 625941b76e29344779a62453 |
def save(self, commit=True): <NEW_LINE> <INDENT> data = self.cleaned_data <NEW_LINE> volunteer = data['volunteer'] <NEW_LINE> if volunteer: <NEW_LINE> <INDENT> volunteer_log = VolunteerLog(volunteer=volunteer) <NEW_LINE> if commit: <NEW_LINE> <INDENT> volunteer_log.save() <NEW_LINE> <DEDENT> return volunteer_log | Take the cleaned data, create and save the new volunteer log | 625941b7a8370b77170526de |
def test_unreachable_lamp_descriptions(self): <NEW_LINE> <INDENT> self.assertEquals(str(self.unreachable_lamp), self.unreachable_lamp.description + ' ' + self.unreachable_lamp.off_description) <NEW_LINE> self.unreachable_lamp.is_lit = True <NEW_LINE> self.assertEquals(str(self.unreachable_lamp), self.unreachable_lamp.description + ' ' + self.unreachable_lamp.on_description) | unreachable_lamp returns the description + off_description when lamp.is_lit is False
and description + on_description when lamp.is_lit is True | 625941b77b25080760e39298 |
def svn_fs_check_path(*args): <NEW_LINE> <INDENT> return _fs.svn_fs_check_path(*args) | svn_fs_check_path(svn_fs_root_t * root, char const * path, apr_pool_t pool) -> svn_error_t | 625941b73617ad0b5ed67d3d |
def update_auth_report(self): <NEW_LINE> <INDENT> if results is None: <NEW_LINE> <INDENT> results = fetch_auth_report() <NEW_LINE> <DEDENT> instances = [] <NEW_LINE> for row in results: <NEW_LINE> <INDENT> instance = self.model(**row) <NEW_LINE> try: <NEW_LINE> <INDENT> old_instance = self.get(BillNumber=instance.BillNumber) <NEW_LINE> instance._log_changes(old_instance) <NEW_LINE> pk = old_instance.pk <NEW_LINE> <DEDENT> except self.model.DoesNotExist: <NEW_LINE> <INDENT> pk = None <NEW_LINE> <DEDENT> instance.pk = pk <NEW_LINE> instance.save() <NEW_LINE> instances.append(instance) <NEW_LINE> <DEDENT> return instances | Получает результаты авторизации платежей за последние 3 дня и
создает/обновляет по ним нужные записи в БД (по одной записи на
каждый BillNumber). | 625941b7283ffb24f3c5574a |
@command(trigger=("feature", "fr", "enhancement")) <NEW_LINE> def feature(*_): <NEW_LINE> <INDENT> return REPLY(content=None, attachments=[ ISSUE_NEW, ISSUE_FEATURE, ]) | Return instructions for creating a new feature request. | 625941b726238365f5f0eca7 |
def create_plot(clim, model_name, season, gridlines=False, levels=None): <NEW_LINE> <INDENT> if not levels: <NEW_LINE> <INDENT> levels = np.arange(0, 13.5, 1.5) <NEW_LINE> <DEDENT> fig = plt.figure(figsize=[12,5]) <NEW_LINE> ax = fig.add_subplot(111, projection=ccrs.PlateCarree(central_longitude=180)) <NEW_LINE> clim.sel(season=season).plot.contourf(ax=ax, levels=levels, extend='max', transform=ccrs.PlateCarree(), cbar_kwargs={'label': clim.units}, cmap=cmocean.cm.haline_r) <NEW_LINE> ax.coastlines() <NEW_LINE> if gridlines: <NEW_LINE> <INDENT> plt.gca().gridlines() <NEW_LINE> <DEDENT> title = '%s precipitation climatology (%s)' %(model_name, season) <NEW_LINE> plt.title(title) | Plot the precipitation climatology.
Args:
clim (xarray.DataArray): Precipitation climatology data
model_name (str): Name of the climate model
season (str): Season
Kwargs:
gridlines (bool): Select whether to plot gridlines
levels (list): Tick marks on the colorbar | 625941b723849d37ff7b2ed0 |
def bin2str(binary): <NEW_LINE> <INDENT> message_bytes = binascii.unhexlify('%x' % (int(binary, 2))) <NEW_LINE> return str(message_bytes, encoding="utf-8") | Turn a binary into string
:param binary:
:return: | 625941b7a17c0f6771cbde92 |
def _introduce_horario(user, dia_semana, date_inicio, date_fin): <NEW_LINE> <INDENT> diff = date_fin - date_inicio <NEW_LINE> minutos = diff.total_seconds() / 60 <NEW_LINE> intervalos = minutos // 15 <NEW_LINE> mas15 = datetime.timedelta(0, 900) <NEW_LINE> for i in range(int(intervalos)): <NEW_LINE> <INDENT> horario = Horario(dia_semana=dia_semana, hora_inicio=date_inicio.time(), profesor=user) <NEW_LINE> horarios_en_bd = list(Horario.objects.filter(profesor=user).filter(dia_semana=dia_semana). filter(hora_inicio=date_inicio.time)) <NEW_LINE> if horarios_en_bd == []: <NEW_LINE> <INDENT> horario.save() <NEW_LINE> date_inicio = date_inicio + mas15 | Metodo que guarda un horario en la base de datos
El siguiente método privado recive un usuario que es profesor, el dia de la semana, una fecha de inicio y
una fecha de fin y guarda en la base de datos objetos horarios por intervalos de 15 minutos.
:param user: Es un objeto usario concretamente profesor
:param dia_semana: Dia de la semana
:param date_inicio: Hora de inicio
:param date_fin: Hora de fin | 625941b74e4d5625662d421b |
def update(self, jobs, data=None, **options): <NEW_LINE> <INDENT> return self._post('update', query_id=jobs, data=data, **options) | Update some job attributes.
PATH: /{apiVersion}/jobs/{jobs}/update
:param str jobs: Comma separated list of job IDs or UUIDs up to a
maximum of 100. (REQUIRED)
:param str study: Study [[user@]project:]study where study and project
can be either the ID or UUID.
:param dict data: params. | 625941b7be383301e01b52cb |
def deleteNode(self, node): <NEW_LINE> <INDENT> if node.next is not None: <NEW_LINE> <INDENT> node.val=node.next.val <NEW_LINE> <DEDENT> if node.next.next is None: <NEW_LINE> <INDENT> node.next=None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.deleteNode(node.next) | :type node: ListNode
:rtype: void Do not return anything, modify node in-place instead. | 625941b750485f2cf553cbd7 |
def count_pattern(text, pattern): <NEW_LINE> <INDENT> hits = 0 <NEW_LINE> for i in range(0, len(text) - len(pattern) + 1): <NEW_LINE> <INDENT> seq = text[i: i + len(pattern)].upper() <NEW_LINE> if pattern.upper() == seq: <NEW_LINE> <INDENT> hits += 1 <NEW_LINE> <DEDENT> <DEDENT> return hits | (str, str) -> int
Count the number of times pattern occurs in text with exact matches,
count also overlapping positions
>>> count_pattern('GCGCG', 'GCG')
2 | 625941b74c3428357757c169 |
def apply(self): <NEW_LINE> <INDENT> model = self.get_model() <NEW_LINE> paths, images, targets = self.get_episode() <NEW_LINE> support_set, support_targets, query_set, query_targets = model.split_support_and_query_set(images, targets) <NEW_LINE> _, query_output = model.set_forward(support_set, support_targets, query_set) <NEW_LINE> query_output = query_output.cpu() <NEW_LINE> query_output = non_max_suppression( query_output, conf_thres=self.objectness_threshold, nms_thres=self.nms_threshold ) <NEW_LINE> self.save_detections(list(paths), query_output) | Executes YOLOMAMLDetect step and saves the result images | 625941b75fdd1c0f98dc0070 |
def prepare_data(data_dir, vocabulary_size, tokenizer=None): <NEW_LINE> <INDENT> train_path = os.path.join(data_dir, "train.txt") <NEW_LINE> dev_path = os.path.join(data_dir, "dev.txt") <NEW_LINE> vocab_path = os.path.join(data_dir, "vocab%d" % vocabulary_size) <NEW_LINE> create_vocabulary(vocab_path, train_path, vocabulary_size, os.path.join(data_dir, "embedding{0}.tsv".format(vocabulary_size)), tokenizer) <NEW_LINE> train_ids_path = train_path + (".ids%d" % vocabulary_size) <NEW_LINE> data_to_token_ids(train_path, train_ids_path, vocab_path, tokenizer) <NEW_LINE> dev_ids_path = dev_path + (".ids%d" % vocabulary_size) <NEW_LINE> data_to_token_ids(dev_path, dev_ids_path, vocab_path, tokenizer) <NEW_LINE> return train_ids_path, dev_ids_path, vocab_path | Get data into data_dir, create vocabularies and tokenize data.
Args:
data_dir: directory in which the data sets will be stored.
vocabulary_size: size of the French vocabulary to create and use.
tokenizer: a function to use to tokenize each data sentence;
if None, basic_tokenizer will be used.
Returns:
A tuple of 3 elements:
(1) path to the token-ids for training data-set,
(2) path to the token-ids for development data-set,
(3) path to the vocabulary file. | 625941b755399d3f055884f2 |
def set(): <NEW_LINE> <INDENT> global setSlot <NEW_LINE> global setChan <NEW_LINE> setSlot = [] <NEW_LINE> setChan = [] <NEW_LINE> consume("SET") <NEW_LINE> if found("["): <NEW_LINE> <INDENT> consume("[") <NEW_LINE> <DEDENT> while not found(","): <NEW_LINE> <INDENT> if found (NUMBER): <NEW_LINE> <INDENT> setSlot.append(token.cargo) <NEW_LINE> <DEDENT> consume(NUMBER) <NEW_LINE> consume(":") <NEW_LINE> if found (NUMBER): <NEW_LINE> <INDENT> setChan.append(token.cargo) <NEW_LINE> <DEDENT> consume(NUMBER) <NEW_LINE> if found(","): <NEW_LINE> <INDENT> consume(",") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if found("]"): <NEW_LINE> <INDENT> consume("]") | These are the rules for the SET keyword, encountered while parsing
waveforms. Format is
SET signallabel TO level [,slew]
see waverules() for more details. | 625941b76e29344779a62454 |
def render(self, surface): <NEW_LINE> <INDENT> GameEntity.renderText(self, surface) | Overridden function render provides unique rendering to the TextBox Entity
This funstion ensures that the TextBox entity and all subclasses render
correctly by passing itself to the renderText function of the GameEntity
Class, and not to the render function which is meant specifically for images | 625941b760cbc95b062c6388 |
def naca(epaisseur, N=101): <NEW_LINE> <INDENT> a = Geom.naca(epaisseur, N) <NEW_LINE> return C.convertArrays2ZoneNode('naca', [a]) | Create a naca profile of N points.
Usage: naca(epaisseur, N) | 625941b7f8510a7c17cf9543 |
def isIDHotkey(self, hotkey): <NEW_LINE> <INDENT> for key in hotkey: <NEW_LINE> <INDENT> if type(key) == str: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True | Test if hotkey is coded in IDs | 625941b72ae34c7f2600cf70 |
def toggle_state(self): <NEW_LINE> <INDENT> if self.expandable_flag: <NEW_LINE> <INDENT> if self.expanded_flag: <NEW_LINE> <INDENT> self.PVT_set_state(0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.PVT_set_state(1) | Toggle node's state between expanded and collapsed, if possible | 625941b7ff9c53063f47c03c |
def find3(List): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for i in range(len(List) - 1): <NEW_LINE> <INDENT> if (List[i] == 'P' and List[i+1] == 'P') or (List[i] == 'C' and List[i+1] == 'C'): <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> count = 0 <NEW_LINE> <DEDENT> if count >= 2: <NEW_LINE> <INDENT> if List[i] == 'C': <NEW_LINE> <INDENT> if i+2 < len(List) and List[i+2] == 0: <NEW_LINE> <INDENT> return i + 2 <NEW_LINE> <DEDENT> elif i - 2 >= 0 and List[i-2] == 0: <NEW_LINE> <INDENT> return i - 2 <NEW_LINE> <DEDENT> <DEDENT> elif List[i] == 'P': <NEW_LINE> <INDENT> if i+2 < len(List) and List[i+2] == 0: <NEW_LINE> <INDENT> return i + 2 <NEW_LINE> <DEDENT> elif i - 2 >= 0 and List[i-2] == 0: <NEW_LINE> <INDENT> return i - 2 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return "nothing" | Checks for 3-in-a-rows in a given list by using a loop that increases a count for
every subsequent tile played by the same player. If count reaches 2, it means there
is a 3-in-a-row in the list. If a 3-in-a-row is found, the function identifies whether
it belongs to the player or computer and returns the proper column number in which the
computer should play its next tile. | 625941b7d164cc6175782b8c |
def test_addition_w_date(self): <NEW_LINE> <INDENT> date = Date("H", "2001-01-01 00:00") <NEW_LINE> test = date + TimeDelta("D", 5) <NEW_LINE> assert_equal(test, Date("H", "2001-01-06 00:00")) <NEW_LINE> test = date + TimeDelta("M", 5) <NEW_LINE> assert_equal(test, Date("H", "2001-06-01 00:00")) <NEW_LINE> test = date + TimeDelta("A", 5) <NEW_LINE> assert_equal(test, Date("H", "2006-01-01 00:00")) <NEW_LINE> delta = TimeDelta("H", months=15, hours=24, minutes=60, seconds=3600) <NEW_LINE> test = date + delta <NEW_LINE> assert_equal(test, Date("H", "2002-04-02 02:00")) <NEW_LINE> date = Date("D", "2001-01-01") <NEW_LINE> for unit in ("H", "T", "S"): <NEW_LINE> <INDENT> test = date + TimeDelta(unit, 5) <NEW_LINE> assert_equal(test, date) <NEW_LINE> <DEDENT> test = date + TimeDelta('H', 24) <NEW_LINE> assert_equal(test, Date('D', '2001-01-02')) | Test adding a Date and a TimeDelta | 625941b73cc13d1c6d3c71c3 |
def merkle_root(hash_list): <NEW_LINE> <INDENT> if len(hash_list) == 1: <NEW_LINE> <INDENT> return hash_list[0] <NEW_LINE> <DEDENT> current_level = hash_list <NEW_LINE> while len(current_level) > 1: <NEW_LINE> <INDENT> current_level = merkle_parent_level(current_level) <NEW_LINE> <DEDENT> return current_level[0] | Takes a list of binary hashes and returns the merkle root
| 625941b79b70327d1c4e0c12 |
def reset(self): <NEW_LINE> <INDENT> self.cards = [] <NEW_LINE> self.standing = False | Return cards and stop standing. | 625941b71f037a2d8b94603e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.