code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def replace_hosts(self, hostmap): <NEW_LINE> <INDENT> ipmap = hostmap[core.AddrType.IP4.value] <NEW_LINE> saddr = bytes(self.data[self._saddr]) <NEW_LINE> daddr = bytes(self.data[self._daddr]) <NEW_LINE> if saddr in ipmap: <NEW_LINE> <INDENT> self.data[self._saddr] = ipmap[saddr] <NEW_LINE> <DEDENT> if daddr in ipmap: ...
Replace source/destination addresses.
625941f3851cf427c661aaf4
def get_bbox_crop(image, bbox): <NEW_LINE> <INDENT> h, w = image.shape[:2] <NEW_LINE> xmin, ymin, xmax, ymax = bbox <NEW_LINE> xmin, ymin = max(0, int(xmin)), max(0, int(ymin)) <NEW_LINE> xmax, ymax = min(w, int(xmax)), min(h, int(ymax)) <NEW_LINE> roi = image[ymin:ymax, xmin:xmax] <NEW_LINE> return roi
:param image: :param bbox: :return:
625941f30a50d4780f667481
def testNameserver(self): <NEW_LINE> <INDENT> self.namesTest( self.resolver.lookupNameservers('test-domain.com'), [dns.Record_NS('39.28.189.39', ttl=19283784)] )
Test DNS 'NS' record queries
625941f356ac1b37e62647ad
def _valid_lambda_expr(self, lambda_expr, ctx_bound_vars): <NEW_LINE> <INDENT> bound_args = [] <NEW_LINE> expr = lambda_expr <NEW_LINE> while isinstance(expr, LambdaExpression): <NEW_LINE> <INDENT> bound_args.append(expr.variable) <NEW_LINE> expr = expr.term <NEW_LINE> <DEDENT> body = expr <NEW_LINE> if isinstance(body...
Check whether this `LambdaExpression` should be considered when enumerating programs. Arguments: lambda_expr: `LambdaExpression` ctx_bound_vars: Bound variables from the containing context
625941f350485f2cf553d386
def check(self, filename, header): <NEW_LINE> <INDENT> if not self.is_applicable(header): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if self.info.keytype == "C": <NEW_LINE> <INDENT> return self.check_column(filename, header) <NEW_LINE> <DEDENT> elif self.info.keytype == "G": <NEW_LINE> <INDENT> return self.che...
Pull the value(s) corresponding to this Validator out of it's `header` or the contents of the file. Check them against the requirements defined by this Validator.
625941f376e4537e8c351c63
def testXSplot(self): <NEW_LINE> <INDENT> feMat = mx.mixedMat({'fe56': 1.0}) <NEW_LINE> feMat.setDensity(8.0) <NEW_LINE> ffactors = feMat.microDat['fe56']['ffactor'] <NEW_LINE> totxs = feMat.microDat['fe56']['total'] <NEW_LINE> xsplt.xsPlot(totxs[::-1], label='Fe56 inf dilution') <NEW_LINE> totxs_ssheild = totxs * ffac...
Test ability to read XS file, and plot xs at multiple dilutions.
625941f3a8370b7717052e88
def test_one(self): <NEW_LINE> <INDENT> self.assertEqual(self.filter(1.0), 100)
One returns 100.
625941f3009cb60464c63997
def open_pdf(self, bbox, width, height): <NEW_LINE> <INDENT> self.check_session_timeout() <NEW_LINE> post_data = { "WIDTH" : "%d" % width, "HEIGHT" : "%d" % height, "MAPBBOX" : "%f,%f,%f,%f" % bbox, "SLD_BODY" : "", "RFV_REF" : self.code_commune} <NEW_LINE> url = "http://www.cadastre.gouv.fr/scpc/imprimerExtraitCadastr...
ouvre l'export pdf de la commune courante, pour la bbox donnée, avec la taille donnée
625941f345492302aab5e8b4
def push(self, x): <NEW_LINE> <INDENT> self.stack1.append(x) <NEW_LINE> self.size += 1
Push element x to the back of queue. :type x: int :rtype: void
625941f33346ee7daa2b335c
def manager_property(method=None): <NEW_LINE> <INDENT> if method is None: <NEW_LINE> <INDENT> return manager_property <NEW_LINE> <DEDENT> @wraps(method) <NEW_LINE> def wrapped(self): <NEW_LINE> <INDENT> return RelatedManager(self, method(self)) <NEW_LINE> <DEDENT> return property(wrapped)
Decorates a method that returns a QuerySet instance and expose it as a manager. This is useful to define custom accessors for related value, providing a consistent api between your custom managers and the related managers automatically created by Django. Usage: .. code-block:: python # models.py ...
625941f31f037a2d8b9467e6
def FORECAST_LINEAR(*args) -> Function: <NEW_LINE> <INDENT> return Function("FORECAST_LINEAR", args)
See FORECAST
625941f3be383301e01b5a64
def play(): <NEW_LINE> <INDENT> print("-------Rock Paper Scissiors---------") <NEW_LINE> print("1. Rock\n2. Paper\n3. Scissors") <NEW_LINE> print("------------------------------------------------") <NEW_LINE> rounds = int(input("Enter the number of rounds you want to play: ")) <NEW_LINE> print("------------------------...
Rock Paper Scissors is two person game, where eachone of them tosses the rock, paper or scissors. Followig are the rules: -Rock smashes the scissors. -Paper wraps the rock. -Scissors cut the paper.
625941f3cad5886f8bd275c3
def __init__(self, screen): <NEW_LINE> <INDENT> self.screen = screen <NEW_LINE> self.image = pygame.image.load('images/ship.bmp') <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.screen_rect = self.screen.get_rect() <NEW_LINE> self.rect.centerx = self.screen_rect.centerx <NEW_LINE> self.rect.bottom = self.s...
Initialize the ship and set its starting position.
625941f385dfad0860c3b448
def plot_fields(self, time_step, view=[float('-inf'), float('-inf'), float('inf'), float('inf')], save_directory=os.path.join(os.getcwd(), 'images'), save_name='analytical', fmt='png', dpi=100): <NEW_LINE> <INDENT> for name, field in self.fields.items(): <NEW_LINE> <INDENT> self.fields[name].time_step = time_step <NEW_...
Plots the velocity and pressure fields. Parameters ---------- time_step: integer Index used to as a suffix for the file names. view: 4-list of floats, optional Bottom-left and top-right coordinates of the view to plot; default: entire domain. save_directory: string, optional Directory where to save the images;...
625941f330c21e258bdfaa8f
def remove_types(self, res): <NEW_LINE> <INDENT> result = [res[0]] <NEW_LINE> for row in res[1:]: <NEW_LINE> <INDENT> result.append(tuple(Operation.pv(idx, row) for idx in range(len(row)))) <NEW_LINE> <DEDENT> return result
This method takes the results 'res' that include also the typed value and returns a version of such results without the types that is ready to be stored on the file system.
625941f3bd1bec0571d90c1a
def get_channels(self, sort=False): <NEW_LINE> <INDENT> if sort: <NEW_LINE> <INDENT> channels = self._channels_by_name.values()[:] <NEW_LINE> channels.sort(lambda a, b: cmp(a.name, b.name)) <NEW_LINE> channels.sort(lambda a, b: cmp_channel(a, b)) <NEW_LINE> return channels <NEW_LINE> <DEDENT> return self._channels_by_n...
Get all channels
625941f3596a89723608a0a3
def generate_device_factory_permissions_btrfs_test(self): <NEW_LINE> <INDENT> dev1 = StorageDevice( "dev1", fmt=get_format("btrfs"), size=Size("10 GiB") ) <NEW_LINE> dev2 = BTRFSVolumeDevice( "dev2", size=Size("5 GiB"), parents=[dev1] ) <NEW_LINE> self._add_device(dev1) <NEW_LINE> self._add_device(dev2) <NEW_LINE> dev2...
Test GenerateDeviceFactoryPermissions with btrfs.
625941f37cff6e4e81117f70
def to_stderr(self, message, only_once=False): <NEW_LINE> <INDENT> assert isinstance(message, compat_str) <NEW_LINE> if self.params.get('logger'): <NEW_LINE> <INDENT> self.params['logger'].error(message) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._write_string('%s\n' % self._bidi_workaround(message), self._out_...
Print message to stderr
625941f3f7d966606f6aa5f6
def decode(token, key, algorithms=None, options=None, audience=None, issuer=None, subject=None, access_token=None): <NEW_LINE> <INDENT> defaults = { 'verify_signature': True, 'verify_aud': True, 'verify_iat': True, 'verify_exp': True, 'verify_nbf': True, 'verify_iss': True, 'verify_sub': True, 'verify_jti': True, 'veri...
Verifies a JWT string's signature and validates reserved claims. Args: token (str): A signed JWS to be verified. key (str or dict): A key to attempt to verify the payload with. Can be individual JWK or JWK set. algorithms (str or list): Valid algorithms that should be used to verify the JWS. au...
625941f34e4d5625662d49ba
def test_home_page_has_iterable(): <NEW_LINE> <INDENT> from .views import home_page <NEW_LINE> response = home_page(req) <NEW_LINE> assert hasattr(response["bag_list"], "__iter__")
Test that the home page view responds with iterable named bag_list.
625941f3ac7a0e7691ed46ab
def set_store(store, key=_store_registry_key, app=None): <NEW_LINE> <INDENT> app = app or webapp2.get_app() <NEW_LINE> app.registry[key] = store
Sets an instance of :class:`I18nStore` in the app registry. :param store: An instance of :class:`I18nStore`. :param key: The key used to retrieve the instance from the registry. A default is used if it is not set. :param request: A :class:`webapp2.WSGIApplication` instance used to retrieve the inst...
625941f36e29344779a62bfc
def __init__(self, mdp, discount = 0.9, iterations = 100): <NEW_LINE> <INDENT> self.mdp = mdp <NEW_LINE> self.discount = discount <NEW_LINE> self.iterations = iterations <NEW_LINE> self.values = util.Counter() <NEW_LINE> self.actions = {} <NEW_LINE> for _ in range(iterations): <NEW_LINE> <INDENT> new_stateValues = {} <...
Your value iteration agent should take an mdp on construction, run the indicated number of iterations and then act according to the resulting policy. Some useful mdp methods you will use: mdp.getStates() mdp.getPossibleActions(state) mdp.getTransitionStatesAndProbs(state, action) mdp.getReward(state, a...
625941f330bbd722463cc3b4
@memoize(session=True) <NEW_LINE> def package_role_expand(apiurl, project, package, role='maintainer', inherit=True): <NEW_LINE> <INDENT> meta = ETL.fromstringlist(show_package_meta(apiurl, project, package)) <NEW_LINE> users = meta_role_expand(apiurl, meta, role) <NEW_LINE> if inherit: <NEW_LINE> <INDENT> users.extend...
All users with a certain role on a package, including those who have the role directly assigned and those who are part of a group with that role.
625941f3009cb60464c63998
def increase_speed(self): <NEW_LINE> <INDENT> self.ship_speed_factor *= self.speedup_scale <NEW_LINE> self.bullet_speed_factor *= self.speedup_scale <NEW_LINE> self.alien_speed_factor *= self.speedup_scale <NEW_LINE> self.alien_point = int(self.alien_point * self.score_point)
提高速度设置
625941f326068e7796caf2d3
def tsv_line(value_list): <NEW_LINE> <INDENT> return '\t'.join([str(x) for x in value_list])
Create tab-delimited line from Python list Given a Python list, returns a tab-delimited string with each value in the last converted to a string. Arguments: value_list: Python list of values Returns: String with list values separated by tabs.
625941f323e79379d52eeb47
def writeplan(plan,datapath,idlenv): <NEW_LINE> <INDENT> plan.runstr = genplanflags(plan) <NEW_LINE> Planutil.writeplan(plan,datapath) <NEW_LINE> runpath = os.path.join(datapath,plan.finalpath, plan.display_name) <NEW_LINE> if os.path.isfile(runpath): <NEW_LINE> <INDENT> os.remove(runpath) <NEW_LINE> <DEDENT> runstr = ...
Given a plan object, the datapath and the string containing the csh with the idl environment variables, this writes out the data reduction plan and returns the string neccessary to execute the idl code.
625941f33539df3088e2e937
def lower(value): <NEW_LINE> <INDENT> return value.lower()
Convert a string into all lowercase
625941f3ff9c53063f47c7db
def get_cmd_line(self, ignore_option=[], essential_option=[], forbid_option=[]): <NEW_LINE> <INDENT> warning_flag = True <NEW_LINE> essential_flag = False <NEW_LINE> qemu_io_cmd = self.qemu_io_cmd <NEW_LINE> if self.io_options: <NEW_LINE> <INDENT> for io_option in re.split(",", self.io_options): <NEW_LINE> <INDENT> if ...
Generate the command line for qemu-io from the parameters @params ignore_option: list for the options should not in command @params essential_option: list for the essential options @params forbid_option: list for the option should not in command @return: qemu-io command line
625941f3ec188e330fd5ad7d
def event_raw(self): <NEW_LINE> <INDENT> msg = self.midi.read_raw() <NEW_LINE> if msg: <NEW_LINE> <INDENT> return msg <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return []
Returns a list of all MIDI events, empty list if nothing happened. Useful for debugging or checking new devices.
625941f33eb6a72ae02ecad9
def isValid(s): <NEW_LINE> <INDENT> if s is None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> stack = [] <NEW_LINE> look_up = {')':'(', '}':'{', ']':'['} <NEW_LINE> for character in s: <NEW_LINE> <INDENT> if character in ['(', '{', '[']: <NEW_LINE> <INDENT> stack.append(character) <NEW_LINE> <DEDENT> elif not s...
:type s: str :rtype: bool
625941f371ff763f4b549c82
def test_get_edge_from_subedge(self): <NEW_LINE> <INDENT> subvertices = list() <NEW_LINE> subvertices.append(PartitionedVertex(None, "")) <NEW_LINE> subvertices.append(PartitionedVertex(None, "")) <NEW_LINE> subedges = list() <NEW_LINE> subedges.append(MultiCastPartitionedEdge(subvertices[0], subvertices[1])) <NEW_LINE...
test that tests getting a edge from a graph mapper based off its subedge :return:
625941f3097d151d1a223441
def serialize_testinstance(test_instance): <NEW_LINE> <INDENT> ti = test_instance <NEW_LINE> info = { 'value': ti.value, 'date': ti.work_completed.isoformat(), 'save_date': ti.created.isoformat(), 'comment': ti.comment, 'status': ti.status, 'reference': None, 'tolerance': {'type': None, 'act_low': None, 'tol_low': None...
return a dictionary of test_instance properties
625941f3dd821e528d63b78f
def prn_lists(a, max_=None, prn_structure=False): <NEW_LINE> <INDENT> if prn_structure: <NEW_LINE> <INDENT> n_h.shape_finder(a, prn=True) <NEW_LINE> <DEDENT> if max_ is None: <NEW_LINE> <INDENT> max_ = 70 <NEW_LINE> <DEDENT> for i, v in enumerate(a): <NEW_LINE> <INDENT> print(f"\n({i})...") <NEW_LINE> for j in v: <NEW_...
Print nested lists as string. Requires -------- ``npg.shape_finder`` See Also -------- ``npg_helpers.shape_finder`` to print or return the structure of the nested structure.
625941f34e696a04525c9a39
def append( self, point: List[List[int]] ): <NEW_LINE> <INDENT> self.__coordinates.append(point) <NEW_LINE> point1 = (sum(point[0]) / 2, sum(point[1]) / 2) <NEW_LINE> point2 = (sum(self.__coordinates[-1][0]) / 2, sum(self.__coordinates[-1][1]) / 2) <NEW_LINE> self.__length += util.manhattan_distance(point1, point2)
Add a value to the path
625941f345492302aab5e8b5
def fit(self, X, y, sample_weight=None): <NEW_LINE> <INDENT> if np.issubdtype(y.dtype, np.signedinteger): <NEW_LINE> <INDENT> self.n_classes = np.unique(y).shape[0] <NEW_LINE> if self.n_classes == 2: <NEW_LINE> <INDENT> self.n_classes = 1 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.n_classes = 1
Fit the estimator. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data y : numpy, shape (n_samples, n_targets) Target values. Will be cast to X's dtype if necessary sample_weight : array, shape (n_samples,) Individual weights for each sample
625941f3a17c0f6771cbe63a
def squareSurface(*args, **kwargs): <NEW_LINE> <INDENT> pass
This command produces a square surface given 3 or 4 curves. Returns: `string[]` Object name and node name
625941f3167d2b6e31219180
def __init__(self, app_id: str) -> None: <NEW_LINE> <INDENT> self.app_id = app_id
Create a signing manager.
625941f3e1aae11d1e74a2a9
def get(self): <NEW_LINE> <INDENT> all_courses = course_dao.get_all() <NEW_LINE> return course_schema.dump(all_courses, many=True)
An endpoint to get all courses from the database. Parameters ---------- None Returns ------- [JSON] dict of the form {"courses": [list-of-courses]}
625941f3236d856c2ad44dcf
def findMedianSortedArrays(self, nums1, nums2): <NEW_LINE> <INDENT> nums1len=len(nums1) <NEW_LINE> nums2len=len(nums2) <NEW_LINE> smallnum,medinum=divmod(nums1len+nums2len,2) <NEW_LINE> crusmall=1 <NEW_LINE> crunums1=0 <NEW_LINE> crunums2=0 <NEW_LINE> smallnum+=medinum <NEW_LINE> while crusmall < smallnum : <NEW_LINE> ...
:type nums1: List[int] :type nums2: List[int] :rtype: float
625941f3796e427e537b0bb6
def testRaisesUnableToParseForInvalidFiles(self): <NEW_LINE> <INDENT> parser = google_logging.GoogleLogParser() <NEW_LINE> knowledge_base_values = {'year': 2020} <NEW_LINE> invalid_file_name = 'access.log' <NEW_LINE> invalid_file_path = self._GetTestFilePath([invalid_file_name]) <NEW_LINE> self._SkipIfPathNotExists(inv...
Test that attempting to parse an invalid file should raise an error.
625941f3de87d2750b860385
def _ows_check_charm_func(state, message, charm_func_with_configs): <NEW_LINE> <INDENT> if charm_func_with_configs: <NEW_LINE> <INDENT> charm_state, charm_message = charm_func_with_configs() <NEW_LINE> if charm_state != 'active' and charm_state != 'unknown': <NEW_LINE> <INDENT> state = workload_state_compare(state, cha...
Run a custom check function for the charm to see if it wants to change the state. This is only run if not in 'maintenance' and tests to see if the new state is more important that the previous one determined by the interfaces/relations check. @param state: the previously determined state so far. @param message: the u...
625941f3be8e80087fb21223
def encrypter(self): <NEW_LINE> <INDENT> table = range(256) <NEW_LINE> self.__ksa__(table) <NEW_LINE> i = 0 <NEW_LINE> j = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> i = (i + 1) % 256 <NEW_LINE> j = (j + table[i]) % 256 <NEW_LINE> table[i], table[j] = table[j], table[i] <NEW_LINE> k = table[(table[i] + table[j]) % 25...
generator for big data or big file
625941f33346ee7daa2b335d
def _set_threshold(self, module_name, threshold): <NEW_LINE> <INDENT> util.dict_set_path(self.modules, module_name, dict(__threshold__=threshold))
Sets a special loglevel for the given module.
625941f33eb6a72ae02ecada
def validate_scope(self, client, scope): <NEW_LINE> <INDENT> return True
Returns True if the scope is valid for the given client
625941f363b5f9789fde76d1
def fit(self, weather_source): <NEW_LINE> <INDENT> for modeling_period_label, modeling_period in self.modeling_period_set.iter_modeling_periods(): <NEW_LINE> <INDENT> filtered_data = self._filter_by_modeling_period( self.trace, modeling_period) <NEW_LINE> filtered_trace = EnergyTrace( self.trace.interpre...
Fit all models associated with this trace. Parameters ---------- weather_source : eemeter.weather.ISDWeatherSource Weather source to use in creating covariate data.
625941f3f7d966606f6aa5f7
def __init__(self, name=None, brief='', **field_args): <NEW_LINE> <INDENT> Widget.__init__(self, name=name, brief=brief, **field_args) <NEW_LINE> self.tag_name = "div" <NEW_LINE> self[0] = tag.Part(tag_name="div", attribs={"style":"display:none;"}) <NEW_LINE> self[0][0] = tag.Part(tag_name="p") <NEW_LINE> self[0][0][0]...
label: The text appearing in a label tag to the left of the input field label_class: The css class of the label to the left of the input field error_class: The class applied to the hidden paragraph on error. input_text: The default text in the text input field, field name used as name attribute redstar: If True a red a...
625941f315baa723493c4566
def tok_touch_all(self, touch_tokens, msgatime): <NEW_LINE> <INDENT> cursor = self.conn.cursor() <NEW_LINE> for token in touch_tokens: <NEW_LINE> <INDENT> cursor.execute("UPDATE bayes_token SET atime=%s WHERE token=%s", (msgatime, token)) <NEW_LINE> <DEDENT> self.conn.commit() <NEW_LINE> cursor.close()
Update the access time for all the specified tokens.
625941f33c8af77a43ae3d93
def update_value(self, delta): <NEW_LINE> <INDENT> self.value += delta <NEW_LINE> self.value = min(self.value, self.maximum) <NEW_LINE> self.value = max(self.value, 0) <NEW_LINE> percentage = self.value * 1.0 / self.maximum <NEW_LINE> self.filled_bar = pygame.Surface((self.frame.w * percentage, self.frame.h)) <NEW_LINE...
Updates the value of the of the bar with value_change. value_change should be a change such as dx would be.
625941f3bf627c535bc137bb
def revenue_pie(year, labels, savefig = False, save_as = 'revenue_pie'): <NEW_LINE> <INDENT> fig, ax = plt.subplots(figsize=(8,6)) <NEW_LINE> ax.pie([df[labels[0]][year], df[labels[1]][year], df[labels[2]][year], df[labels[3]][year], df[labels[4]][year]], explode = [0.13, 0.09, 0.06, 0.02, 0.01], wedgeprops=dict(width=...
input, fiscal year as index location for value in the 'Year' column and a list of 5 strings matching the column names for each top revenue source output is a pie plot of these 5 revenue sources color is determined by the color dictionary with keys = each label
625941f3a934411ee3751c81
def _update_category_id_by_page_data(self, page_data, category_map, delete_category_id_list): <NEW_LINE> <INDENT> def _deta_format(id_str): <NEW_LINE> <INDENT> str_list = [] <NEW_LINE> ids = [x for x in id_str.split(',') if x] <NEW_LINE> for _id_str in ids: <NEW_LINE> <INDENT> alist = _id_str.split(':') <NEW_LINE> cate...
pageにClientで作成されたIDを保持してる場合は,DBで生成されたIDに差し替える
625941f38e7ae83300e4b5ba
def __init__(self, config_data, csvToolInfo, unhandledCSV): <NEW_LINE> <INDENT> super().__init__(config_data, csvToolInfo, unhandledCSV) <NEW_LINE> self.logger = logging.getLogger("LQMT.FlexText.{0}".format(self.getName())) <NEW_LINE> self.header_line = False <NEW_LINE> self.increment_file = False <NEW_LINE> self.flext...
Constructor
625941f3796e427e537b0bb7
def xkcd(scale=1, length=100, randomness=2): <NEW_LINE> <INDENT> if rcParams['text.usetex']: <NEW_LINE> <INDENT> raise RuntimeError( "xkcd mode is not compatible with text.usetex = True") <NEW_LINE> <DEDENT> from matplotlib import patheffects <NEW_LINE> return rc_context({ 'font.family': ['xkcd', 'Humor Sans', 'Comic S...
Turns on `xkcd <https://xkcd.com/>`_ sketch-style drawing mode. This will only have effect on things drawn after this function is called. For best results, the "Humor Sans" font should be installed: it is not included with matplotlib. Parameters ---------- scale : float, optional The amplitude of the wiggle perpe...
625941f30fa83653e46575a3
def grad(theta, X, y, lambda_): <NEW_LINE> <INDENT> n = len(X[0]) <NEW_LINE> m = X.shape[0] <NEW_LINE> vek = [] <NEW_LINE> for j in range(n): <NEW_LINE> <INDENT> sum = 0 <NEW_LINE> for i in range(m): <NEW_LINE> <INDENT> hi = h(X[i], theta) <NEW_LINE> sum += (y[i]-hi)*X[i][j] <NEW_LINE> <DEDENT> sum = (-sum/m) + ((lambd...
6.5 Odvod cenilne funkcije. Vrne numpyev vektor v velikosti vektorja theta.
625941f3cc40096d61595f39
def setTextEdit( self, textEdit ): <NEW_LINE> <INDENT> if ( self._textEdit ): <NEW_LINE> <INDENT> self._textEdit.removeAction(self._findAction) <NEW_LINE> <DEDENT> self._textEdit = textEdit <NEW_LINE> if ( textEdit ): <NEW_LINE> <INDENT> textEdit.addAction(self._findAction)
Sets the text edit that this find widget will use to search. :param textEdit | <QTextEdit>
625941f37b180e01f3dc4ddb
@app.route("/api/v1.0/start_date/<start_date>") <NEW_LINE> def start_date(start_date): <NEW_LINE> <INDENT> session = Session(engine) <NEW_LINE> results = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).filter(Measurement.date >= start_date).all() <NEW_LINE> dates = sess...
Return a JSON list of the minimum temperature, the average temperature, and the max temperature for a given start date that matches the path variable supplied by the user, or a 404 if not.
625941f33cc13d1c6d3c7963
def index(self, filename): <NEW_LINE> <INDENT> t = Tokenizator() <NEW_LINE> try: <NEW_LINE> <INDENT> file = open(filename) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> raise FileNotFoundError("File is not found") <NEW_LINE> <DEDENT> for token in t.generate_alpha_and_digits(file.read()): <NEW_LINE> <INDENT> s...
This method indexes text and adds all alphabetical and digital tokens that it meet into a database with the text positions of their beginning and end. @param filename: name of the text file to be indexed
625941f3e76e3b2f99f3aded
def _plot_div_producer(self): <NEW_LINE> <INDENT> import os <NEW_LINE> import hashlib <NEW_LINE> from jinja2 import Template <NEW_LINE> template = os.path.join(os.path.dirname(__file__), "map_div.html") <NEW_LINE> data = self.data_processing() <NEW_LINE> zone = geopandas.GeoDataFrame.from_file(self.locator.get_zone_geo...
Since this plot doesn't use plotly to plot, we override _plot_div_producer to return a string containing the html div to use for this plot. The template ``map_div.html`` expects some parameters: Here is some example data (in a YAML-like format for documentation purposes) :: data: DH: connected_buil...
625941f36aa9bd52df037394
def test_run_is_uar(self): <NEW_LINE> <INDENT> random.seed(0) <NEW_LINE> nb_samples = 1000 <NEW_LINE> adjacency_list = [ (1, {5}), (2, {4, 6}), (3, {5}) ] <NEW_LINE> expected_adjacency_lists = [[ (1,{5}), (2,{4, 6}), (3,{5}) ], [ (1,{5}), (2,{5, 6}), (3,{4}) ], [ (1,{6}), (2,{4, 5}), (3,{5}) ], [ (1,{5}), (2,{4, 5}), (...
Running the curveball algorithm on a small graph space (only 5 expected adjacency lists)
625941f3b7558d58953c54f3
def restrict(self, axis_name, selector, in_place=True): <NEW_LINE> <INDENT> if in_place: <NEW_LINE> <INDENT> dest = self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dest = self.copy(axes_only=True) <NEW_LINE> dest._assignments.update(self._assignments) <NEW_LINE> <DEDENT> new_ax, sl = dest._axes[axis_name].restrictio...
Restrict the AxisManager by selecting a subset of items in some Axis. The Axis definition and all data fields mapped to that axis will be modified. Arguments: axis_name (str): The name of the Axis. selector (slice or special): Selector, in a form understood by the underlying Axis class (see the .restriction m...
625941f3f9cc0f698b140be2
def test_title(self): <NEW_LINE> <INDENT> assert self.celtuce.title == "Celtuce" <NEW_LINE> assert self.cyclone.title == "Tropical Depression Ten (2005)"
Test the title.
625941f329b78933be1e5c90
def recurse_children(self, value): <NEW_LINE> <INDENT> self.values.append(value) <NEW_LINE> if value.parent: <NEW_LINE> <INDENT> value.level = value.parent.level + 1 <NEW_LINE> <DEDENT> if value.children: <NEW_LINE> <INDENT> value.value += "*" <NEW_LINE> <DEDENT> for c in value.children: <NEW_LINE> <INDENT> self.recurs...
Appends value and all of its child values to this facet's values list using depth-first recursion. Value levels are also calculated for display purposes.
625941f38e05c05ec3eea965
def list_command_history( self, command=None, queue=None, start=None, stop=None, page_size=500, descending=False, ): <NEW_LINE> <INDENT> params = { "order": "desc" if descending else "asc", } <NEW_LINE> if queue: <NEW_LINE> <INDENT> params["queue"] = queue <NEW_LINE> <DEDENT> if page_size is not None: <NEW_LINE> <INDEN...
Reads command history entries between the specified start and stop time. :param str command: Either a fully-qualified XTCE name or an alias in the format ``NAMESPACE/NAME``. :param str queue: Name of the queue that the command was assigned to. :param ~datetime.datetime start: Minimum generation tim...
625941f3cc0a2c11143dd47d
def grid4d_path(): <NEW_LINE> <INDENT> return ROOT.joinpath("pres_temp_4D.nc")
Return path to the Grid 4D
625941f38e05c05ec3eea966
def extract_file(self, filename): <NEW_LINE> <INDENT> filepath = os.path.join(self._root, filename) <NEW_LINE> with open(filepath, "r") as yfile: <NEW_LINE> <INDENT> return yaml.load(yfile, FmuLoader)
Extract file method
625941f363d6d428bbe44add
def date(self, date): <NEW_LINE> <INDENT> if date is not None: <NEW_LINE> <INDENT> split = date.split('~') <NEW_LINE> if len(split) == 1: <NEW_LINE> <INDENT> self._lbound = Timestamp(date) <NEW_LINE> self._rbound = Timestamp(date) <NEW_LINE> <DEDENT> elif split[0] == '': <NEW_LINE> <INDENT> self._rbound = Timestamp(spl...
Pass in the date used in the original query. Parameters ---------- date : str Date (date range) that was queried: date -> 'd', '~d', 'd~', 'd~d' d -> '%Y-%m-%d %H:%M:%S,%f', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d'
625941f34f6381625f115027
def set_curve_data_point(self, curve, index, sensor_units, temperature): <NEW_LINE> <INDENT> self.command("CRVPT {},{},{},{}".format(curve, index, sensor_units, temperature))
Configures a user curve point Args: curve (int or str): * Specifies which curve to configure index (int): * Specifies the points index in the curve sensor_units (float): * Specifies sensor units for this point to 6 digits temperature (float): * Specifies the correspon...
625941f3b830903b967e9ef0
def test_De(self): <NEW_LINE> <INDENT> system = System(uwp='D770777-7') <NEW_LINE> self.assertTrue('De' in system.trade_codes)
Test De
625941f32eb69b55b151cea4
def __init__(self, text): <NEW_LINE> <INDENT> self.message_text = text <NEW_LINE> self.valid_words = load_words(WORDLIST_FILENAME)
Initializes a CiphertextMessage object text (string): the message's text a CiphertextMessage object has two attributes: self.message_text (string, determined by input text) self.valid_words (list, determined using helper function load_words)
625941f344b2445a3393267d
def print_complete(): <NEW_LINE> <INDENT> if tcon.now() == 0: <NEW_LINE> <INDENT> print("\n") <NEW_LINE> log.error(" Test Not Executed!\n") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(f"\n************ Time {tcon.now()} {TIME_UNIT}: " f"Testbench Completed *****************")
Print a message after a test has completed (successfully or otherwise). This function also checks if test has actually run for non-zero time. This function should be called at the end of every tcon.py, right befor simulation is halted with tcon.halt() Args: None Returns: None
625941f356b00c62f0f14c49
def median(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.total == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if len(self.bins) >= self.maxbins: <NEW_LINE> <INDENT> return self.quantiles(0.5)[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mid = (self.total) / 2 <NEW_LINE> if self.total % 2 ==...
Return a median for the points inserted into the histogram. This will be the true median whenever the histogram has less than the maximum number of bins, otherwise it will be an approximation.
625941f3507cdc57c63072d6
def dict_to_stock_info(stock_dict): <NEW_LINE> <INDENT> logging.debug(f'Nse dict: {stock_dict}') <NEW_LINE> pChange = Decimal(stock_dict["pChange"]).quantize(TWOPLACES) <NEW_LINE> stock_info = StockInfo(stock_dict['name'], NIFTY, stock_dict["lastPrice"], pChange, -1, -1, -1) <NEW_LINE> logging.debug(f' Equivalent Stock...
Convert dictionary returned from Nse to StockInfo object to make it compatible with existing tools :param stock_dict: :return: StockInfo
625941f38c3a8732951589ae
def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> if os.name == 'posix': <NEW_LINE> <INDENT> self._putsocket, self._getsocket = socket.socketpair() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> server.bind(('127.0.0.1', 0)) <NEW_L...
Constructor.
625941f307f4c71912b11a71
def scaler_lobatto(aerr, n_nodes, k, tol): <NEW_LINE> <INDENT> p = 2 * n_nodes - 1 <NEW_LINE> x = tol * (1 - (1 / k)** p) / aerr <NEW_LINE> scaler = x ** (1 / p) <NEW_LINE> return scaler
This function calculates :math:`x` the amount the step size should increase or decrease for the proper adaptive time step size for Gauss-Lobatto nodes. :param numpy.ndarray aerr: the maximum absolute error between the approximate solution :math:`y_h` and the higher accuracy solution :math:`y_{h/k}` :param int ...
625941f37b180e01f3dc4ddc
def getRankingList(): <NEW_LINE> <INDENT> res = [] <NEW_LINE> setUsersRank() <NEW_LINE> rank = list(CustomUser.objects.all()) <NEW_LINE> rank.sort(key=lambda user: user.rank, reverse=False) <NEW_LINE> for user in rank: <NEW_LINE> <INDENT> res.append({"rank": user.rank, "username": user.username, "total": user.wallet_qu...
Metodo que devuelve una lista con el ranking de usuarios.
625941f3627d3e7fe0d6943e
def score_pairwise_gapless(seq1, seq2, matrix): <NEW_LINE> <INDENT> for A, B in zip(seq1, seq2): <NEW_LINE> <INDENT> pair = (A, B) <NEW_LINE> if pair not in matrix: <NEW_LINE> <INDENT> yield matrix[(tuple(reversed(pair)))] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield matrix[pair]
Calculates a score between two aligned sequences without gaps, based on matrix applied. A, B are each paired amino acid in the pairwise alignment Usage: # import various matrices from biopython (many available) from Bio.SubsMat.MatrixInfo import ident, blosum62, pam120, levin a = "ACGEGGGFFFCCC" b = "ACFGGGTFFTCCC" c...
625941f3a4f1c619b28b0616
def _FeedConsumerPools(self, result): <NEW_LINE> <INDENT> if result is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for pool in self.consumer_pools: <NEW_LINE> <INDENT> pool.AddSingleTaskInput(result, from_producer=True)
Callback function used internally to distribute the output of this pool's workers to the registered consumer pools.
625941f3004d5f362079a91a
def save(self, *args, **kwargs): <NEW_LINE> <INDENT> super(ChangeLog, self).save(*args, **kwargs) <NEW_LINE> self.change_request.save()
After saving a log entry, save the parent change to set the updated field value.
625941f37b25080760e39a41
def run(self): <NEW_LINE> <INDENT> server = self._create_server() <NEW_LINE> self._delete_server(server["id"])
Create and then delete a server. Measure the performance of creating and deleting servers with different level of load.
625941f3925a0f43d254a469
def cancel_open_orders(context, data): <NEW_LINE> <INDENT> for asset, orders in get_open_orders().items(): <NEW_LINE> <INDENT> for order in orders: <NEW_LINE> <INDENT> cancel_order(order) <NEW_LINE> if order.amount < 0: <NEW_LINE> <INDENT> add_to_misses(context, asset, True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT...
Cancel all open orders.
625941f3d58c6744b4258249
def test_factorial(self): <NEW_LINE> <INDENT> f1 = lambda n: 1 if n < 2 else n * f1(n - 1) <NEW_LINE> f1 = memo.memo(f1) <NEW_LINE> f2 = lambda n: 1 if n < 2 else n * f2(n - 1) <NEW_LINE> f2 = memo.lru(10)(f2) <NEW_LINE> self.assertEqual(f1(42), f2(42)) <NEW_LINE> for n in range(100): <NEW_LINE> <INDENT> self.assertEqu...
Tests LRUCacheQueue for recursive function calls (factorial)
625941f399cbb53fe67931d0
def read_CIFAR10(data_folder): <NEW_LINE> <INDENT> img_height = 32 <NEW_LINE> img_width = 32 <NEW_LINE> num_class = 10 <NEW_LINE> num_channel = 3 <NEW_LINE> num_val_img = 5000 <NEW_LINE> train_img = [] <NEW_LINE> train_label = [] <NEW_LINE> test_img = [] <NEW_LINE> test_label = [] <NEW_LINE> train_file_list = ['data_ba...
Reads and parses examples from CIFAR10 data files
625941f3d58c6744b425824a
def __str__(self) -> str: <NEW_LINE> <INDENT> return json.dumps(self.to_dict(), indent=2)
Return a `str` version of this Collection object.
625941f3fb3f5b602dac3c86
def draw_arc(startlon, startlat, endlon, endlat, n, upper,outname): <NEW_LINE> <INDENT> n = float(n) <NEW_LINE> u = sqrt((endlon-startlon)**2 + (endlat-startlat)**2)/2 <NEW_LINE> v = u/2.5 <NEW_LINE> dt = u/n <NEW_LINE> theta = atan((endlat-startlat)/(endlon-startlon)) <NEW_LINE> center_x = (endlon + startlon) / 2. <NE...
take the longitude and latitude of two end points, drawn a dotted arc between the two points; n is the number of points along the arc; upper=True/False decides whether the upper or lower half of the ellipse will be drawn as the arc; outname is the route name of the output vtp file
625941f3004d5f362079a91b
def _export_data(self, dirname, clear=False): <NEW_LINE> <INDENT> assets = [] <NEW_LINE> data = [(name, self.get_data(name)) for name in self.get_data_names()] <NEW_LINE> export_assets_and_data(assets, data, dirname, self.id, clear) <NEW_LINE> logger.info('Exported data for %r to %r.' % (self.id, dirname))
Export all assets and data specific to this session. Private method, used by app.export().
625941f399cbb53fe67931d1
def at_init(self): <NEW_LINE> <INDENT> if self.db.is_giving_light: <NEW_LINE> <INDENT> self.delete()
If this is called with the Attribute is_giving_light already set, we know that the timer got killed by a server reload/reboot before it had time to finish. So we kill it here instead. This is the price we pay for the simplicity of the non-persistent delay() method.
625941f39f2886367277ae74
def fake_number_sequence(quantity, length, patterns=['{}'], output_file=None, seed=None): <NEW_LINE> <INDENT> if seed: <NEW_LINE> <INDENT> random.seed(seed) <NEW_LINE> <DEDENT> def _get_random_sequence(pattern, length): <NEW_LINE> <INDENT> sequence = '' <NEW_LINE> for i in range(length): <NEW_LINE> <INDENT> sequence +=...
Generate list of number sequence :param quantity: Number of generated number sequence :param length: Length of each sequence :param patterns: List of patterns :param output_file: path to output file :param seed: :return: - if output_file is None: return a list of sequences, otherwise write generated sequences to ou...
625941f3cad5886f8bd275c4
def reliability_calc(RACC, ACC): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = (ACC - RACC) / (1 - RACC) <NEW_LINE> return result <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return "None"
Calculate reliability. :param RACC: random accuracy :type RACC : float :param ACC: accuracy :type ACC : float :return: reliability as float
625941f33c8af77a43ae3d94
def _linear_alpha_cmap(cmap): <NEW_LINE> <INDENT> alpha_cmap = cmap(np.arange(cmap.N)) <NEW_LINE> alpha_cmap[:, -1] = np.linspace(0, 1, cmap.N) <NEW_LINE> return ListedColormap(alpha_cmap)
add linear alpha to an existing colormap
625941f3293b9510aa2c387c
def load_sols(opt_folder, cols, sol_file_str='solution_*.csv'): <NEW_LINE> <INDENT> sol_files = glob.glob(os.path.join(opt_folder, sol_file_str)) <NEW_LINE> decisions = [] <NEW_LINE> for f in sol_files: <NEW_LINE> <INDENT> df = pd.read_csv(f) <NEW_LINE> decisions.append(np.array(df[cols])) <NEW_LINE> <DEDENT> return de...
Loads solution files from opt_folder, returning a list of np.arrays containing the values from the columns listed in cols. :param opt_folder: :param cols: :param sol_file_str: :return:
625941f3a79ad161976cc732
def lookup(self, name, anynested=False, fuzzy=False): <NEW_LINE> <INDENT> lookin = self._byname <NEW_LINE> if anynested: <NEW_LINE> <INDENT> lookin = self._bystrings <NEW_LINE> <DEDENT> if fuzzy: <NEW_LINE> <INDENT> matched = [] <NEW_LINE> for test in lookin: <NEW_LINE> <INDENT> if name in test: <NEW_LINE> <INDENT> mat...
Looks up the given predicate name and returns all predicates from the answer set whose name matches exactly. If anynested is True, it searches nested predicates as well, so for example a predicate "bar(foo)." will match a search for either "foo" or "bar" if anynested is True, but will only match a search for "bar" if ...
625941f376d4e153a657f11f
def prepare_GPRMC(self, msgparts): <NEW_LINE> <INDENT> assert type(msgparts) == list <NEW_LINE> res = {} <NEW_LINE> try: <NEW_LINE> <INDENT> res["lat"] = msgparts[3] + msgparts[4] <NEW_LINE> res["lon"] = msgparts[5] + msgparts[6] <NEW_LINE> res["SOG"] = float(msgparts[7]) <NEW_LINE> res["COG"] = float(msgparts[8]) <NEW...
>>> nmeaParser().prepare_GPRMC("$GPRMC,133725,V,3851.3970,N,09500.5709,W,0.0000,0.000,300416,,*2C".split(",")) {'SOG': 0.0, 'lon': '09500.5709W', 'COG': 0.0, 'lat': '3851.3970N', 'ts_GPS': datetime.datetime(1900, 1, 1, 13, 37, 25), 'date_GPS': datetime.datetime(2016, 4, 30, 0, 0)}
625941f38da39b475bd65568
def largestContour(contours): <NEW_LINE> <INDENT> largest = (0, []) <NEW_LINE> for c in contours: <NEW_LINE> <INDENT> contour_area = cv2.contourArea(c) <NEW_LINE> if contour_area > largest[0]: <NEW_LINE> <INDENT> largest = (contour_area, c) <NEW_LINE> <DEDENT> <DEDENT> return largest[1]
Finds the contour with the largest area in the list. :param contours: list of contours :returns: the largest countour
625941f316aa5153ce362a65
def send_discovered(self, host, port, path): <NEW_LINE> <INDENT> endpoints = [self._make_endpoint_dict(endpoint) for endpoint in self._dispatcher.get_endpoints()] <NEW_LINE> if path[-1] != '/': <NEW_LINE> <INDENT> path += '/' <NEW_LINE> <DEDENT> path = urljoin(path, 'endpoints') <NEW_LINE> try: <NEW_LINE> <INDENT> conn...
Sends a "discovered" HTTP POST request to the dispatcher servlet of the framework that has been discovered :param host: The address of the sender :param port: Port of the HTTP server of the sender :param path: Path of the dispatcher servlet :return: True if the request has been handled by the peer
625941f34527f215b584ca3e
def getDefault(self, name): <NEW_LINE> <INDENT> return self.__defaults[name] if name in self.__defaults else None;
Gets a default value. @param: string name A variable name @return mixed The default value or None when not given
625941f366656f66f7cbc799
def plugin_end(self): <NEW_LINE> <INDENT> self.xmpp['xep_0030'].del_feature(feature=UserShares.namespace) <NEW_LINE> self.xmpp['xep_0163'].remove_interest(UserShares.namespace) <NEW_LINE> pass
:return:
625941f350485f2cf553d388
def simSetTextureFromUrl(self, object_name, url): <NEW_LINE> <INDENT> self.client.call("simSetTextureFromUrl", object_name, url)
Set texture of an object from a URL resource. Args: object_name (string): Name of object for which the texture is to be set url (string): URL of texture file
625941f3287bf620b61d404c
def __init__(self, ds, augmentors, index=(0, 1), copy=True): <NEW_LINE> <INDENT> self.augs = AugmentorList(augmentors) <NEW_LINE> self.ds = ds <NEW_LINE> self._nr_error = 0 <NEW_LINE> def func(dp): <NEW_LINE> <INDENT> dp = copy_mod.copy(dp) <NEW_LINE> copy_func = copy_mod.deepcopy if copy else lambda x: x <NEW_LINE> tr...
Args: ds (DataFlow): input DataFlow. augmentors (AugmentorList): a list of :class:`imgaug.ImageAugmentor` instance to be applied in order. index: tuple of indices of components. copy (bool): Some augmentors modify the input images. When copy is True, a copy will be made before any augmentors are...
625941f3009cb60464c63999
def AddPython3Template(bus, folder, default=False): <NEW_LINE> <INDENT> return AddGeneralizedTemplate( bus=bus, topic='kattcmd:template:python-added', folder=folder, default=default, defaultname='py3.py', fileending='.py' )
Adds a python3 template to a problem folder.
625941f373bcbd0ca4b2c662
def calc_conv_out_dims(X_shape, W_shape, stride=1, pad=0, dilation=0): <NEW_LINE> <INDENT> dummy = np.zeros(X_shape) <NEW_LINE> s, p, d = stride, pad, dilation <NEW_LINE> if len(X_shape) == 3: <NEW_LINE> <INDENT> _, p = pad1D(dummy, p) <NEW_LINE> pw1, pw2 = p <NEW_LINE> fw, in_ch, out_ch = W_shape <NEW_LINE> n_ex, in_l...
Compute the dimension of the output volume for the specified convolution. Parameters ---------- X_shape : 3-tuple or 4-tuple The dimensions of the input volume to the convolution. If 3-tuple, entries are expected to be (`n_ex`, `in_length`, `in_ch`). If 4-tuple, entries are expected to be (`n_ex`, `in_rows...
625941f35510c4643540f9c1
def test_create_token_invalid_credentials(self): <NEW_LINE> <INDENT> payload = { 'email': 'test@test.com', 'password': 'test123', 'name': 'Test Name', } <NEW_LINE> create_user(**payload) <NEW_LINE> payload = { 'email': 'test@test.com', 'password': 'testtest', } <NEW_LINE> res = self.client.post(TOKEN_URL, payload) <NEW...
Test that token is not created if invalid credentials are given
625941f366656f66f7cbc79a