code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def update_train_state(args,model,train_state): <NEW_LINE> <INDENT> if train_state['epoch_index'] == 0: <NEW_LINE> <INDENT> torch.save(model.state_dict(),train_state['model_filename']) <NEW_LINE> train_state['stop_early'] = False <NEW_LINE> <DEDENT> elif train_state['epoch_index'] >= 1: <NEW_LINE> <INDENT> loss_tm1,los... | Handle the training state updates.
Components:
- Early Stopping: Prevent overfitting.
- Model Checkpoint: Model is saved if the model is better
:param args: main arguments
:param model: model to train
:param train_state: a dictionary representing the training state values
:returns:
a new train_state | 625941efc432627299f051b2 |
def _writeText(self, image, text, pos): <NEW_LINE> <INDENT> offset = 0 <NEW_LINE> x, y = pos <NEW_LINE> offsets = [] <NEW_LINE> widths = [] <NEW_LINE> heights = [] <NEW_LINE> for c in text: <NEW_LINE> <INDENT> c_size = self.font.getsize(c) <NEW_LINE> c_image = Image.new('RGBA', c_size, (0, 0, 0, 0)) <NEW_LINE> c_draw =... | Write morphed text in Image object. | 625941ef6fb2d068a760f60f |
def spline_base(height, width, Nr_Knots_x = 5.0, Nr_Knots_y = 5.0, spline_order = 3,scale_factor=None): <NEW_LINE> <INDENT> Knots_x = augknt(np.linspace(0,width,Nr_Knots_x),spline_order) <NEW_LINE> Knots_y = augknt(np.linspace(0,height,Nr_Knots_y),spline_order) <NEW_LINE> if not scale_factor: <NEW_LINE>... | Computes a set of 2D spline basis functions.
The basis functions cover the entire space in height*width and can
for example be used to create fixation density maps.
Input:
height: int
height of each basis
width: int
widht of each basis
Nr_Knots_x: int
# of knots in x direction.... | 625941efc432627299f051b3 |
def is_equal(self, g): <NEW_LINE> <INDENT> if len(self._vertices) != len(g._vertices): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for name,vertex in self._vertices.iteritems(): <NEW_LINE> <INDENT> if name not in g._vertices: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if vertex.color != g._vertices[n... | Check whether the graph is equal to the graph 'g'.
Returns True if this is the case and False otherwise. | 625941ef7d847024c06be829 |
def parse_balances(self, img, filter_seat=None): <NEW_LINE> <INDENT> coords = self.coords['balances'] <NEW_LINE> logger.info('parsing balances with {}'.format(coords)) <NEW_LINE> template = self.img['dollar_balance'] <NEW_LINE> threshold = coords['th_tpl'] <NEW_LINE> locs = self.match_template(img, template, threshold,... | Parses balances. Requires OCR.
- template match dollar
- crop out where matched after dollar
Can additionally only OCR for a specific seat | 625941ef76e4537e8c351be0 |
def ipa_syllable_to_pinyin(s, accented=True): <NEW_LINE> <INDENT> if accented: <NEW_LINE> <INDENT> return _ipa_syllable_to_accented(s) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return _ipa_syllable_to_numbered(s) | Convert IPA syllable *s* to a Pinyin syllable.
If *accented* is ``True``, diacritics are added to the Pinyin syllable. If
it's ``False``, numbers are used to indicate the syllable's tone. | 625941ef596a89723608a021 |
def setNextPin(self, source): <NEW_LINE> <INDENT> if self.pinA is None: <NEW_LINE> <INDENT> self.pinA = source <NEW_LINE> <DEDENT> elif self.pinB is None: <NEW_LINE> <INDENT> self.pinB = source <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeError('Error: NO EMPTY PINS') | set next available pin | 625941ef01c39578d7e753a4 |
@app.route('/welcome') <NEW_LINE> def welcome(): <NEW_LINE> <INDENT> return render_template("welcome.html") | Login page shows login form | 625941efe8904600ed9f249f |
def matrixReshape(self, nums, r, c): <NEW_LINE> <INDENT> import numpy as np <NEW_LINE> try: <NEW_LINE> <INDENT> return np.reshape(nums, (r, c)).tolist() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return nums | :type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]] | 625941efa4f1c619b28b0594 |
def regex_the_drive(translation): <NEW_LINE> <INDENT> drive_string = translation[1233] <NEW_LINE> used_drive = remove_colon(drive_string) <NEW_LINE> used_drive = re.sub('drive', '[Dd]rive', used_drive) <NEW_LINE> return used_drive | Regex out `Used drive` string from the translation json. | 625941efd4950a0f3b08c8af |
def bootstrap_sp(args): <NEW_LINE> <INDENT> from configobj import ConfigObj <NEW_LINE> from cassandra import __version__ <NEW_LINE> from cassandra.compfactory import create_component <NEW_LINE> if args['logdir'] is None: <NEW_LINE> <INDENT> logging.basicConfig(stream=sys.stdout, level=args['loglvl']) <NEW_LINE> logging... | Bootstrap the multithreaded (single processing) version of the calculation.
:param args: Dictionary of command line arguments parsed by argparse.
:return: (component-list, capability-table) | 625941ef5f7d997b87175005 |
def __init__(self, raw_events=[], start_hour=8, end_hour=22): <NEW_LINE> <INDENT> self.events = [] <NEW_LINE> for event in raw_events: <NEW_LINE> <INDENT> wrapper = EventRenderer(event.name, event.start, event.end, reverse("events_event_view", args=[event.id])) <NEW_LINE> self.events.append(wrapper) <NEW_LINE> <DEDENT>... | Initialize with raw_events as a list or QuerySet of Events | 625941ef925a0f43d254a3e5 |
def cmap_discretize(self, cmap, N): <NEW_LINE> <INDENT> if type(cmap) == str: <NEW_LINE> <INDENT> cmap = plt.get_cmap(cmap) <NEW_LINE> <DEDENT> colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.))) <NEW_LINE> colors_rgba = cmap(colors_i) <NEW_LINE> indices = np.linspace(0, 1., N+1) <NEW_LINE> cdict = {} <NE... | Return a discrete colormap from the continuous colormap cmap.
From http://scipy.github.io/old-wiki/pages/Cookbook/Matplotlib/ColormapTransformations
Args:
cmap: colormap instance, eg. cm.jet.
N: number of colors.
Returns:
discrete colourmap
Author: FJC | 625941efc4546d3d9de72fa2 |
def __init__(self, total, page_size, total_page, page_num, rows): <NEW_LINE> <INDENT> self.total = total <NEW_LINE> self.pageSize = page_size <NEW_LINE> self.totalPage = total_page <NEW_LINE> self.pageNum = page_num <NEW_LINE> self.rows = rows <NEW_LINE> self.prevPage = page_num - 1 if page_num > 1 else 1 <NEW_LINE> se... | :param total: 总记录数
:param page_size: 页大小
:param total_page: 总页数
:param page_num: 当前页
:param rows: 数据
:param prevPage: 上一页页码
:param nextPage: 下一页页码 | 625941ef566aa707497f4ac9 |
def test_firefox_windows_profiles(capsys, become_windows, change_homedir): <NEW_LINE> <INDENT> out = None <NEW_LINE> try: <NEW_LINE> <INDENT> cli(["--show-profiles", "firefox"]) <NEW_LINE> <DEDENT> except SystemExit: <NEW_LINE> <INDENT> captured = capsys.readouterr() <NEW_LINE> out = captured.out <NEW_LINE> <DEDENT> pr... | Test --show-profiles option for Firefox on Windows | 625941ef4428ac0f6e5bad60 |
def ready(self): <NEW_LINE> <INDENT> import user.signals | 应用的初始化 | 625941ef167d2b6e312190fd |
@csrf_exempt <NEW_LINE> @require_POST <NEW_LINE> def login(request): <NEW_LINE> <INDENT> username = request.POST.get('username', '') <NEW_LINE> password = request.POST.get('password', '') <NEW_LINE> try: <NEW_LINE> <INDENT> User.objects.get(username=username) <NEW_LINE> <DEDENT> except User.DoesNotExist: <NEW_LINE> <IN... | View login | 625941ef287bf620b61d3fc9 |
def get_bi(self, items_list): <NEW_LINE> <INDENT> bi = (sum([rating - self.user_baselines[user] - self.mu for user, rating in items_list.items()])/(len(items_list)+self.reg)) <NEW_LINE> return bi | simple method to calculate the baseline estimator of an item
based of the equations described in the report | 625941efff9c53063f47c759 |
def __init__(self): <NEW_LINE> <INDENT> self.inipath=dirs.CONF_DIR <NEW_LINE> self.cf=ConfigObj(self.inipath,encoding='utf-8') | 导入conf.ini文件 | 625941efd486a94d0b98e6af |
def fit(self, x_data, t_data): <NEW_LINE> <INDENT> assert isinstance(x_data, pandas.DataFrame) <NEW_LINE> assert isinstance(t_data, pandas.Series) <NEW_LINE> model_args = {'linear_optimizer': self.linear_optimizer, 'dnn_hidden_units': self.dnn_hidden_units, 'dnn_optimizer': self.dnn_optimizer, 'dnn_activation_fn': self... | run training
Parameters
----------
x_data : pandas.DataFrame
input data
t_data : pandas.Series
true output
Returns
-------
DNNLinearCombinedEstimator | 625941ef38b623060ff0b356 |
def get_duration_hour(self): <NEW_LINE> <INDENT> return self.duration_hour | Get duration hour.
Returns:
str: Duration hour. | 625941ef29b78933be1e5c0e |
def func_filter_outlier_iqr(df, df_IQR): <NEW_LINE> <INDENT> for index, row in df_IQR.iterrows(): <NEW_LINE> <INDENT> df.loc[(df[index] < row['Lower_Bound']) | (df[index] > row['Upper_Bound']), index] = np.nan <NEW_LINE> <DEDENT> return df | function to filter outlier based on IQR
:param df: dataframe
:param df_IQR: dataframe of IQR ranges
:return: filtered dataframe with outliers replaced with NaN | 625941ef30dc7b7665901ec9 |
def Run(profileFile): <NEW_LINE> <INDENT> profile = Profile() <NEW_LINE> profile.LoadFromFile(profileFile) <NEW_LINE> surfaceFile = profile.StlFile <NEW_LINE> surfaceFileScale = profile.StlFileUnit.SizeInMetres <NEW_LINE> ipFinder = GeometryInletPointFinder(profile.OutputGeometryFile) <NEW_LINE> inletPointIndices = ipF... | Process all the Inlets specified by profileFile, solving the Navier-
Stokes equations for steady flow down an infinite channel with the cross
section of the inlet. Writes the point ID and the fluid velocity at that
point, the velocity being such that the integral of the flow across the
channel is unity.
Currently out... | 625941ef3cc13d1c6d3c78e0 |
def t_TEXT(t): <NEW_LINE> <INDENT> t.type = reserved.get(t.value,"TEXT") <NEW_LINE> return t | \'.+?\' | 625941efb7558d58953c5471 |
def get_finance_index_XQ(code): <NEW_LINE> <INDENT> if code[0] in ['6','9']: <NEW_LINE> <INDENT> code='SH'+code <NEW_LINE> <DEDENT> if code[0] in ['0','2','3']: <NEW_LINE> <INDENT> code='SZ'+code <NEW_LINE> <DEDENT> url='https://xueqiu.com/stock/f10/finmainindex.json?symbol={0}&page=1&size=400'.format(code) <NEW_LINE> ... | 获取股票的历史交易数据 | 625941efd164cc61757832b8 |
@register.assignment_tag <NEW_LINE> def get_form_helper(type='horizontal'): <NEW_LINE> <INDENT> if type == 'horizontal': <NEW_LINE> <INDENT> return Bootstrap3HorizontalFormHelper() <NEW_LINE> <DEDENT> elif type == 'inline': <NEW_LINE> <INDENT> return Bootstrap3InlineFormHelper() <NEW_LINE> <DEDENT> elif type == 'bare':... | <type>に応じたFormHelperを返します。
もし、該当する<type>が見つからない場合は、TemplateSyntaxErrorを投げます。
Syntax:
{% get_form_helper as <variable> %}
{% get_form_helper <type> as <variable> %}
Type: (Default: horizontal)
horizontal: Bootstrap3のHorizontal Formを描画するHelper
inline: Bootstrap3Inline Formを描画するHelper
bare: horizonta... | 625941efd58c6744b42581c6 |
def source_photons(bandpass, wavelength, magnitude, diameter, extinction): <NEW_LINE> <INDENT> return np.floor(4.5e10 / wavelength * 10**(-(magnitude + extinction) / 2.5) * diameter**2 * bandpass) | Number of photons collected per second by a telescope given diameter from source of given magnitude
Adopted from Massey et al. 1988
Specify bandpass and mean wavelength of observation
Does not assume transmission or detector efficiency | 625941efb545ff76a891437f |
def __init__(self, email, credentials=None, auth_type=None, retry_policy=None): <NEW_LINE> <INDENT> self.email = email <NEW_LINE> self.credentials = credentials <NEW_LINE> self.auth_type = auth_type <NEW_LINE> self.retry_policy = retry_policy <NEW_LINE> self._urls_visited = [] <NEW_LINE> self._redirect_count = 0 <NEW_L... | :param email: The email address to autodiscover
:param credentials: Credentials with authorization to make autodiscover lookups for this Account | 625941ef3346ee7daa2b32da |
def intersect(s1, s2): <NEW_LINE> <INDENT> assert (s1.step is None and s2.step is None) or s1.step == s2.step, "Only implemented for same-step slices" <NEW_LINE> if s1.start is None: <NEW_LINE> <INDENT> start = s2.start <NEW_LINE> <DEDENT> elif s2.start is None: <NEW_LINE> <INDENT> start = s1.start <NEW_LINE> <D... | Returns the intersection of two slices (which must have the same step).
Parameters
----------
s1, s2 : slice
The slices to intersect.
Returns
-------
slice | 625941ef0a366e3fb873ed89 |
def range(self, lower, upper): <NEW_LINE> <INDENT> self.bounds = Interval(lower, upper) | Sets the lower and upper limits on the Parameter
Parameters
----------
lower : float
lower bound
upper : float
upper bound
Returns
-------
None | 625941eff548e778e58cdae9 |
def list2cmdline(seq): <NEW_LINE> <INDENT> result = [] <NEW_LINE> needquote = False <NEW_LINE> for arg in seq: <NEW_LINE> <INDENT> bs_buf = [] <NEW_LINE> if result: <NEW_LINE> <INDENT> result.append(' ') <NEW_LINE> <DEDENT> needquote = (" " in arg) or ("\t" in arg) or ("|" in arg) or not arg <NEW_LINE> if needquote: <N... | Translate a sequence of arguments into a command line
string, using the same rules as the MS C runtime:
1) Arguments are delimited by white space, which is either a
space or a tab.
2) A string surrounded by double quotation marks is
interpreted as a single argument, regardless of white space
or pipe characte... | 625941ef55399d3f05588c21 |
def modifyStringWithSome1337(string, ch=1): <NEW_LINE> <INDENT> modifiedString = '' <NEW_LINE> for char in string: <NEW_LINE> <INDENT> change = random.randint(0, int(ch)) <NEW_LINE> if char == ' ': <NEW_LINE> <INDENT> char = '/' <NEW_LINE> <DEDENT> elif change == 1: <NEW_LINE> <INDENT> if char.lower() == 'a': <NEW_LINE... | takes a string and returns a modified (more 1337) string
the higher ch is, the less likely it is that a character will be changed
0 = no change
1 = 50/50 chance of a character being changed
20 = character very unlikely to be changed
A whitespace in the string will always be replaced with a forward slash
in the return... | 625941ef167d2b6e312190fe |
def build_successors_table(tokens): <NEW_LINE> <INDENT> table = {} <NEW_LINE> prev = '.' <NEW_LINE> for word in tokens: <NEW_LINE> <INDENT> if prev not in table: <NEW_LINE> <INDENT> table[prev] = [] <NEW_LINE> <DEDENT> "*** YOUR CODE HERE ***" <NEW_LINE> table[prev] += [word] <NEW_LINE> prev = word <NEW_LINE> <DEDENT> ... | Return a dictionary: keys are words; values are lists of
successors.
>>> text = ['We', 'came', 'to', 'investigate', ',', 'catch', 'bad', 'guys', 'and', 'to', 'eat', 'pie', '.']
>>> table = build_successors_table(text)
>>> sorted(table)
[',', '.', 'We', 'and', 'bad', 'came', 'catch', 'eat', 'guys', 'investigate', 'pie'... | 625941ef07f4c71912b119ee |
def patient_research_study_status(patient, ignore_QB_status=False): <NEW_LINE> <INDENT> from datetime import datetime <NEW_LINE> from .research_study import EMPRO_RS_ID, ResearchStudy <NEW_LINE> as_of_date = datetime.utcnow() <NEW_LINE> results = {} <NEW_LINE> for rs in ResearchStudy.assigned_to(patient): <NEW_LINE> <I... | Returns details regarding patient readiness for available studies
Wraps complexity of checking multiple QB_Status and ResearchStudy
availability. Includes several business rule checks as well
as enforcing user has completed outstanding work from other studies
if applicable. NB - a user may be "ready" for a study, bu... | 625941ef796e427e537b0b34 |
def assignCA(self, CA): <NEW_LINE> <INDENT> warn('This method will be deprecated.', PendingDeprecationWarning) <NEW_LINE> self.CA = CA <NEW_LINE> for function in CA.registered_functions: <NEW_LINE> <INDENT> self.add_function(function_code=function, function_body=CA.registered_functions[function]) | Assigning alarm system | 625941ef099cdd3c635f11c1 |
def doClose(obj, event): <NEW_LINE> <INDENT> if not event.transition or event.transition.id not in ['adviceClose'] or obj != event.object: <NEW_LINE> <INDENT> return | generated workflow subscriber. | 625941ef4c3428357757c88d |
def setUp(self): <NEW_LINE> <INDENT> tuple0 = [{'A', 'B'}, {0,1,2,3,4,5,6}, {1,3,5,7}] <NEW_LINE> tuple1 = [{'A', 'B'}, {0,1,2,3,4}, {5,6,7,8}] <NEW_LINE> if self.id().split('.')[-1] == 'test_firstList': <NEW_LINE> <INDENT> self.testParams = [ {'tupleOfLists': tuple0, 'listNumber': {1}, 'lowerBound': 0, 'upperBound': 7... | Set up the parameters for the individual tests. | 625941efec188e330fd5acfd |
def get_track(self, distance): <NEW_LINE> <INDENT> distance += 20 <NEW_LINE> forward_tracks = [] <NEW_LINE> current = 0 <NEW_LINE> mid = distance * 3 / 5 <NEW_LINE> t = 0.2 <NEW_LINE> v = 0 <NEW_LINE> while current < distance: <NEW_LINE> <INDENT> if current < mid: <NEW_LINE> <INDENT> a = 2 <NEW_LINE> <DEDENT> else: <NE... | 根据偏移量获取移动轨迹
:param distance: 偏移量
:return: 移动轨迹 | 625941effff4ab517eb2f9a9 |
def start_workers(count): <NEW_LINE> <INDENT> from kivy.clock import Clock <NEW_LINE> global workers <NEW_LINE> for i in range(count): <NEW_LINE> <INDENT> w_interface = WorkerInterface() <NEW_LINE> w_interface.start_process() <NEW_LINE> workers[w_interface.id] = w_interface <NEW_LINE> <DEDENT> Clock.schedule_interval(_... | Creates WorkerInterface instances and starts Worker processes,
then schedules _update with Clock interval | 625941ef8a349b6b435e86dc |
def list( self, resource_group_name, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> def internal_paging(next_link=None, raw=False): <NEW_LINE> <INDENT> if not next_link: <NEW_LINE> <INDENT> url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/vi... | Gets a list of all VM scale sets under a resource group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_co... | 625941ef56ac1b37e626472e |
def inherit(self, other_manager): <NEW_LINE> <INDENT> for attr,value in other_manager.__dict__.items(): <NEW_LINE> <INDENT> if attr != 'loggerDict': <NEW_LINE> <INDENT> setattr(self, attr, value) <NEW_LINE> <DEDENT> <DEDENT> for name,logger in other_manager.loggerDict.items(): <NEW_LINE> <INDENT> self.loggerDict[name] ... | Inherit attributes and logger instances from an other/existing
manager. | 625941efd486a94d0b98e6b0 |
def get_block(self, block_num): <NEW_LINE> <INDENT> return self.call('get_block', block_num, api='database_api') | Get the full block, transactions and all, given a block number.
Args:
block_num (int) number.
Returns:
dict in a JSON compatible format. | 625941efcc40096d61595eb7 |
def symbol_name(self): <NEW_LINE> <INDENT> return _ccsds_swig.mpsk_preamble_cc_sptr_symbol_name(self) | symbol_name(mpsk_preamble_cc_sptr self) -> std::string | 625941ef99fddb7c1c9de8f7 |
def method_1(Y_train, Y_test, reg=0.1, k=20, eta=0.03, eps=0.0001): <NEW_LINE> <INDENT> M = max(max(Y_train[:,0]), max(Y_test[:,0])).astype(int) <NEW_LINE> N = max(max(Y_train[:,1]), max(Y_test[:,1])).astype(int) <NEW_LINE> U,V, ret = train_model(M, N, k, eta, reg, Y_train, eps=eps) <NEW_LINE> RMSE = get_RMSE(U, V, Y_t... | Runs method 1 over the given training parameters and returns a matrix of
root-mean-squared error (RMSE). | 625941ef293b9510aa2c37fa |
def current_dataset_name(self): <NEW_LINE> <INDENT> return self._current_dataset | Return the current dataset name. | 625941efd58c6744b42581c7 |
def calc_floor(current_index, current_page, sum_page, total_num=0): <NEW_LINE> <INDENT> rank = sum_page.get(current_page - 1, 0) <NEW_LINE> rank += current_index + 1 <NEW_LINE> if total_num > 0: <NEW_LINE> <INDENT> return total_num - rank + 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return rank | 计算当前页第 k 条消息在所有消息中的位置,若 total_num 为 0,则第一条位置为 1,否则最后一条位置为1
Args:
current_index: 消息在当前页的位置
current_page: 当前页
sum_page: 前 k 个页包含的消息条数
total_num: 所有消息的数量 | 625941ef97e22403b379d505 |
def train_and_plot(data: pd.DataFrame, test_size: float = 0.3): <NEW_LINE> <INDENT> X = data.negative - data.positive <NEW_LINE> pca = PCA(n_components=2) <NEW_LINE> X2 = pca.fit_transform(X) <NEW_LINE> clf = train_model(X, test_size) <NEW_LINE> X0, X1 = X2[:, 0], X2[:, 1] <NEW_LINE> xx, yy = make_meshgrid(X0, X1) <NEW... | use SVM to classify them and then plot them after projecting X, y into 2D using PCA
| 625941efaad79263cf390fb3 |
def leftPadding(self): <NEW_LINE> <INDENT> return 0.0 | QTextTableCellFormat.leftPadding() -> float | 625941ef71ff763f4b549bff |
def tearDown(self): <NEW_LINE> <INDENT> self.assertFalse(self.lock.is_locked) <NEW_LINE> return None | Asserts that the lock file *self.lock* is not locked. | 625941efd7e4931a7ee9e489 |
def test_manager_active(self): <NEW_LINE> <INDENT> Entry.objects.create(pub_date=self.now, is_active=False, headline='inactive', slug='a') <NEW_LINE> Entry.objects.create(pub_date=self.now, is_active=True, headline='active', slug='b') <NEW_LINE> self.assertQuerysetEqual(Entry.objects.published(), ['active'], transform=... | Make sure that the Entry manager's `active` method works | 625941ef2c8b7c6e89b35d26 |
def minimumSizeHint(self): <NEW_LINE> <INDENT> return QtCore.QSize(700, 400) | set an (arbitrary) minimum size for the widget | 625941ef8c0ade5d55d3ef29 |
def add_rules(self, firewall_id, inbound_rules=None, outbound_rules=None): <NEW_LINE> <INDENT> args = [] <NEW_LINE> if inbound_rules: <NEW_LINE> <INDENT> args.extend(["--inbound-rules", inbound_rules]) <NEW_LINE> <DEDENT> if outbound_rules: <NEW_LINE> <INDENT> args.extend(["--outbound-rules", outbound_rules]) <NEW_LINE... | Add inbound/outbound rules to the firewall. | 625941ef377c676e91272710 |
def _create_animal_of_species_statement(from_name, to_name): <NEW_LINE> <INDENT> return create_edge_statement("Animal_OfSpecies", "Animal", from_name, "Species", to_name) | Return a SQL statement to create an Animal_OfSpecies edge. | 625941efdc8b845886cb5aa0 |
@main_blueprint.route('/catalog/<string:category>/edit', methods=['GET', 'POST']) <NEW_LINE> @login_required <NEW_LINE> @check_authentication <NEW_LINE> def category_edit(category): <NEW_LINE> <INDENT> user = pg_session.query(User).filter_by(google_id=session['id']).one() <NEW_LINE> cat_edit = pg_session.query(Category... | Edit the given category
* user - Retrieve the user details from the db with session['id']
* cat_edit - Retrieve the category to be edited from the db.
.. http:get:: /catalog/(string:category)/edit
:param category: The selected category
:type category: str
:return: Render the category_edit template
.. ht... | 625941ef92d797404e3046f6 |
def get_key_words_nlp(self) : <NEW_LINE> <INDENT> self.title = list(self.title) <NEW_LINE> new = [] <NEW_LINE> for cara in self.title : <NEW_LINE> <INDENT> if cara not in ["-",":","!","?","'","|"] : <NEW_LINE> <INDENT> new.append(cara) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> new.append(" ") <NEW_LINE> <DEDENT> <... | DESCRIPTION
this function is used to get the key words using the nlp thank to an analyse of the title it is only
for the second part
WE NEED JUST THE TITLE !
OUTPUT :
out1 : list of str
this is the list of the main entities of the sentence find by spacy
| 625941ef91af0d3eaac9bf88 |
def get_provider_links_metadata(self): <NEW_LINE> <INDENT> return | Gets the metadata for the provider chain.
:return: metadata for the provider chain
:rtype: ``osid.Metadata``
*compliance: mandatory -- This method must be implemented.* | 625941efff9c53063f47c75a |
def to_hex(string): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if len(string) > 0 and isinstance(string, str): <NEW_LINE> <INDENT> return ':'.join(x.encode('hex') for x in string) <NEW_LINE> <DEDENT> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> vlog(1, 'Unable to convert string to hex') <NEW_LINE> <DEDENT> r... | Dumps string as hex | 625941ef2ae34c7f2600d69a |
def test_register_empty_email(self): <NEW_LINE> <INDENT> empty_email = { 'email': '', 'password': 'password' } <NEW_LINE> res = self.client().post('/api/v1/auth/register', data=empty_email) <NEW_LINE> self.assertEqual(res.status_code, 400) <NEW_LINE> result = json.loads(res.data.decode()) <NEW_LINE> self.assertEqual( r... | Test if a correct message is returned when an empty email is supplied for registration
:return: | 625941ef0383005118ecfb4a |
def poetry(request, pk, slug): <NEW_LINE> <INDENT> return readers.item(request, 'poetry', pk, slug, src='public_url') | Returns the poetry from the repository | 625941ef656771135c3ebddf |
def unregister(self, receiver_id): <NEW_LINE> <INDENT> del self.receivers[receiver_id] | Unregister a receiver by its id. | 625941ef1d351010ab856084 |
def get_important_features(clf, columns): <NEW_LINE> <INDENT> feature_importances = clf.feature_importances_ <NEW_LINE> f_i = sorted(zip(map(lambda x: round(x, 4), feature_importances), columns), reverse=True) <NEW_LINE> print("Most important features are: ", f_i) <NEW_LINE> return f_i | :param clf: Sklearn Classifier optimized with GridSearch
:param columns: list of columns
:return: | 625941ef10dbd63aa1bd310c |
def r(w, Xs): <NEW_LINE> <INDENT> n = len(Xs) <NEW_LINE> P = projection_matrix(w) <NEW_LINE> c = C(w, Xs) <NEW_LINE> return np.sqrt(sum(np.dot(c - X, np.dot(P, c - X)) for X in Xs) / n) | Calculate the radius given the cylinder direction and a list
of data points. | 625941ef85dfad0860c3b3c6 |
def set_kick_period(self, period): <NEW_LINE> <INDENT> self.KICK_PERIOD = period + self.STARTUP_DELAY | Adjust the KICK_PERIOD between __init__() and start() | 625941efcc0a2c11143dd3fb |
def transmission_cb(word, word_eol, userdata): <NEW_LINE> <INDENT> if path.exists(_TRANSMISSIONSTATS): <NEW_LINE> <INDENT> lines = open(_TRANSMISSIONSTATS, "r").readlines() <NEW_LINE> downloaded = helper.units(int(lines[1].split(":")[1][1:-3]), 1024) <NEW_LINE> uploaded = helper.units(int(lines[5].split(":")[1][1:-1]),... | Reads transmission's stats file and show total Upload and Download in
the active channel
Arguments:
word -- array of strings sent by HexChat/X-Chat to every hook (ignored)
word_eol -- array of strings sent by HexChat/X-Chat to every hook (ignored)
userdata -- optional variable that can be sent to a hook (ignored) | 625941ef85dfad0860c3b3c7 |
def WatchUnWarns(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') | Subscribe to unwarn events.
| 625941efa17c0f6771cbe5b9 |
def spec_for_words(self, string): <NEW_LINE> <INDENT> return " ".join(map(self.spec_for_word, string.split())) | Return a dragonfly spec string for any string that can be obtained from string by making substitutions for individual words in string. | 625941ef63d6d428bbe44a5b |
def parseBlock(self, text, prevLineData): <NEW_LINE> <INDENT> return self.parser.parseBlock(text, prevLineData) | Parse line of text and return
lineData
where
lineData is data, which shall be saved and used for parsing next line
This is quicker version of highlighBlock, which doesn't return results,
but only parsers the block and produces data, which is necessary for parsing next line.
Use it for invisible lines | 625941ef097d151d1a2233c0 |
def _cleanup_source_host(self, source_instance): <NEW_LINE> <INDENT> ctxt = source_instance._context <NEW_LINE> objects.InstanceAction.action_start( ctxt, source_instance.uuid, instance_actions.CONFIRM_RESIZE, want_result=False) <NEW_LINE> source_migration = objects.Migration.get_by_uuid( ctxt, self.migration.uuid) <NE... | Cleans up the instance from the source host.
Creates a confirmResize instance action in the source cell DB.
Destroys the guest from the source hypervisor, cleans up networking
and storage and frees up resource usage on the source host.
:param source_instance: Instance object from the source cell DB | 625941ef442bda511e8be97a |
def test_post_function_with_header_patch(client): <NEW_LINE> <INDENT> rv = client.post('/', headers={'X_HTTP_METHOD_OVERRIDE': 'PATCH'}) <NEW_LINE> assert b'PATCH Return' in rv.data | Start with a blank database. | 625941efa219f33f34628ecc |
def show_cart(request, template_name): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> postdata = request.POST.copy() <NEW_LINE> if postdata['submit'] == 'Remove': <NEW_LINE> <INDENT> cart.remove_from_cart(request) <NEW_LINE> <DEDENT> if postdata['submit'] == 'Update': <NEW_LINE> <INDENT> cart.upda... | view function for the page displaying the customer shopping cart,
and allows for the updating of quantities and removal of product instances | 625941efcc0a2c11143dd3fc |
def rotation(r): <NEW_LINE> <INDENT> global _rotation <NEW_LINE> _rotation = int(round(r/90.0)) | Set the display rotation in degrees.
Actual rotation will be snapped to the nearest 90 degrees. | 625941ef26068e7796caf251 |
def test_wrap_file(path_rgb_byte_tif): <NEW_LINE> <INDENT> with rasterio.open(path_rgb_byte_tif) as src: <NEW_LINE> <INDENT> vrt = WarpedVRT(src, crs=DST_CRS) <NEW_LINE> assert vrt.crs == CRS.from_string(DST_CRS) <NEW_LINE> assert tuple(round(x, 1) for x in vrt.bounds) == ( -8789636.7, 2700460.0, -8524406.4, 2943560.2 ... | A VirtualVRT has the expected dataset properties. | 625941ef6fece00bbac2dcaf |
def on(self, device, color, brightness): <NEW_LINE> <INDENT> d = self.get_data_user() <NEW_LINE> user = d["guid"] = self.get_user_guid() <NEW_LINE> d["device"] = device <NEW_LINE> d["color"] = color <NEW_LINE> d["brightness"] = brightness <NEW_LINE> url = self.url("/api/device/turnOn") <NEW_LINE> self.pu... | Device is "id" such as 6 not any guid | 625941ef99cbb53fe679314f |
def slotBack(self): <NEW_LINE> <INDENT> self.menuText = "" <NEW_LINE> curIndex = self.ui.mainStack.currentIndex() <NEW_LINE> self.pie.updatePie(curIndex-1) <NEW_LINE> self.menu.prev() <NEW_LINE> _w = self.ui.mainStack.currentWidget() <NEW_LINE> _w.backCheck() <NEW_LINE> self.stackMove(self.getCur(self.moveInc * -1)) <N... | execute previous step | 625941ef60cbc95b062c6aae |
def update_gl_options(self, default=-1, **kwargs): <NEW_LINE> <INDENT> if default is not -1: <NEW_LINE> <INDENT> self._gl_options[0] = default <NEW_LINE> <DEDENT> self._gl_options.update(kwargs) | Update GL options rather than replacing all. See set_gl_options(). | 625941ef73bcbd0ca4b2c5df |
def subject_member_update(context, memb_id, values): <NEW_LINE> <INDENT> session = get_session() <NEW_LINE> memb_ref = _subject_member_get(context, memb_id, session) <NEW_LINE> _subject_member_update(context, memb_ref, values, session) <NEW_LINE> return _subject_member_format(memb_ref) | Update an SubjectMember object. | 625941ef097d151d1a2233c1 |
def is_device_at(self, address: int) -> bool: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._i2c.read_byte(address) <NEW_LINE> return True <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> return False | :param address: an I2C address
:returns true if there is an I2C device at this address | 625941ef32920d7e50b2873f |
def __init__(self, listener, online_experiment, out_hostname, out_port, plot_sensors, use_out_server, save_data, model_base_name, save_model_trainer_params, handle=None, backlog=None, spawn='default', **ssl_args): <NEW_LINE> <INDENT> self.online_experiment = online_experiment <NEW_LINE> self.out_hostname = out_hostname... | adapt_model only needed to know for saving | 625941ef63f4b57ef0001673 |
def testGetWorkflowGroup(self): <NEW_LINE> <INDENT> requestTypes = ("StepChain", "TaskChain", "ReReco") <NEW_LINE> for wflowType in requestTypes: <NEW_LINE> <INDENT> wflowObj = Workflow("wflow_test", {"RequestType": wflowType, "DbsUrl": "a_dbs_url"}) <NEW_LINE> self.assertEqual(wflowObj.getWorkflowGroup(), "production"... | Test the `getWorkflowGroup` method functionality | 625941ef1d351010ab856085 |
def test_department21(self): <NEW_LINE> <INDENT> self.assertTrue(self.driver.department_Select_sj()) | 查询部门-成功 | 625941ef5166f23b2e1a56c3 |
def remove_punct(text): <NEW_LINE> <INDENT> no_punct = "" <NEW_LINE> for ch in text: <NEW_LINE> <INDENT> if ch not in string.punctuation: <NEW_LINE> <INDENT> no_punct = no_punct + ch <NEW_LINE> <DEDENT> <DEDENT> return no_punct | This function is used to remove all punctuation
marks from a string. Spaces do not count as punctuation and should
not be removed. The funcion takes a string and returns a new string
which does not contain any puctuation. For example:
>>> remove_punct("Hello, World!")
'Hello World'
>>> remove_punct("-- ...Hey! -- Yes?... | 625941ef5e10d32532c5f48f |
def rearange_board(queens_positions, queen): <NEW_LINE> <INDENT> queen_row = queen[0] <NEW_LINE> minimum_conflicts = [] <NEW_LINE> minimum_conflict = float('inf') <NEW_LINE> for test_col in range(len(queens_positions)+1): <NEW_LINE> <INDENT> num_conflicts = 0 <NEW_LINE> for second_queen in range(len(queens_positions)):... | chose a place to put the choosen queen and place it on the board | 625941efe5267d203edce200 |
def _get_unpatched(cls): <NEW_LINE> <INDENT> while cls.__module__.startswith('setuptools'): <NEW_LINE> <INDENT> cls, = cls.__bases__ <NEW_LINE> <DEDENT> if not cls.__module__.startswith('distutils'): <NEW_LINE> <INDENT> raise AssertionError( "distutils has already been patched by %r" % cls ) <NEW_LINE> <DEDENT> return ... | Protect against re-patching the distutils if reloaded
Also ensures that no other distutils extension monkeypatched the distutils
first. | 625941efc4546d3d9de72fa3 |
def stft(self, x, fftsize=128, step=65, mean_normalize=True, real=False, compute_onesided=True): <NEW_LINE> <INDENT> if real: <NEW_LINE> <INDENT> local_fft = np.fft.rfft <NEW_LINE> cut = -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> local_fft = np.fft.fft <NEW_LINE> cut = None <NEW_LINE> <DEDENT> if compute_onesided... | Compute STFT for 1D real valued input X | 625941ef55399d3f05588c22 |
def update(self, friendly_name=values.unset, unique_name=values.unset, attributes=values.unset): <NEW_LINE> <INDENT> data = values.of({ 'FriendlyName': friendly_name, 'UniqueName': unique_name, 'Attributes': attributes, }) <NEW_LINE> payload = self._version.update( 'POST', self._uri, data=data, ) <NEW_LINE> return Chan... | Update the ChannelInstance
:param unicode friendly_name: The friendly_name
:param unicode unique_name: The unique_name
:param unicode attributes: The attributes
:returns: Updated ChannelInstance
:rtype: twilio.rest.ip_messaging.v1.service.channel.ChannelInstance | 625941efc432627299f051b4 |
def iterrows(filename, encoding=ENCODING, dialect=DIALECT, rowtype=ROWTYPE, **fmtparams): <NEW_LINE> <INDENT> with open_reader(filename, encoding, dialect, rowtype, **fmtparams) as reader: <NEW_LINE> <INDENT> for row in reader: <NEW_LINE> <INDENT> yield row | Iterator yielding rows from a CSV file (closed on exaustion or error).
Args:
filename: File (name) argument for the :func:`py:io.open` call.
encoding (str): Name of the encoding used to decode the file content.
dialect: CSV dialect argument for :func:`csv23.reader`.
rowtype (str):
``'list'`` fo... | 625941ef76d4e153a657f09c |
def _parse_line(self, line, image, matcher=re.compile(r"^(\w+)=(.+)")): <NEW_LINE> <INDENT> if "=" not in line: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> match = matcher.match(line) <NEW_LINE> if not match: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> key, val = match.groups() <NEW_LINE> self[image][key] = val.s... | Parse one line from bitbake -e output or from .env file.
Put result key-value pair into the storage. | 625941ef4d74a7450ccd4730 |
def handle_command(command): <NEW_LINE> <INDENT> response = "" <NEW_LINE> if command.find(COMMAND1) >= 0: <NEW_LINE> <INDENT> response = "does it look like i have eyes too you." <NEW_LINE> <DEDENT> elif command.find(COMMAND2) >= 0: <NEW_LINE> <INDENT> response = "eniglesh plz." <NEW_LINE> <DEDENT> elif command.find(COM... | Determine if the command is valid. If so, take action and return
a response, if necessary. | 625941efcb5e8a47e48b800b |
def __init__( self, element, on=None, bind=None, include_foreign_key_constraints=None ): <NEW_LINE> <INDENT> super(CreateTable, self).__init__(element, on=on, bind=bind) <NEW_LINE> self.columns = [CreateColumn(column) for column in element.columns] <NEW_LINE> self.include_foreign_key_constraints = include_foreign_key_c... | Create a :class:`.CreateTable` construct.
:param element: a :class:`_schema.Table` that's the subject
of the CREATE
:param on: See the description for 'on' in :class:`.DDL`.
:param bind: See the description for 'bind' in :class:`.DDL`.
:param include_foreign_key_constraints: optional sequence of
:class:`_schema.Fore... | 625941efa79ad161976cc6b0 |
def rib_route_update(dev, channel_id, **kwargs): <NEW_LINE> <INDENT> result = [] <NEW_LINE> dest_prefix_iterator = prpd.dest_prefix_limiter(**kwargs) <NEW_LINE> for i in dest_prefix_iterator: <NEW_LINE> <INDENT> kwargs["dest_prefix"] = i <NEW_LINE> updreq = rib_generate_update_req(**kwargs) <NEW_LINE> result.append(prp... | Update attributes in already added static routes
add new route if the route is not present already | 625941ef7047854f462a196e |
def right(self, angle): <NEW_LINE> <INDENT> self._rotate(-angle) | Turn Myturtle right by angle units.
| 625941ef8e71fb1e9831dd11 |
def __awake_next__(self) -> Tuple[Coroutine, Interrupt]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> waiter, interrupt = self._waiting.pop(0) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> raise NoSubscribers <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> __USIM_STATE__.loop.schedule(waiter, signal=interrup... | Awake the oldest waiter | 625941ef26068e7796caf252 |
def CollectdUploadConfig(self, request, context): <NEW_LINE> <INDENT> if self.dut_check != 0: <NEW_LINE> <INDENT> return vsperf_pb2.StatusReply(message="DUT-Host is not Connected [!]" "\nMake sure to establish connection with" ... | Upload collectd config-file on DUT | 625941ef3539df3088e2e8b6 |
def initialize(self, pA: np.array): <NEW_LINE> <INDENT> rho = TaitEOS.TaitEOS_height( self.rho0, self.height, self.B, self.gamma, pA['y'] ) <NEW_LINE> for j in prange(len(pA)): <NEW_LINE> <INDENT> pA[j]['rho'] = rho[j] <NEW_LINE> <DEDENT> return pA | Initialize the particles, should only be run once at the start of the solver.
Parameters
----------
pA: np.array
Particle array, all particles
Returns
-------
pA: np.array
Initialized particle array, all particles. | 625941ef3617ad0b5ed68461 |
def resid_anscombe(self, endog, mu, scale=1.): <NEW_LINE> <INDENT> hyp2f1 = lambda x: special.hyp2f1(2 / 3., 1 / 3., 5 / 3., x) <NEW_LINE> return 3/2. * (endog**(2/3.) * hyp2f1(-self.alpha * endog) - mu**(2/3.) * hyp2f1(-self.alpha * mu)) / (mu * (1+self.alpha * mu)*scale**3)**(1/6) | The Anscombe residuals for the negative binomial family
Parameters
----------
endog : array-like
Endogenous response variable
mu : array-like
Fitted mean response variable
scale : float, optional
An optional argument to divide the residuals by sqrt(scale).
The default is 1.
Returns
-------
resid_ansco... | 625941ef4f88993c3716c5cc |
def update_all(self): <NEW_LINE> <INDENT> for device in self.home.devices: <NEW_LINE> <INDENT> device.fire_update_event() | Signal all devices to update their state. | 625941ef3346ee7daa2b32db |
def __IsMotorEnabled(self): <NEW_LINE> <INDENT> return _Box2D.b2RevoluteJoint___IsMotorEnabled(self) | __IsMotorEnabled(b2RevoluteJoint self) -> bool
Is the joint motor enabled? | 625941ef66656f66f7cbc718 |
def forward(self, index, c, w): <NEW_LINE> <INDENT> return F.sigmoid(self.scale * (index- c - w / 2)) | :param index: Float (batch, length, 1)
:param c: Float (batch, 1, 1)
:param w: Float (batch, 1, 1)
:return:
masks: Float (batch, length, 1) | 625941ef566aa707497f4acb |
def parse_arguments(self): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description="Liberouter GUI REST API\n" "CESNET 2016 - 2017.\n\n" "Authors: Petr Stehlik, Jakub Neruda, Petr Velan, Radek Krejci\n" "GitHub: https://github.com/CESNET/liberouter-gui" , formatter_class=RawTextHe... | Handle arguments | 625941ef462c4b4f79d1dc3a |
def __init__(self, min_alpha_step, alpha_step = 1., **kwargs): <NEW_LINE> <INDENT> self.minStepSize = min_alpha_step <NEW_LINE> self.stepSize = alpha_step <NEW_LINE> self.goldenNumber = (math.sqrt(5) - 1) / 2. | Needs to have :
- a minimum step size (min_alpha_step)
Can have :
- a step modifier, a factor to modulate the step (alpha_step = 1.) | 625941ef0a50d4780f667402 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.