code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def dataSet2performance(dataSet): <NEW_LINE> <INDENT> newDictionary = copy.deepcopy((dataSet[next(iter(dataSet))])) <NEW_LINE> for keyT in newDictionary: <NEW_LINE> <INDENT> newDictionary[keyT] = 0 <NEW_LINE> <DEDENT> for key0 in dataSet: <NEW_LINE> <INDENT> for key1 in newDictionary: <NEW_LINE> <INDENT> for key2 in da... | Calculate the performance: how many of the files wanted specific permissions | 625941d1046cf37aa974cee0 |
def source_image_link(self, image_id): <NEW_LINE> <INDENT> return self.image_info[image_id]["path"] | Возвращает путь или URL к изображению.
Переопределите этот метод, чтобы вернуть URL-адрес
изображения, если оно доступно в Интернете для легкой отладки. | 625941d13346ee7daa2b2f05 |
def get_builder(builder_file_name): <NEW_LINE> <INDENT> ui_filename = get_data_file('ui', '%s.ui' % (builder_file_name,)) <NEW_LINE> if not os.path.exists(ui_filename): <NEW_LINE> <INDENT> ui_filename = None <NEW_LINE> <DEDENT> builder = Builder() <NEW_LINE> builder.set_translation_domain('network-manager') <NEW_LINE> ... | Return a fully-instantiated Gtk.Builder instance from specified ui
file
:param builder_file_name: The name of the builder file, without extension.
Assumed to be in the 'ui' directory under the data path. | 625941d176e4537e8c35180c |
def getFootprint(self, metadata=None): <NEW_LINE> <INDENT> if not metadata: <NEW_LINE> <INDENT> footprint = self.instance.geometry() <NEW_LINE> <DEDENT> elif not isinstance(metadata, dict): <NEW_LINE> <INDENT> raise ValueError("metadata is not a dictionary") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> equals = [ (ite... | Return the footprint from the collection.
Parameters
----------
metadata: dict
Dictionary of key/value for filtering the collection
(the default is None, which doesn't filter)
Returns
-------
dict
Footprint of all geometries from a collection
Example
-------
>>c = GEEUtil('projects/fao-wapor/L1/L1_AETI_D... | 625941d1ec188e330fd5a936 |
def setUp(self): <NEW_LINE> <INDENT> self._helper = helper.ImportHelper() <NEW_LINE> with tempfile.NamedTemporaryFile('w', suffix='.yaml') as fw: <NEW_LINE> <INDENT> fw.write(MOCK_CONFIG) <NEW_LINE> fw.seek(0) <NEW_LINE> self._helper.add_config(fw.name) | Set up the test. | 625941d163d6d428bbe44688 |
@package.required(['deluged', 'deluge-web']) <NEW_LINE> def index(request): <NEW_LINE> <INDENT> status = get_status() <NEW_LINE> form = None <NEW_LINE> if request.method == 'POST': <NEW_LINE> <INDENT> form = DelugeForm(request.POST, prefix='deluge') <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> _apply_changes(requ... | Serve configuration page. | 625941d15166f23b2e1a52f2 |
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_struct_3I.pack(_x.height, _x.width, _x.step)) <NEW_LINE> length = len(self.corners) <NEW_LINE> buff.write(_struct_I.pack(length)) <NEW_LINE> for val1 in self.corners: <NEW_LINE> <INDENT> _x = val1 <NEW_LINE> buff.wr... | serialize message into buffer
:param buff: buffer, ``StringIO`` | 625941d182261d6c526ab639 |
def make_query(self, args, require_all=True, analyzer=None): <NEW_LINE> <INDENT> if isinstance(args, dict): <NEW_LINE> <INDENT> args = args.items() <NEW_LINE> <DEDENT> if not isinstance(args, list): <NEW_LINE> <INDENT> args = [args] <NEW_LINE> <DEDENT> result = [] <NEW_LINE> for query in args: <NEW_LINE> <INDENT> if is... | Create simple queries (strings or field searches) or
combine multiple queries (AND/OR).
To specifiy rules for field searches, you may want to take a look at
:meth:`~.CommonDatabase.set_field_analyzers`. The parameter
'match_text_partial' can override the previously defined
default setting.
:param args: queries or sea... | 625941d130c21e258bdfa637 |
def remove(name=None, slot=None, fromrepo=None, pkgs=None, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0] <NEW_LINE> <DEDENT> except MinionError as exc: <NEW_LINE> <INDENT> raise CommandExecutionError(exc) <NEW_LINE> <DEDENT> old = list_pkgs() ... | Remove packages via emerge --unmerge.
name
The name of the package to be deleted.
slot
Restrict the remove to a specific slot. Ignored if ``name`` is None.
fromrepo
Restrict the remove to a specific slot. Ignored if ``name`` is None.
Multiple Package Options:
pkgs
Uninstall multiple packages. ``slo... | 625941d1596a897236089c59 |
def test__api_cart_add_one_too_many_1_multi(self): <NEW_LINE> <INDENT> settings.MAX_SELECTIONS_ALLOWED = 1 <NEW_LINE> url = '/__cart/reset.json?reqno=42' <NEW_LINE> expected = {'recycled_count': 0, 'count': 0, 'reqno': 42} <NEW_LINE> self._run_json_equal(url, expected) <NEW_LINE> url = '/__cart/add.json?opusid=co-iss-n... | [test_cart_api.py] /__cart/add: good OPUSID no download too many 1 multi | 625941d17b180e01f3dc4995 |
def convex_hull(labels, indexes=None, fast=True): <NEW_LINE> <INDENT> if indexes is None: <NEW_LINE> <INDENT> indexes = np.unique(labels) <NEW_LINE> indexes.sort() <NEW_LINE> indexes = indexes[indexes != 0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> indexes = np.array(indexes) <NEW_LINE> <DEDENT> if len(indexes) == ... | Given a labeled image, return a list of points per object ordered by
angle from an interior point, representing the convex hull.s
labels - the label matrix
indexes - an array of label #s to be processed, defaults to all non-zero
labels
Returns a matrix and a vector. The matrix consists of one row per
point ... | 625941d1b7558d58953c50ac |
def fsGetValidatedUserConfig(fullyQualifiedFilename): <NEW_LINE> <INDENT> errors = [] <NEW_LINE> configObject = {} <NEW_LINE> try: <NEW_LINE> <INDENT> inputFile = open(fullyQualifiedFilename) <NEW_LINE> configFileContents = '' <NEW_LINE> for line in inputFile: <NEW_LINE> <INDENT> if not re.search('^[ \t]*\/\/', line): ... | Get the user specified gitsummary configuration
Validate the contents and return errors if appropriate.
Return
Dictionary - A dictionary containing the following keys:
KEY_RETURN_STATUS - Boolean - Whether the configuration
returned is valid
KEY_RE... | 625941d1bf627c535bc13368 |
def floatx(): <NEW_LINE> <INDENT> return _FLOATX | Returns the default float type, as a string.
E.g. `'float16'`, `'float32'`, `'float64'`.
Returns:
String, the current default float type.
Example:
>>> tf.keras.backend.floatx()
'float32' | 625941d163b5f9789fde727f |
def dayRangeIntervals(start, end, interval=30, reverse=False, buffer='second'): <NEW_LINE> <INDENT> unit = 'day' <NEW_LINE> start_date = ee.Date(start) <NEW_LINE> end_date = ee.Date(end) <NEW_LINE> begin_date = end_date if reverse else start_date <NEW_LINE> diff = end_date.difference(start_date, unit) <NEW_LINE> comple... | Divide a date range into many DateRange objects. Return a list of DateRange
:param start: the start date
:param end: the end date
:param interval: range of the DateRange in units
:return: a list holding ee.DateRange
:rtype: list | 625941d1187af65679ca52b8 |
def get_id(x): <NEW_LINE> <INDENT> value = x['id'] <NEW_LINE> return value | (dict) -> str
Retrieves value for key "id" from dictionary x. | 625941d1d486a94d0b98e2df |
def update_for_kmz(self): <NEW_LINE> <INDENT> self.gpoints = self.corners <NEW_LINE> self.gnorms = self.norms <NEW_LINE> self.gfaces = {} <NEW_LINE> if list(self.faces.values())[0].shape[1] == 4: <NEW_LINE> <INDENT> for i in self.faces: <NEW_LINE> <INDENT> self.gfaces[i] = np.append(self.faces[i][:, :-1], self.faces[i]... | Update for the kmz file.
Returns
-------
None. | 625941d1097d151d1a222ff2 |
def CCOMB(vectors): <NEW_LINE> <INDENT> return (COMP([ SCALARVECTPROD,CONS([ COMP([ DIV, CONS([K(1),LEN]) ]), VECTSUM ]) ]))(vectors) | To create the convex combination of a list of vectors.
Each vector is given as a list of coordinates.
Return a vector. | 625941d126238365f5f0f008 |
def _fmt_score(score): <NEW_LINE> <INDENT> if score is None: <NEW_LINE> <INDENT> return u'0 (N/A)' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return u'{:.4}'.format(100. * score) | Float -> String | 625941d115baa723493c410f |
def deviceConnectionGetTypes(): <NEW_LINE> <INDENT> return _AriaPy.Aria_deviceConnectionGetTypes() | deviceConnectionGetTypes() -> char | 625941d1a934411ee375182d |
def set_logger_verbose(logger): <NEW_LINE> <INDENT> set_logger_level(logging.DEBUG, logger) | Set Logger to verbose level.
API Documentation
:param logger: Logger for which the level should be specified.
:type logger: :class:`logging.Logger` | 625941d19f2886367277aa26 |
def show_layers(self, redraw=True): <NEW_LINE> <INDENT> if len(self.layers) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for layer in self.layers: <NEW_LINE> <INDENT> self._show_layer(layer, redraw=redraw) | show available layers | 625941d17c178a314d6ef5fa |
def correlation_pass_1ch(uncorrelated_samples, term, delta, weight, correlation_samples): <NEW_LINE> <INDENT> if term == 18: <NEW_LINE> <INDENT> assert(len(correlation_samples) == 2) <NEW_LINE> uncorrelated = ([correlation_samples[1], correlation_samples[0]] + uncorrelated_samples) <NEW_LINE> correlated = [] <NEW_LINE>... | given a list of uncorrelated_samples[s]
term, delta and weight ints
and a list of correlation_samples[s] ints
returns a (correlated[s], weight, samples[s]) tuple
containing correlated samples and updated weight/samples | 625941d1adb09d7d5db6c929 |
def get_metadata_statement(self, json_ms, cls=MetadataStatement, context=''): <NEW_LINE> <INDENT> logger.debug('Incoming metadata statement: {}'.format(json_ms)) <NEW_LINE> _pi = self.unpack_metadata_statement(json_ms=json_ms, cls=cls) <NEW_LINE> if not _pi.result: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> logg... | Unpack and evaluate a compound metadata statement. Goes through the
necessary three steps.
* unpack the metadata statement
* verify that the given statements are expected to be used in this context
* evaluate the metadata statements (= flatten)
:param json_ms: The metadata statement as a JSON document or a
dictio... | 625941d11f037a2d8b946397 |
def polygon_union(poly1, poly2): <NEW_LINE> <INDENT> area1 = poly1.area; <NEW_LINE> area2 = poly2.area; <NEW_LINE> area_inter = polygon_intersection(poly1, poly2) <NEW_LINE> return area1 + area2 - area_inter; | Calculate the area of the union of two polygons
Parameters
poly1 : a polygon (shapely.geometry.polygon.Polygon object)
poly2 : a polygon (shapely.geometry.polygon.Polygon object)
Returns
area_inter: the area of union of the two given polygons, a scalar | 625941d1d99f1b3c44c67727 |
def have_compiler(): <NEW_LINE> <INDENT> compiler = customized_ccompiler() <NEW_LINE> try: <NEW_LINE> <INDENT> cmd = compiler.compiler <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not compiler.initialized: <NEW_LINE> <INDENT> compiler.initialize() <NEW_LINE> <DEDENT> <DEDEN... | Return True if there appears to be an executable compiler
| 625941d150812a4eaa59c4ba |
def p_meta_classifiers_stmt_indent(p): <NEW_LINE> <INDENT> p[0] = Node("classifiers", children=[p[5]]) | meta_classifiers_stmt : CLASSIFIERS_ID COLON NEWLINE INDENT classifiers_list DEDENT
| 625941d192d797404e304324 |
def _check_strings(self, expected, actual): <NEW_LINE> <INDENT> if expected != actual: <NEW_LINE> <INDENT> self._write_python_string('/tmp/binman.expected', expected) <NEW_LINE> self._write_python_string('/tmp/binman.actual', actual) <NEW_LINE> print('Failures written to /tmp/binman.{expected,actual}') <NEW_LINE> <DEDE... | Check that a string matches its expected value
If the strings do not match, they are written to the /tmp directory in
the same Python format as is used here in the test. This allows for
easy comparison and update of the tests.
Args:
expected (str): Expected string
actual (str): Actual string | 625941d14d74a7450ccd435d |
def mathOperation(x, y, f = add): <NEW_LINE> <INDENT> return f(x, y) | This function takes two input parameters called x and y.
The third input parameter is another function.
When executed, f(x,y) is calculated. As f defaults to add (default argument), the default return
value is x + y. Otherwise it depends on what function f is provided.
Note: The parameter "f" is set to "add" without o... | 625941d18da39b475bd6510f |
def __del__(self): <NEW_LINE> <INDENT> type(self).number_of_instances -= 1 <NEW_LINE> print("Bye rectangle...") | delete and instance
| 625941d17cff6e4e81117b1f |
def init_indexes(self, remote_peer_id): <NEW_LINE> <INDENT> self._next_index[remote_peer_id] = self._log.last_index() + 1 <NEW_LINE> self._match_index[remote_peer_id] = 0 | Initialize next_index and match_index of a remote peer.
:param remote_peer_id: The id of the remote peer.
:type remote_peer_id: six.binary_type | 625941d110dbd63aa1bd2d3e |
def create_right_frame(self): <NEW_LINE> <INDENT> self.frame_right = tk.Frame(root, bg="white") <NEW_LINE> self.frame_right.place(relheight=1, relwidth=.2, relx=0.8) <NEW_LINE> self.frame_right.grid_columnconfigure(0, weight=1) <NEW_LINE> self.frame_right.grid_rowconfigure(0, weight=1) <NEW_LINE> self.add_widgets_to_ri... | This function creates panel which allows you to control pod.
:return: None | 625941d14a966d76dd5511aa |
def Tag(arg, arg2=None): <NEW_LINE> <INDENT> if arg2 is not None: <NEW_LINE> <INDENT> arg = (arg, arg2) <NEW_LINE> <DEDENT> if isinstance(arg, (tuple, list)): <NEW_LINE> <INDENT> if len(arg) != 2: <NEW_LINE> <INDENT> raise ValueError("Tag must be an int or a 2-tuple") <NEW_LINE> <DEDENT> arg_types = set([type(arg[0]), ... | Create a Tag.
General function for creating a Tag in any of the standard forms:
* Tag(0x00100015)
* Tag('0x00100015')
* Tag((0x10, 0x50))
* Tag(('0x10', '0x50'))
* Tag(0x0010, 0x0015)
* Tag(0x10, 0x15)
* Tag(2341, 0x10)
* Tag('0xFE', '0x0010')
Parameters
----------
arg : int or str or 2-tuple/list
If int or str,... | 625941d194891a1f4081bc44 |
def draw_layer(screen, layer): <NEW_LINE> <INDENT> for cell in layer: <NEW_LINE> <INDENT> draw_cell(screen, cell) | Redraw an entire layer. Used for peeking or when changing layers | 625941d107d97122c4178a27 |
def parse(self, filename): <NEW_LINE> <INDENT> BlockParser.reset() <NEW_LINE> with open(filename, 'r') as f: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> block = BlockParser.next_block(filename, f) <NEW_LINE> if block is None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if block: <NEW... | Parses a single file, reading in all available documentation blocks.
:param filename: Name of the file to document.
:returns: Reference to the DocBuilder for chaining. | 625941d123849d37ff7b3229 |
def __init__(self, icebin_in, topo_in): <NEW_LINE> <INDENT> self.icebin_in = icebin_in <NEW_LINE> self.topo_in = topo_in <NEW_LINE> self.read_icebin_in(icebin_in) <NEW_LINE> self.setup_segments() | Args:
topo_in:
Name of original ModelE TOPO file
icebin_in:
Name of IceBin input file
stieglitz:
If True, generate initial conditions for Stieglitz model | 625941d1cb5e8a47e48b7c43 |
def mergeTwoFiles(file1, file2, out_name): <NEW_LINE> <INDENT> with open(file1, 'r') as first_file: <NEW_LINE> <INDENT> with open(file2, 'r') as second_file: <NEW_LINE> <INDENT> with open(out_name, 'w', newline = '') as output_file: <NEW_LINE> <INDENT> reader1, reader2 = csv.reader(first_file), csv.reader(second_file) ... | Function that takes in two file name strings and and output file name string, and combines the two input files in increasing
order according to its 10-th cell | 625941d17cff6e4e81117b20 |
def custom_remove(input_list, value): <NEW_LINE> <INDENT> index = 0 <NEW_LINE> count = 0 <NEW_LINE> initial_list = input_list[:] <NEW_LINE> for item in input_list: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> for i in range(count): <NEW_LINE> <INDENT> if input_list[i]== value: <NEW_LINE> <INDENT> index = i <NEW_L... | Remove the first item of the value in list.
The function custom_remove(input_list, value) should have the same
functionality as input_list.remove(value) where the first item of
the value specified is removed and the function returns nothing.
For example:
>>> notes = ['Do', 'Re', 'Mi', 'Fa', 'So', 'La', 'Ti', 'Do... | 625941d16e29344779a627ab |
def get_or_create(self, worksheet): <NEW_LINE> <INDENT> if worksheet not in self.kernels: <NEW_LINE> <INDENT> self.lock.acquire() <NEW_LINE> self.kernels[worksheet] = KernelController(self.kernel_dir) <NEW_LINE> self.lock.release() <NEW_LINE> <DEDENT> return self.kernels[worksheet] | Return existing kernels and create nonexistent ones. | 625941d14e4d5625662d4571 |
def whitewash_node_data(node, path="", channel_data={}): <NEW_LINE> <INDENT> kind = node.get("kind", None) <NEW_LINE> if not kind: <NEW_LINE> <INDENT> return node <NEW_LINE> <DEDENT> if kind in channel_data["attribute_whitelists"]: <NEW_LINE> <INDENT> for key in node.keys(): <NEW_LINE> <INDENT> if (key not in channel_d... | Utility function to convert nodes into the format used by KA Lite.
Extracted from other functions so as to be reused by both the denormed
and fully inflated exercise and video nodes. | 625941d13cc13d1c6d3c7514 |
def is_purchase_permitted(self, stockrecord, user=None, quantity=1, product=None): <NEW_LINE> <INDENT> product = product or stockrecord.product <NEW_LINE> if not self.is_available_to_buy(stockrecord): <NEW_LINE> <INDENT> return False, _("'%s' is not available to purchase") % product.title <NEW_LINE> <DEDENT> max_qty = ... | Test whether a particular purchase is possible (is a user buying a
given quantity of the product) | 625941d1eab8aa0e5d26dcf2 |
def post(self): <NEW_LINE> <INDENT> input_username = self.request.get("username") <NEW_LINE> input_password = self.request.get("password") <NEW_LINE> params = dict(username=input_username) <NEW_LINE> error = False <NEW_LINE> if not input_username: <NEW_LINE> <INDENT> params["invalid_username"] = "Username must be fille... | POST method for the /login action.
Verifies the user's input, check if an user exists with the
credentials provided and redirects to the welcome page if yes,
stay in the same page and show errors if no. | 625941d173bcbd0ca4b2c210 |
def test_div(self): <NEW_LINE> <INDENT> fraction1 = Fraction(3, 5) <NEW_LINE> fraction2 = Fraction(1, 5) <NEW_LINE> fraction3 = Fraction(-1, 10) <NEW_LINE> self.assertTrue((fraction1 / fraction2) == Fraction(15, 5)) <NEW_LINE> self.assertTrue((fraction2 / fraction3) == Fraction(10, -5)) <NEW_LINE> self.assertTrue((frac... | test fraction substraction | 625941d1e1aae11d1e749e52 |
def testSingleton(self): <NEW_LINE> <INDENT> self.assertTrue(self.reg is synreg.ExtensionRegister()) | Test that the syntax register is a singleton | 625941d14f88993c3716c201 |
def atten(self, attenuation): <NEW_LINE> <INDENT> pass | This method allows for the setting of the amount of attenuation on the input of the ADC. This allows for a wider possible input voltage range, at the cost of accuracy (the same number of bits now represents a wider range).
The possible attenuation options are:
ADC.ATTN_0DB: 0dB attenuation, gives a maximum input volta... | 625941d13c8af77a43ae393b |
def world_to_local(self, v): <NEW_LINE> <INDENT> return cpffi.cpBodyWorld2Local(self._body, v) | Convert world space coordinates to body local coordinates
:Parameters:
v : (x,y) or `Vec2d`
Vector in world space coordinates | 625941d1baa26c4b54cb12b9 |
def draw_img_preds(img, depth_pred, seg_pred, uncertainty_threshold=0.0, apply_depth_mask=False): <NEW_LINE> <INDENT> plt.figure(0, figsize=(8, 6)) <NEW_LINE> plt.subplot(2, 3, 1) <NEW_LINE> plt.title('RGB') <NEW_LINE> plt.imshow(img) <NEW_LINE> plt.gca().axes.get_yaxis().set_ticks([]) <NEW_LINE> plt.gca().axes.get_xax... | Display the input RGB image, and the corresponding depth and segmentation images next to each other. | 625941d1283ffb24f3c55a9a |
def merge(self, ball): <NEW_LINE> <INDENT> merged = False <NEW_LINE> if not self.fast_collision_check(ball): <NEW_LINE> <INDENT> merged = False <NEW_LINE> return merged <NEW_LINE> <DEDENT> dposition = self.displacement(ball.position) <NEW_LINE> distance2 = dposition.dot(dposition) <NEW_LINE> dspeed = self.speed - ball.... | Handles particle merge (inelastic collision)
Args:
ball (Particle): particle to check collision with
Returns:
boolean: True when merge occured | 625941d17d847024c06be457 |
def test_simple(self): <NEW_LINE> <INDENT> eq_(''.join(build_lines('hello', [], [(0, 3, 'a'), (3, 5, 'b')])), u'<span class="a">hel</span><span class="b">lo</span>') | Sanity-check build_lines, which ties the whole shootin' match
together. | 625941d1d8ef3951e32436d8 |
def send_yut_playlist(self): <NEW_LINE> <INDENT> payload = { 'tc': 'yut_playlist', 'req': self._req } <NEW_LINE> self.send(payload) | Send a youtube playlist request. | 625941d11d351010ab855cb6 |
def emit(self, record): <NEW_LINE> <INDENT> trace = traceback.format_exc(record.__dict__['exc_info']) if record.__dict__['exc_info'] else None <NEW_LINE> extra = json.dumps(record.__dict__['extra']) if "extra" in record.__dict__ else None <NEW_LINE> log = Log( logger=record.__dict__['name'], level=record.__dict__['leve... | Catch the log entry, grab any traceback data and any extra data if provided. | 625941d1d10714528d5ffe7f |
def done(self, ud, d): <NEW_LINE> <INDENT> def _handle(m, ud, d): <NEW_LINE> <INDENT> return m.done(ud, d) <NEW_LINE> <DEDENT> return all(self._foreach_proxy_method(ud, _handle)) | Is the download done ? | 625941d10fa83653e4657155 |
def plot_disp(data, true_hadroness=False): <NEW_LINE> <INDENT> hadro = "reco_type" <NEW_LINE> if true_hadroness: <NEW_LINE> <INDENT> hadro = "mc_type" <NEW_LINE> <DEDENT> gammas = data[data[hadro] == 0] <NEW_LINE> plt.subplot(221) <NEW_LINE> reco_disp_norm = np.sqrt(gammas['reco_disp_dx'] ** 2 + gammas['reco_disp_dy'] ... | Plot the performance of reconstructed position
Parameters:
-----------
data: pandas DataFrame
true_hadroness: boolean
True: True gammas and proton events are plotted (they are separated
using true hadroness).
False: Gammas and protons are separated using reconstructed
hadroness (hadro_rec) | 625941d15fc7496912cc3b18 |
def analytical_solution(self, x0, t): <NEW_LINE> <INDENT> m = self.m <NEW_LINE> c = self.c <NEW_LINE> k = self.k <NEW_LINE> delta = (c**2 - 4 * m * k)**0.5 <NEW_LINE> x1 = -c - delta / (2 * m) <NEW_LINE> x2 = -c + delta / (2 * m) <NEW_LINE> raise NotImplementedError | return analytical solution when Fext = 0 | 625941d1f9cc0f698b140795 |
def peek(self) -> int: <NEW_LINE> <INDENT> while self.push_stack: <NEW_LINE> <INDENT> self.pop_stack.append(self.push_stack.pop()) <NEW_LINE> <DEDENT> return self.pop_stack[-1] | Get the front element. | 625941d16fb2d068a760f239 |
def timecodeToFrame(t, fps): <NEW_LINE> <INDENT> if isinstance(t, int) or isinstance(t, float): <NEW_LINE> <INDENT> return int(t * fps) <NEW_LINE> <DEDENT> if not isinstance(t, str): <NEW_LINE> <INDENT> raise TypeError("expected a timecode of type int, float, or str, but instead received a {}".format(type(t))) <NEW_LIN... | timecodeToFrame(t, fps)
Converts the timecode `t` to an integer frame number.
The timecode can either be an int/float number of seconds, or a string "[[h:]m:]s". | 625941d1c432627299f04de1 |
def __init__(self, host, login, password): <NEW_LINE> <INDENT> self.host = host <NEW_LINE> self.login = login <NEW_LINE> self.password = password <NEW_LINE> self.ftp = None <NEW_LINE> self.dt = None <NEW_LINE> self.connect() <NEW_LINE> self.update_time_difference() | Constructor
Args:
host: FTP server host
login: FTP login
password: FTP password | 625941d1b545ff76a8913fb0 |
def create_user_from_facebook_user_info(user_info): <NEW_LINE> <INDENT> facebook_user_id = user_info['id'] <NEW_LINE> first_name = user_info['first_name'] <NEW_LINE> last_name = user_info['last_name'] <NEW_LINE> url_img_profile = user_info['picture']['data']['url'] <NEW_LINE> return User.objects.get_or_create( username... | Facebook GraphAPI의 'User'에 해당하는 응답인 user_info로부터
id, first_name, last_name, picture항목을 사용해서
Django의 User를 가져오거나 없는경우 새로 만듬 (get_or_create)
:param user_info: Facebook GraphAPI - User의 응답
:return: get_or_create의 결과 tuple (User instance, Bool(created)) | 625941d1eab8aa0e5d26dcf3 |
def update_transform(self): <NEW_LINE> <INDENT> if self.low_rank is False: <NEW_LINE> <INDENT> A = np.dot(np.diag(self.P1), self.G) + self.alpha * self.sigma2 * np.eye(self.M) <NEW_LINE> B = self.PX - np.dot(np.diag(self.P1), self.Y) <NEW_LINE> self.W = np.linalg.solve(A, B) <NEW_LINE> <DEDENT> elif self... | Calculate a new estimate of the deformable transformation.
See Eq. 22 of https://arxiv.org/pdf/0905.2635.pdf. | 625941d131939e2706e4d004 |
def __init__(self, address, default_port=8086): <NEW_LINE> <INDENT> host = address.split(':') <NEW_LINE> try: <NEW_LINE> <INDENT> port = host[1] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> port = default_port <NEW_LINE> <DEDENT> self.name = address <NEW_LINE> self.url = "http://%s:%s" % (host[0], port) <... | Initialize object | 625941d1e8904600ed9f20c9 |
def clear() -> None: <NEW_LINE> <INDENT> if os.name == 'nt': <NEW_LINE> <INDENT> _ = os.system('cls') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _ = os.system('clear') | Clears the console.
| 625941d1b57a9660fec33a1f |
def get_landmarks(self,im,fname,n=2): <NEW_LINE> <INDENT> rects = self.detector(im, 1) <NEW_LINE> if len(rects) >=5: <NEW_LINE> <INDENT> raise TooManyFaces('Too many faces in '+fname) <NEW_LINE> <DEDENT> if len(rects) <2: <NEW_LINE> <INDENT> raise NoFace('No enough face in' +fname) <NEW_LINE> <DEDENT> return [np.matrix... | 人脸定位和特征提取,定位到两张及以上脸或者没有人脸将抛出异常
im:
照片的numpy数组
fname:
照片名字的字符串
返回值:
人脸特征(x,y)坐标的矩阵 | 625941d1f7d966606f6aa1a0 |
def fetch(self, url, listener, chunk_size_bytes=None, timeout_secs=None): <NEW_LINE> <INDENT> chunk_size_bytes = chunk_size_bytes or 10 * 1024 <NEW_LINE> timeout_secs = timeout_secs or 1.0 <NEW_LINE> if not isinstance(listener, self.Listener): <NEW_LINE> <INDENT> raise ValueError('listener must be a Listener instance, ... | Fetches data from the given URL notifying listener of all lifecycle events.
:param string url: the url to GET data from
:param listener: the listener to notify of all download lifecycle events
:param chunk_size_bytes: the chunk size to use for buffering data, 10 KB by default
:param timeout_secs: the maximum time to w... | 625941d1be383301e01b561f |
def _primary_edge( node_to_tm, primary_to_tol, edge, edge_rate, fg_track, bg_tracks, chunk_tree, chunks, node_to_chunk, chunk_edge_to_event): <NEW_LINE> <INDENT> va, vb = edge <NEW_LINE> all_states = set(primary_to_tol) <NEW_LINE> tm = node_to_tm[va] <NEW_LINE> chunk = node_to_chunk[va] <NEW_LINE> bg_name_to_state = {}... | A helper function to build the codon process chunk tree. | 625941d115fb5d323cde0cac |
def dataChanged(self): <NEW_LINE> <INDENT> return False | Check if data has changed since the last build of the Frame.
Always returns False. Should be re-implmented in subclass if an actual
test is needed. | 625941d13539df3088e2e4e6 |
def _handle_offset_response(self, partition, future, response): <NEW_LINE> <INDENT> topic, partition_info = response.topics[0] <NEW_LINE> assert len(response.topics) == 1 and len(partition_info) == 1, ( 'OffsetResponse should only be for a single topic-partition') <NEW_LINE> part, error_code, offsets = partition_info[0... | Callback for the response of the list offset call above.
Arguments:
partition (TopicPartition): The partition that was fetched
future (Future): the future to update based on response
response (OffsetResponse): response from the server
Raises:
AssertionError: if response does not match partition | 625941d13eb6a72ae02ec67a |
def test_cross_ou_journal_entry(self): <NEW_LINE> <INDENT> self.company.write({ 'inter_ou_clearing_account_id': self.inter_ou_account_id.id, }) <NEW_LINE> self.acc_move_model = self.env['account.move'] <NEW_LINE> self.journal_model = self.env['account.journal'] <NEW_LINE> journal_ids = self.journal_model.search([('code... | Test balance of cross OU journal entries.
Test that when I create a manual journal entry with multiple
operating units, new cross-operating unit entries are created
automatically whent the journal entry is posted, ensuring that each
OU is self-balanced. | 625941d1f9cc0f698b140796 |
def test_ndec(mainw, extratim=0): <NEW_LINE> <INDENT> path = os.path.join(mainw.testspath, "selftests", "ndec.plt") <NEW_LINE> msg = mainw.loadFile(path) <NEW_LINE> if msg: <NEW_LINE> <INDENT> return 1, msg <NEW_LINE> <DEDENT> subw = mainw.getCurrentSubWindow() <NEW_LINE> if subw is None: <NEW_LINE> <INDENT> return 1, ... | Test the 'ndec' script command.
:param mainw: the application MainWindow
:return: a tuple (err, msg).
err = 0 if success, 1 if failure and -1 if interrupted by user.
msg = contains an error message ("" if not error) | 625941d130c21e258bdfa639 |
def _prepare_queues(self): <NEW_LINE> <INDENT> [self._create_tag_queue(miner) for miner in Config.ARCHITECTURE['tag_miners']] <NEW_LINE> self.channel.exchange_declare(exchange='tag_miners_ex', type='fanout') <NEW_LINE> self.vec_asm_queues = [] <NEW_LINE> self.current_vec_asm_queue = 0 <NEW_LINE> [self._create_asm_queue... | For each tag miner, we create a queue,
base on the architecture config | 625941d145492302aab5e45f |
def is_surjective(self): <NEW_LINE> <INDENT> return self.codomain() == self.image() | Return ``True`` if and only if ``self`` is surjective.
EXAMPLES::
sage: S = SimplicialComplex([(0,1,2)], is_mutable=False)
sage: S
Simplicial complex with vertex set (0, 1, 2) and facets {(0, 1, 2)}
sage: T = SimplicialComplex([(0,1)], is_mutable=False)
sage: T
Simplicial complex with vertex s... | 625941d101c39578d7e74fd6 |
@app.route('/sso/callback') <NEW_LINE> def callback(): <NEW_LINE> <INDENT> code = request.args.get('code') <NEW_LINE> token = request.args.get('state') <NEW_LINE> pop = cache.pop(token, None) <NEW_LINE> pyfa_state = session['pyfa-state'] <NEW_LINE> pyfa_redirect = session['pyfa-redirect'] <NEW_LINE> sess_token = sessio... | This is where the user comes after he logged in SSO | 625941d18c0ade5d55d3eb56 |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend_shop.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you... | Run administrative tasks. | 625941d17b180e01f3dc4997 |
@login_required(login_url='login') <NEW_LINE> def join_game(request): <NEW_LINE> <INDENT> min_id = (Game.objects. filter(status=GameStatus.CREATED). exclude(cat_user=request.user). aggregate(Min('id'))) <NEW_LINE> if min_id['id__min']: <NEW_LINE> <INDENT> result = (Game.objects. filter(id=min_id['id__min'])) <NEW_LINE>... | Joins to the CREATED game where you are not playing as cat with lower id.
Args:
request (HttpRequest): Metadata about the requested page
Returns:
render(...) (HttpResponse): Template information
Author: | 625941d1435de62698dfdde8 |
def alias_by_address(self, address): <NEW_LINE> <INDENT> return self.request('get', '/alias/by-address/{}'.format(address)) | Get alias by address
:param address: acryl address
:return:
:rtype: AcrylClientResponse | 625941d12c8b7c6e89b3595b |
def is_int(s): <NEW_LINE> <INDENT> return INT_RE.match(str(s)) is not None | String contains integer | 625941d17047854f462a15a4 |
def __init__(self, text='', color=(200,200,200), html=None, anchor=(0,0), border=None, fill=None): <NEW_LINE> <INDENT> UIGraphicsItem.__init__(self) <NEW_LINE> self.textItem = QtGui.QGraphicsTextItem() <NEW_LINE> self.lastTransform = None <NEW_LINE> self._bounds = QtCore.QRectF() <NEW_LINE> if html is None: <NEW_LINE> ... | Arguments:
*text* The text to display
*color* The color of the text (any format accepted by pg.mkColor)
*html* If specified, this overrides both *text* and *color*
*anchor* A QPointF or (x,y) sequence indicating what region of the text box will
be anchored to the item's position. A value of (0,0) sets t... | 625941d11f5feb6acb0c4ceb |
def GetPath(self, item_name, *__args): <NEW_LINE> <INDENT> pass | GetPath(self: GH_IReader, item_name: str, item_index: int, basePath: str) -> Array[str]
Gets the value of the item with the specified name and index.
Name comparison is
not case-sensitive.
item_name: Name of item to retrieve.
item_index: Index of item to retrieve.
basePath... | 625941d13617ad0b5ed68093 |
def showFileDialog(self): <NEW_LINE> <INDENT> filename = QtGui.QFileDialog.getOpenFileName( self, 'Open file', self.dirIn) <NEW_LINE> filename = str(filename) <NEW_LINE> if filename == '': <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self._openfile() | Open a dialog box to choose file. | 625941d1d58c6744b4257dfa |
def countAndSay(self, n): <NEW_LINE> <INDENT> if n == 1: <NEW_LINE> <INDENT> return '1' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s = self.countAndSay(n-1) + '1' <NEW_LINE> return s | :type n: int
:rtype: str | 625941d1fbf16365ca6f6362 |
def get_time(): <NEW_LINE> <INDENT> return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') | 获取当前时间
=> 格式: '2017-12-13 16:32:30' | 625941d1925a0f43d254a013 |
def index(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> context = {u'model': model, u'session': model.Session, u'user': g.user, u'auth_user_obj': g.userobj} <NEW_LINE> data_dict = {u'q': u'*:*', u'facet.field': h.facets(), u'rows': 4, u'start': 0, u'sort': u'view_recent desc', u'fq': u'capacity:"public"'} <NEW_LINE> ... | display home page | 625941d138b623060ff0af89 |
def seq_to_satn(seq, im=None): <NEW_LINE> <INDENT> seq = np.copy(seq).astype(int) <NEW_LINE> if im is None: <NEW_LINE> <INDENT> solid_mask = seq == 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> solid_mask = im == 0 <NEW_LINE> <DEDENT> uninvaded_mask = seq == -1 <NEW_LINE> seq[seq <= 0] = 0 <NEW_LINE> seq = rankdata(s... | Converts an image of invasion sequence values to saturation values.
Parameters
----------
seq : ndarray
The image containing invasion sequence values in each voxel. Solid
should be indicated as 0's and uninvaded voxels as -1.
im : ndarray, optional
A binary image of the porous media, with ``True`` indicat... | 625941d1ec188e330fd5a939 |
def save_obj(base_mapper, states, uowtransaction, single=False): <NEW_LINE> <INDENT> if not single and not base_mapper.batch: <NEW_LINE> <INDENT> for state in _sort_states(states): <NEW_LINE> <INDENT> save_obj(base_mapper, [state], uowtransaction, single=True) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> states_to_in... | Issue ``INSERT`` and/or ``UPDATE`` statements for a list
of objects.
This is called within the context of a UOWTransaction during a
flush operation, given a list of states to be flushed. The
base mapper in an inheritance hierarchy handles the inserts/
updates for all descendant mappers. | 625941d1507cdc57c6306e78 |
def toDatabase(self, sender, receiver, message): <NEW_LINE> <INDENT> m = Message( sender=sender, receiver=receiver, message=message ) <NEW_LINE> m.save() | Emulates email sending. "Emails" are just stored as a database record
@param sender: the sender
@type sender: User object
@param receiver: the receiver
@type receiver: User object
@param message: the message | 625941d14c3428357757c4c3 |
def check_events(settings, robot, buttons, next_button, mqtt): <NEW_LINE> <INDENT> for event in pygame.event.get(): <NEW_LINE> <INDENT> if event.type == pygame.QUIT: <NEW_LINE> <INDENT> sys.exit() <NEW_LINE> <DEDENT> elif event.type == pygame.KEYDOWN: <NEW_LINE> <INDENT> if event.key == pygame.K_q: <NEW_LINE> <INDENT> ... | Respond to keypresses and mouse events. | 625941d19c8ee82313fbb911 |
def askForFile(self): <NEW_LINE> <INDENT> dlg = QFileDialog(caption="Select File",filter = "ICLoad Files (*.txt *.csv *tsv *xlsx);;Text files (*.txt *.csv *tsv);;Excel files (*.xlsx)") <NEW_LINE> dlg.setFileMode(QFileDialog.ExistingFiles) <NEW_LINE> if dlg.exec_(): <NEW_LINE> <INDENT> filenames = dlg.selectedFiles() <N... | Get File Names | 625941d191af0d3eaac9bbb5 |
def create_note_with_melodic_interval(self, melodic_interval): <NEW_LINE> <INDENT> new_note_int = melodic_interval.create_note_int(self.note_int) <NEW_LINE> assert new_note_int >= 0 <NEW_LINE> return Notes(new_note_int) | Creates note based on the MelodicInterval.
Parameters
----------
melodic_interval : MelodicInterval
Returns
-------
Notes | 625941d1a934411ee375182f |
def adjust_heap(self, nums, startpos, endpos): <NEW_LINE> <INDENT> pos = startpos <NEW_LINE> childpos = pos * 2 + 1 <NEW_LINE> if childpos < endpos: <NEW_LINE> <INDENT> rightpos = childpos + 1 <NEW_LINE> if rightpos < endpos and nums[rightpos] > nums[childpos]: <NEW_LINE> <INDENT> childpos = rightpos <NEW_LINE> <DEDENT... | [startpos, endpos]为调整的范围
对该范围内的元素调整,使它们满足堆的性质 | 625941d1d99f1b3c44c67728 |
def test_01_02_thicken_negative(self): <NEW_LINE> <INDENT> image = np.array( [[1, 1, 0, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0], [1, 1, 0, 1]], bool ) <NEW_LINE> result = morph.thicken(image) <NEW_LINE> self.assertTrue(np.all(result == image)) | Test patterns that should not thicken | 625941d18da39b475bd65110 |
def run_remove_duplicates_suite(remove_duplicates_function): <NEW_LINE> <INDENT> suite = poc_simpletest.TestSuite() <NEW_LINE> suite.run_test(remove_duplicates_function([]), [], "remove dups []") <NEW_LINE> suite.run_test(remove_duplicates_function([1]), [1], "remove dups [1]") <NEW_LINE> suite.run_test(remove_duplicat... | Some informal testing code for remove_duplicates_function | 625941d1462c4b4f79d1d86c |
def clientPollingInterval(self): <NEW_LINE> <INDENT> return random.choice(range(3, 8)) | Set the interval for the client polling.
You should always make it a little random to avoid synchronization. | 625941d150812a4eaa59c4bc |
def pauseProducing(self): <NEW_LINE> <INDENT> self.keepProducing = False | Permet d'arrêter le dépilement des messages. | 625941d17c178a314d6ef5fd |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <... | Returns the model properties as a dict | 625941d194891a1f4081bc45 |
def test_score_is_unique(self): <NEW_LINE> <INDENT> item1, item2 = OrderItem.objects.all()[:2] <NEW_LINE> PQueue.objects.create(item=item1) <NEW_LINE> pqueue = PQueue.objects.create(item=item2) <NEW_LINE> with self.assertRaises(IntegrityError): <NEW_LINE> <INDENT> pqueue.score = 1000 <NEW_LINE> pqueue.save() | Two elements cannot share the same score. | 625941d126238365f5f0f00b |
def get_tenant_subscription_usage_using_get_with_http_info(self, **kwargs): <NEW_LINE> <INDENT> all_params = [] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_LINE> pa... | getTenantSubscriptionUsage # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_tenant_subscription_usage_using_get_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: Subscripti... | 625941d199fddb7c1c9de52c |
def _has_unrelated(self, name, path): <NEW_LINE> <INDENT> size_limit = get_size(self.file) / 10.0 <NEW_LINE> for file in files(path, types=self.TYPES): <NEW_LINE> <INDENT> if file.file == self.file: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> name_ = file.get_file_info().get('display_name') <NEW_LINE> if not name_... | Check unrelated media in the given directory.
| 625941d1c432627299f04de2 |
def display_friends(self): <NEW_LINE> <INDENT> self.user_max_label_text.set("Max Friends (0=No Limit)") <NEW_LINE> self.user_entry.grid(row=0, column=3, sticky=tk.W, pady=10) <NEW_LINE> self.user_label.grid(row=0, column=2, sticky=tk.E) <NEW_LINE> self.user_max_entry.grid(row=1, column=3, sticky=tk.W, pady=10) <NEW_LIN... | Displays friends archive specific portions of the GUI | 625941d194891a1f4081bc46 |
def get_cols(self, lines): <NEW_LINE> <INDENT> header_lines = self.process_lines(lines) <NEW_LINE> header_vals = [vals for vals in self.splitter(header_lines)] <NEW_LINE> if len(header_vals) == 0: <NEW_LINE> <INDENT> raise ValueError('At least one header line beginning and ending with ' 'delimiter required') <NEW_LINE>... | Initialize the header Column objects from the table ``lines``.
Based on the previously set Header attributes find or create the column names.
Sets ``self.cols`` with the list of Columns. This list only includes the actual
requested columns after filtering by the include_names and exclude_names
attributes. See ``self... | 625941d130dc7b7665901b02 |
def build_thredds_catalog_fragment(data_root, user, deployment, template_dir): <NEW_LINE> <INDENT> raise NotImplementedError("build_thredds_catalog fragment has been removed " "in favor of utilizing a THREDDS datasetScan, " "see glider_dac/thredds/templates/catalog.xml") | Builds a thredds catalog entry | 625941d1004d5f362079a4ce |
def save(self): <NEW_LINE> <INDENT> self.common.log("Settings", "save") <NEW_LINE> open(self.filename, "w").write(json.dumps(self._settings, indent=2)) <NEW_LINE> self.common.log("Settings", "save", f"Settings saved in {self.filename}") | Save settings to file. | 625941d191f36d47f21ac68f |
def __eq__(self,poly): <NEW_LINE> <INDENT> if len(self) == len(poly): <NEW_LINE> <INDENT> if all([x == y for x,y in zip(self.coef,poly.coef)]): <NEW_LINE> <INDENT> if self.modulus == poly.modulus: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False | Check if two polynomials have the same coefficient and are over the same field | 625941d1009cb60464c6354d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.