code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def label_from_instance(self, obj): <NEW_LINE> <INDENT> desc = smart_unicode(obj) <NEW_LINE> ident = smart_unicode(self.to_native(obj.pk)) <NEW_LINE> if desc == ident: <NEW_LINE> <INDENT> return desc <NEW_LINE> <DEDENT> return "%s - %s" % (desc, ident)
Return a readable representation for use with eg. select widgets.
625941c6d164cc6175782d70
def polyfit(self, deg=4): <NEW_LINE> <INDENT> self.polydeg = deg <NEW_LINE> n_row = self.imshape[0] <NEW_LINE> nap = self.nap <NEW_LINE> ap_col_interp = np.arange(0, n_row, dtype=int) <NEW_LINE> ap_upper_interp = [] <NEW_LINE> ap_lower_interp = [] <NEW_LINE> ap_center_interp = [] <NEW_LINE> ap_upper_chebcoef = [] <NEW_...
fit using chebyshev polynomial for adopted apertures
625941c68c3a8732951583dc
def set_viewport_background(): <NEW_LINE> <INDENT> pass
Set current movie clip as a camera background in 3D view-port (works only when a 3D view-port is visible)
625941c6462c4b4f79d1d6f3
def print_lib_config(heading, lib_config): <NEW_LINE> <INDENT> print(' %s' % heading) <NEW_LINE> if len(lib_config) == 0: <NEW_LINE> <INDENT> print(' -') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for key, value in sorted(lib_config.items()): <NEW_LINE> <INDENT> if len(value) > 0: <NEW_LINE> <INDENT> print(' ...
Print (partial) lib_config
625941c656b00c62f0f1467b
def try_acquire(self): <NEW_LINE> <INDENT> return stack_lock_object.StackLock.create(self.stack_id, self.engine_id)
Try to acquire a stack lock, but don't raise an ActionInProgress exception or try to steal lock.
625941c6e76e3b2f99f3a831
def print_text(font, x, y, text, screen, color=(0,0,0)): <NEW_LINE> <INDENT> imgText = font.render(text, True, color) <NEW_LINE> screen.blit(imgText, (x,y))
This will draw text at desired x,y coordinate on the given surface with given color. @param font: pygame's font object @type font: pygame.font.Font @param x: x coordinate of text starting with left most pixel @type x: int @param y: y coordinate of text starting with top most pixel @type y: int @param text: The text to...
625941c6fff4ab517eb2f45e
def hit(self,points = 1): <NEW_LINE> <INDENT> canv.coords(self.id,-10,-10,-10,-10) <NEW_LINE> self.points += points <NEW_LINE> canv.itemconfig(self.id_points, text = self.points)
Попадание шарика в цель
625941c663b5f9789fde7108
def exec_command_expecting_more(self, cmd, more_prompt="--More--", terminal_name=None): <NEW_LINE> <INDENT> return self._find_terminal( terminal_name).current_shell().exec_command_expecting_more( cmd, more_prompt)
Executes the specified command. Used for handling cases where the command output is too large and paging function is not disabled. If the execution was successful, the result of the command is returned together with the number of pages. The result of the command exceeds maximum limit of lines, therefore the '--More--...
625941c6a79ad161976cc168
def number_of_players(self): <NEW_LINE> <INDENT> return len(self.game_players)
Returns the number of players in the game.
625941c6adb09d7d5db6c7b3
def p_expression_divide(p): <NEW_LINE> <INDENT> indent() <NEW_LINE> f.write(str(p[1]) + " / " + str(p[3]) + "\n") <NEW_LINE> print ("p_expression_divide")
expression : expression DIVIDES term
625941c6d7e4931a7ee9df40
def mainloop(): <NEW_LINE> <INDENT> _run_startup() <NEW_LINE> try: <NEW_LINE> <INDENT> while not stopped.is_set(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> stopped.wait(config['thread_wait_interval']) <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> final...
This function exists for Sideboard plugins which do not run CherryPy. It runs all of the functions registered with sideboard.lib.on_startup and then waits for shutdown, at which point it runs all functions registered with sideboard.lib.on_shutdown.
625941c699cbb53fe6792c09
def _findLiveSnapshotSupport(guest): <NEW_LINE> <INDENT> features = guest.getElementsByTagName('features') <NEW_LINE> if not features: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> for feature in features[0].childNodes: <NEW_LINE> <INDENT> if feature.nodeName == 'disksnapshot': <NEW_LINE> <INDENT> value = feature...
Returns the status of the live snapshot support on the hypervisor (QEMU). param guest: the `guest' XML element of the libvirt capabilities XML Return type: None or boolean. None if libvirt does not report the live snapshot support (as in version <= 1.2.2),
625941c6a4f1c619b28b005f
def affectTokenAfterParseBeforeModifiers(self, m21Obj): <NEW_LINE> <INDENT> return m21Obj
called after the object has been acquired but before modifiers have been applied.
625941c62c8b7c6e89b357e4
def is_fields_in_dict(query_dict, *fields): <NEW_LINE> <INDENT> return all(field in query_dict.dict() for field in fields)
Return True if all field in fields are in the request_dict
625941c699cbb53fe6792c0a
def __init__(self, suppress_warning=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> dxpy._DEBUG = int(environ.get("_DX_DEBUG", 0)) <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> warn("WARNING: Expected _DX_DEBUG to be an integer, but got", environ["_DX_DEBUG"]) <NEW_LINE> dxpy._DEBUG = 0 <NEW_LINE...
:param suppress_warning: Whether to suppress the warning message for any mismatch found in the environment variables and the dx configuration file :type suppress_warning: boolean
625941c6925a0f43d2549e99
def dict(self): <NEW_LINE> <INDENT> return { 'value': self.value, 'script': to_hexstring(self.lock_script), 'script_type': self.script_type, 'public_key': to_hexstring(self.public_key), 'public_key_hash': to_hexstring(self.public_key_hash), 'address': self.address, 'output_n': self.output_n, 'spent': self.spent, }
Get transaction output information in json format :return dict: Json with amount, locking script, public key, public key hash and address
625941c645492302aab5e2e5
def __init__(self, database='dbase.db'): <NEW_LINE> <INDENT> self.connection = sqlite3.connect(database) <NEW_LINE> self.cursor = self.connection.cursor() <NEW_LINE> self.image = Image()
Подключаемся к БД и сохраняем курсор соединения
625941c63cc13d1c6d3c739e
def retrieve(self, request, pk): <NEW_LINE> <INDENT> f_request = get_object_or_404(FriendshipRequest, id=pk) <NEW_LINE> serializer = self.serializer_class(f_request) <NEW_LINE> return Response(serializer.data)
get info from the friendhsip request with pk = pk
625941c62eb69b55b151c8d1
def deserialize(value: str) -> HDNode: <NEW_LINE> <INDENT> pass
Construct a BIP0032 HD node from a base58-serialized value.
625941c67b180e01f3dc4823
def is_reference(self): <NEW_LINE> <INDENT> return CursorKind_is_ref(self)
Test if this is a reference kind.
625941c699fddb7c1c9de3b5
def __getitem__(self, key): <NEW_LINE> <INDENT> assert self.isopen <NEW_LINE> if isinstance(key, tuple): <NEW_LINE> <INDENT> base_key, track_key = key <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> base_key = key <NEW_LINE> track_key = slice(None) <NEW_LINE> <DEDENT> base_index = False <NEW_LINE> track_index = False <NE...
Return the continuous data corresponding to this bp slice :param key: key must index or slice bases, but can also index, slice, or directly specify (string or list of strings) the data tracks. :type key: <base_key>[, <track_key>] :returns: numpy.array If slice is taken over or outside a super...
625941c6187af65679ca5141
def get_bag(self, name): <NEW_LINE> <INDENT> logging.debug("Getting %s contents", name) <NEW_LINE> row = column = 0 <NEW_LINE> bag = getattr(self.player, "get_" + name)() <NEW_LINE> for i in range(len(bag)): <NEW_LINE> <INDENT> item = getattr(self.ui, name).item(row, column) <NEW_LINE> empty_item = (item is None or typ...
Return the entire contents of a given non-equipment bag as raw values.
625941c631939e2706e4ce8f
def set_APIKey(self, value): <NEW_LINE> <INDENT> super(CreateRecipientListInputSet, self)._set_input('APIKey', value)
Set the value of the APIKey input for this Choreo. ((required, string) The API Key obtained from SendGrid.)
625941c6fb3f5b602dac36b5
def __init__(self, birth_date, year, meriod, week, day): <NEW_LINE> <INDENT> self.birth_date = birth_date <NEW_LINE> self.year = year <NEW_LINE> self.meriod = meriod <NEW_LINE> self.week = week <NEW_LINE> self.day = day
Init with values.
625941c65510c4643540f40b
def add_value(value_name, value_or_fn): <NEW_LINE> <INDENT> def _inner(result): <NEW_LINE> <INDENT> value = value_or_fn <NEW_LINE> if hasattr(value, '__call__'): <NEW_LINE> <INDENT> value = value_or_fn(result) <NEW_LINE> <DEDENT> result[value_name] = value <NEW_LINE> <DEDENT> return _inner
Post-test hook which as the value or the result of evaluating function on result to the test result dict. Example usage:: @test @after_test(add_value("grade", 7)) def graded_testcase(m): ...
625941c6b7558d58953c4f3a
def removeSceneEventFilter(self, QGraphicsItem): <NEW_LINE> <INDENT> pass
removeSceneEventFilter(self, QGraphicsItem)
625941c6be8e80087fb20c68
def extract_image(img, toErode, valueX, valueY): <NEW_LINE> <INDENT> gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) <NEW_LINE> height, width = img.shape[:2] <NEW_LINE> thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, valueX, valueY) <NEW_LINE> im2, contours, hierarchy = cv2.findCon...
it will extract image in the simplest case
625941c623e79379d52ee588
def J(self, J_norm: np.ndarray): <NEW_LINE> <INDENT> n_y, n_x, _ = J_norm.shape <NEW_LINE> sigma_x = self._sigma_x.T.reshape((1, n_x, 1)) <NEW_LINE> sigma_y = self._sigma_y.reshape((n_y, 1, 1)) <NEW_LINE> return J_norm * sigma_y / sigma_x
Return denormalized Jacobian: J_norm = J_norm * sigma_y / sigma_x Parameters ---------- J_norm: np.ndarray Normalized Jacobian, shape (n_y, n_x, m) where n_y = no. of outputs n_x = no. of inputs ...
625941c66fece00bbac2d760
def genOptCodeStructFuncFile(names,variables,openof_root): <NEW_LINE> <INDENT> outstr='#ifndef STRUCTS_FUNC_SRC_H_\n' <NEW_LINE> outstr+='#define STRUCTS_FUNC_SRC_H_\n' <NEW_LINE> outstr+='\n' <NEW_LINE> for n,v in zip(names,variables): <NEW_LINE> <INDENT> outstr+='\n' <NEW_LINE> outstr+=genOptCodeSet(n,v) <NEW_LINE> o...
Method generates C++ code and writes it to struct_func_src.h. To generate the code, the genOptCodeFuncPtr, genOptCodeSet, genOptCodeFuncPtr_h function is used. :param names: List of strings containing the names of the optimization objects :param variables: List of strings containing the variable names of the optimizat...
625941c666656f66f7cbc1ce
@cli.command('hl_extractor') <NEW_LINE> @click.option('--threads', '-t', default=1, type=int) <NEW_LINE> def command_hl_extractor(threads=1): <NEW_LINE> <INDENT> hl_extractor.hl_calc.main(threads)
Compute high-level features from low-level data files.
625941c65fcc89381b1e16e1
def clone_template(): <NEW_LINE> <INDENT> CONFIG['template_source'] = mkdtemp(prefix='pl-cloud-starter-template') <NEW_LINE> print("{} Created temp directory {}".format(PREFIX, CONFIG['template_source'])) <NEW_LINE> print("{} Cloning pl-cloud-starter to temp dir".format(PREFIX)) <NEW_LINE> cwd = os.getcwd() <NEW_LINE> ...
Clone pl-cloud-starter to a temp dir
625941c6ac7a0e7691ed40f2
def remove_selected_cells(self, pivot, rowShift): <NEW_LINE> <INDENT> self.deadSelectedCells = {} <NEW_LINE> cellsByRow = order_selection_by_rows(self.canvas._selectedCells.values()) <NEW_LINE> for rowID in range(pivot, pivot+rowShift): <NEW_LINE> <INDENT> if rowID in cellsByRow: <NEW_LINE> <INDENT> for entr...
Remove the deleted items from the current selection (if applicable).
625941c694891a1f4081bacc
@login_required <NEW_LINE> def profile(request, pk): <NEW_LINE> <INDENT> profile = UserProfile.objects.get(user=pk) <NEW_LINE> if request.method == "POST": <NEW_LINE> <INDENT> pf = ProfileForm(request.POST, request.FILES, instance=profile) <NEW_LINE> if pf.is_valid(): <NEW_LINE> <INDENT> pf.save() <NEW_LINE> <DEDENT> <...
Edit user profile.
625941c621bff66bcd684977
def flush_index(self, **kwargs): <NEW_LINE> <INDENT> self._validate_kwargs('flush_index', kwargs) <NEW_LINE> return self._invoke('flush_index', timeout_millis=kwargs.get('timeout_millis'), )
Flush all pending messages in ingestion pipeline to permanent storage and make them available to search. @type timeout_millis: C{long} or C{None} @kwarg timeout_millis: timeout in milliseconds. If it is not present or it is 0, there is no timeout. @rtype: C{bool} @return: true if flush succeeded; false otherwise. @rai...
625941c62ae34c7f2600d155
def invoke_remote_action_on_target(self, rem_act): <NEW_LINE> <INDENT> if rem_act["RecipientId"] != self._cm_config["NodeId"]: <NEW_LINE> <INDENT> self.sig_log("A mis-delivered remote action was discarded: {0}" .format(rem_act), "LOG_WARNING") <NEW_LINE> return <NEW_LINE> <DEDENT> n_cbt = self.create_cbt(self._module_n...
Convert the received remote action into a CBT and invoke it locally
625941c6cb5e8a47e48b7acf
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
625941c621bff66bcd684978
def p_forcond_empty(self, p): <NEW_LINE> <INDENT> p[0] = None
forcond : SEMICOLON
625941c6fbf16365ca6f61e5
def test_form_validator(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> FormValidator(cleaned_data={}) <NEW_LINE> <DEDENT> except ModelFormFieldValidatorError as e: <NEW_LINE> <INDENT> self.fail( f'ModelFormFieldValidatorError unexpectedly raised. Got {e}')
Asserts raises if cleaned data is None; that is, not provided.
625941c6a79ad161976cc169
def new_url(module): <NEW_LINE> <INDENT> url_base = "/axapi/v3/pki/copy-cert" <NEW_LINE> f_dict = {} <NEW_LINE> return url_base.format(**f_dict)
Return the URL for creating a resource
625941c6460517430c3941ac
def __init__(self, setup_user=None, setup_time=None, remove_user=None, remove_time=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <N...
EventEventMessageMaintenance - a model defined in OpenAPI
625941c67c178a314d6ef481
def __eq__(self, other): <NEW_LINE> <INDENT> if self.capacity == other.capacity: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Returns True if the capacity of self is equal to that of other.
625941c607f4c71912b114a5
def _getSelectedProjectName(self): <NEW_LINE> <INDENT> return str(self.projectsListWidget.currentItem().text())
Get the name for the project selected by the user.
625941c6a8ecb033257d30f1
def print_execution(self): <NEW_LINE> <INDENT> print(' '.join(self.connect + ['--commands=batch,%s,run-batch' % ','.join(self.commands)]))
Prints the execution string |
625941c68c3a8732951583dd
def my_ip_address(): <NEW_LINE> <INDENT> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <NEW_LINE> sock.connect(("8.8.8.8", 80)) <NEW_LINE> return sock.getsockname()[0]
return the public ip of the local host
625941c6eab8aa0e5d26db7b
def basic_map(proj): <NEW_LINE> <INDENT> fig = plt.figure(figsize=(15, 10)) <NEW_LINE> view = fig.add_axes([0, 0, 1, 1], projection=proj) <NEW_LINE> view.set_extent([-120, -70, 20, 50]) <NEW_LINE> view.add_feature(cartopy.feature.NaturalEarthFeature(category='cultural', name='admin_1_states_provinces_lakes', scale='50m...
Make our basic default map for plotting
625941c6435de62698dfdc70
def nth_datum(caffedb, n): <NEW_LINE> <INDENT> n += 1 <NEW_LINE> it = caffedb.iterator() <NEW_LINE> for _ in range(n): <NEW_LINE> <INDENT> _, v = it.next() <NEW_LINE> <DEDENT> datum = caffe_pb2.Datum() <NEW_LINE> datum.ParseFromString(v) <NEW_LINE> return datum
Returns nth datum. 0-based index
625941c663b5f9789fde7109
def test_sha1_expected_hashlib(self): <NEW_LINE> <INDENT> for src, SHA, MD5 in self.testdata: <NEW_LINE> <INDENT> self.assertEqual(hashlib.sha1(src).hexdigest(), SHA)
hashlib.sha1().hexdigest() yields expected results
625941c638b623060ff0ae11
def is_goal(self, state: GraphProblemState) -> bool: <NEW_LINE> <INDENT> assert isinstance(state, RelaxedDeliveriesState) <NEW_LINE> return state.dropped_so_far == self.drop_points
This method receives a state and returns whether this state is a goal. TODO: implement this method!
625941c6cc40096d61595975
def get_args_as_string(self): <NEW_LINE> <INDENT> args_list = self._get_arg_list() <NEW_LINE> return ", ".join( ["{}={}".format(key, args_list.get(key)) for key in args_list.keys()] )
@rtype: str
625941c6d8ef3951e3243561
def shuffle_list(self, containers_list): <NEW_LINE> <INDENT> shuffle_len = self.shuffle_len if self.shuffle_len > 0 else len(containers_list) <NEW_LINE> shuffled = [] <NEW_LINE> list_len = len(containers_list) <NEW_LINE> start = 0 <NEW_LINE> stop = shuffle_len <NEW_LINE> while start < list_len: <NEW_LINE> <INDENT> sub ...
Divide a list of containers to lists with a length self.shuffle_len and shuffle every sublist. If self.shuffle_len == -1, do not divide the list. :param containers_list: a non-shuffled list of containers :return: a shuffled list of containers
625941c6baa26c4b54cb1144
def test_setNumberDensities(self): <NEW_LINE> <INDENT> b = self.Block <NEW_LINE> b.setNumberDensity("NA", 0.5) <NEW_LINE> refDict = { "U235": 0.00275173784234, "U238": 0.0217358415457, "W": 1.09115150103e-05, "ZR": 0.00709003962772, } <NEW_LINE> b.setNumberDensities(refDict) <NEW_LINE> for nuc in refDict.keys(): <NEW_L...
Make sure we can set multiple number densities at once.
625941c671ff763f4b5496ad
def find(self, directory): <NEW_LINE> <INDENT> _index = {} <NEW_LINE> for path, subdirs, files in os.walk(directory): <NEW_LINE> <INDENT> for filename in files: <NEW_LINE> <INDENT> if not self._match_keyword(filename): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> filepath = os.path.join(path, filename) <NEW_LINE> n...
find latest versions of packages
625941c61d351010ab855b40
def bragi_make_params_with_instance_test(): <NEW_LINE> <INDENT> instance = mock.MagicMock() <NEW_LINE> instance.name = 'bib' <NEW_LINE> instance.poi_dataset = None <NEW_LINE> bragi = GeocodeJson(host='http://bob.com/autocomplete') <NEW_LINE> request = {"q": "aa", "count": 20} <NEW_LINE> params = bragi.make_params(reque...
test of generate params with instance
625941c6cb5e8a47e48b7ad0
def exceeded_running_limit(conn): <NEW_LINE> <INDENT> running_workflow_query = "SELECT COUNT(*) " "FROM freesurfer_interface.jobs " "WHERE state = 'RUNNING'" <NEW_LINE> try: <NEW_LINE> <INDENT> fsurfer.log.initialize_logging() <NEW_LINE> logger = fsurfer.log.get_l...
Check to see if the number of workflows in RUNNING state is more than MAX_RUNNING_WORKFLOWS :param conn: database connection to use :return: True if condition holds, False otherwise
625941c6379a373c97cfab68
def __init__(self, channel): <NEW_LINE> <INDENT> self.GetManagedPlacementView = channel.unary_unary( '/google.ads.googleads.v2.services.ManagedPlacementViewService/GetManagedPlacementView', request_serializer=google_dot_ads_dot_googleads__v2_dot_proto_dot_services_dot_managed__placement__view__service__pb2.GetManagedPl...
Constructor. Args: channel: A grpc.Channel.
625941c66fb2d068a760f0c0
def reset(self): <NEW_LINE> <INDENT> ESTWithProjections.reset(self) <NEW_LINE> self.bestPath = None <NEW_LINE> self.bestPathCost = None
Resets all planning effort
625941c61b99ca400220aad5
def SetHeight(self,height:'Any') -> 'None': <NEW_LINE> <INDENT> pass
Sets the height of the toolbar. Args: height(Any):The height in pixels of the toolbar. Returns: None
625941c64e4d5625662d43fd
def get_stats_csv(self, data): <NEW_LINE> <INDENT> stats = self._get_stats() <NEW_LINE> rows = [list(stats.keys())] + [list(i) for i in zip(*stats.values())] <NEW_LINE> with open(CSV_FILE_FORMAT.format(self.project.get_project(), self.subproject), 'w') as csvfile: <NEW_LINE> <INDENT> spamwriter = csv.writer(csvfile, qu...
Returns a CSV file attachment containing global statistics for the project
625941c631939e2706e4ce90
def fetch_and_register_actor(self, actor_class_key): <NEW_LINE> <INDENT> actor_id_str = self._worker.actor_id <NEW_LINE> (driver_id, class_name, module, pickled_class, checkpoint_interval, actor_method_names) = self._worker.redis_client.hmget( actor_class_key, [ "driver_id", "class_name", "module", "class", "checkpoint...
Import an actor. This will be called by the worker's import thread when the worker receives the actor_class export, assuming that the worker is an actor for that class. Args: actor_class_key: The key in Redis to use to fetch the actor. worker: The worker to use.
625941c655399d3f055886d8
def set_style(self): <NEW_LINE> <INDENT> css_provider = Gtk.CssProvider() <NEW_LINE> css_provider.load_from_path('estilos.css') <NEW_LINE> Gtk.StyleContext().add_provider_for_screen( Gdk.Screen.get_default(), css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION )
Permite añadir estilos a ciertos elementos del programa. :return: void
625941c6b5575c28eb68e024
def __init__(self, message_handler, version='2.0', timeout=30): <NEW_LINE> <INDENT> super(JsonRpcServer, self).__init__(self._create_protocol, timeout=timeout) <NEW_LINE> self._message_handler = message_handler <NEW_LINE> if version not in ('1.0', '2.0'): <NEW_LINE> <INDENT> raise ValueError('version: must be "1.0" or ...
The *message_handler* argument specifies the JSON-RPC message handler. It must be a callable with signature ``message_handler(message, protocol)``. The message handler is called in a separate dispatcher fiber (one per connection). The *version* argument specifies the default JSON-RPC version. The *timeout* argument sp...
625941c6f9cc0f698b140621
@blueprint_user.route('/login/', methods=['POST']) <NEW_LINE> @require_json_with_args('username', 'password') <NEW_LINE> def login(): <NEW_LINE> <INDENT> username = str(request.parsed_json['username']) <NEW_LINE> password = str(request.parsed_json['password']) <NEW_LINE> if not auth.check_password(username, password): ...
Logs in a user. On success returns an authorization token, which must then be sent up with every call requiring authorization. On failure returns a 401 NOT AUTHORIZED. Ex: (assumes prefix is localhost:5000/user/) ``` curl -X POST -H "Content-Type: application/json" localhost:5000/user/login/ -d '{ "usern...
625941c6004d5f362079a358
def TraceQuit(): <NEW_LINE> <INDENT> sendTrace({'type':'TraceQuit'}) <NEW_LINE> _TraceQuit()
TraceQuit() Shutdown collecting trace process, by retiring the connected channelend. Application will hang if this is not invoked. This function will abort tracing when called.
625941c6d268445f265b4e92
def addSigningInformation(self, account, permission): <NEW_LINE> <INDENT> self.constructTx() <NEW_LINE> self["blockchain"] = self.blockchain.rpc.chain_params <NEW_LINE> if isinstance(account, self.publickey_class): <NEW_LINE> <INDENT> self["missing_signatures"] = [str(account)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <IND...
This is a private method that adds side information to a unsigned/partial transaction in order to simplify later signing (e.g. for multisig or coldstorage) FIXME: Does not work with owner keys!
625941c65f7d997b87174abb
def build_tags(self, text: str) -> None: <NEW_LINE> <INDENT> self._text = text <NEW_LINE> words = self.text2words(text) <NEW_LINE> for current_word in words: <NEW_LINE> <INDENT> tag = self.process_word(current_word) <NEW_LINE> if tag: <NEW_LINE> <INDENT> self._tags[tag] += 1 <NEW_LINE> self._words[tag].add(current_word...
Build tags and words from text
625941c68e05c05ec3eea398
def test_calls_reallocation(self): <NEW_LINE> <INDENT> self.resp_calls = [] <NEW_LINE> self.allocation_pool.complete(self.cr, self.uid, [64], context='complete_test_resp') <NEW_LINE> self.assertEqual(len(self.resp_calls), 3) <NEW_LINE> self.assertIn((self.nurse, [self.location]), self.resp_calls) <NEW_LINE> self.assert...
Test that the calls the responsibility allocation method with the user ID and location IDS
625941c6377c676e912721cd
def visit_output(self, node): <NEW_LINE> <INDENT> print(self.visit(node.expr))
Print the value of the expression.
625941c615fb5d323cde0b32
def __init__(self, *attrs, **kwargs): <NEW_LINE> <INDENT> self.codes = [codes[attr.lower()] for attr in attrs if isinstance(attr, str)] <NEW_LINE> if kwargs.get("reset", True): <NEW_LINE> <INDENT> self.codes[:0] = [codes["reset"]] <NEW_LINE> <DEDENT> def qualify_int(i): <NEW_LINE> <INDENT> if isinstance(i, int): <NEW_L...
:param attrs: are the attribute names of any format codes in `codes` :param kwargs: may contain `x`, an integer in the range [0-255] that selects the corresponding color from the extended ANSI 256 color space for foreground text `rgb`, an iterable of 3 integers in the range [0-255] that select the corresponding colo...
625941c673bcbd0ca4b2c09b
def setFormat(self, format): <NEW_LINE> <INDENT> return _DataModel.AuxStream_setFormat(self, format)
setFormat(AuxStream self, std::string const & format)
625941c64527f215b584c47d
def get_srid(self, geom): <NEW_LINE> <INDENT> if geom.srid is None or (geom.srid == -1 and self._srid != -1): <NEW_LINE> <INDENT> return self._srid <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return geom.srid
Has logic for retrieving the default SRID taking into account the SRID of the field.
625941c6236d856c2ad447fd
def update_a_jobs(main, file, compiler_versions: dict, images_mapping: dict, compiler_deleting: dict): <NEW_LINE> <INDENT> platform = { "name": "AppVeyor", "beginning_keywords": ("matrix:",), "end_keyword": "install:", "delimiter": ": ", "job_beginning_indication": "-", "job_beginning_indication_use_spaces": False, } <...
This update script adds new compiler versions to the AppVeyor jobs :param file: CI file path :param compiler_versions: List of recommended new compiler versions :param images_mapping: Mapping of compiler version to specific CI runtime images :param compiler_deleting: Compiler versions which are getting deleted
625941c62ae34c7f2600d156
def _attrs_to_driver(self, router): <NEW_LINE> <INDENT> distributed = _is_distributed( router.get('distributed', lib_const.ATTR_NOT_SPECIFIED)) <NEW_LINE> ha = _is_ha(router.get('ha', lib_const.ATTR_NOT_SPECIFIED)) <NEW_LINE> drivers = list(self.drivers.values()) <NEW_LINE> if self.default_provider: <NEW_LINE> <INDENT>...
Get a provider driver handle based on the ha/distributed flags.
625941c615baa723493c3f99
def get_token(): <NEW_LINE> <INDENT> auth_url = os.environ['OS_AUTH_URL'].replace('v2.0', 'v3') <NEW_LINE> url = "%s/auth/tokens?nocatalog" % auth_url <NEW_LINE> body = { "auth":{ "identity": { "methods": ["password"], "password": { "user": { "name": os.environ['OS_USERNAME'], "domain": {"id": "default"}, "password": o...
The python keystoneclient doesn't provide a way to get a v3 nocatalog token, so this function gets one from the api.
625941c6d99f1b3c44c675b5
def clone(estimator, safe=True): <NEW_LINE> <INDENT> estimator_type = type(estimator) <NEW_LINE> if estimator_type in (list, tuple, set, frozenset): <NEW_LINE> <INDENT> return estimator_type([clone(e, safe=safe) for e in estimator]) <NEW_LINE> <DEDENT> elif not hasattr(estimator, 'get_params'): <NEW_LINE> <INDENT> if n...
Constructs a new estimator with the same parameters. Clone does a deep copy of the model in an estimator without actually copying attached data. It yields a new estimator with the same parameters that has not been fit on any data. Parameters ---------- estimator: estimator object, or list, tuple or set of objects ...
625941c6046cf37aa974cd6d
def test_process_projects(self): <NEW_LINE> <INDENT> p1 = self._create_project(self.inventory_type, "My Electronic Parts") <NEW_LINE> p2 = self._create_project(self.inventory_type, "My Music") <NEW_LINE> p3 = self._create_project(self.inventory_type, "My Stamp Collection") <NEW_LINE> projects = [ {'project': p1, 'role_...
Test that projects can be added and removed from a user.
625941c6c4546d3d9de72a57
def letterCombinations(self, digits): <NEW_LINE> <INDENT> dic = { "2":"abc", "3":"def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "vxyz" } <NEW_LINE> def rec(index, curr): <NEW_LINE> <INDENT> if index == n: <NEW_LINE> <INDENT> res.append(curr) <NEW_LINE> return <NEW_LINE> <DEDENT> for c in dic[d...
:type digits: str :rtype: List[str] "23" / | \ "a" "b" "c" / "af""ad""ae"
625941c691af0d3eaac9ba3c
def reset(self): <NEW_LINE> <INDENT> _resetArray = [] <NEW_LINE> for stellar in self._current_save: <NEW_LINE> <INDENT> _resetArray.append(stellar) <NEW_LINE> <DEDENT> _saveArray = [] <NEW_LINE> for stellar in self._current_save: <NEW_LINE> <INDENT> _saveArray.append(stellar.clone()) <NEW_LINE> <DEDENT> self._current_s...
If the state has previously been saved, return a list of the objects in the save variable. Then rebuild the save variable using clones once more (so that the save state remains decoupled from the running simulation.) If the state has never been saved, return an empty list. reset() -> list(stellar)
625941c6090684286d50ed09
def work(self, input, output, **kwargs): <NEW_LINE> <INDENT> d = {} <NEW_LINE> for word, v in input: <NEW_LINE> <INDENT> d[word] = sum(v) + d.get(word, 0) <NEW_LINE> <DEDENT> for word, num in d.iteritems(): <NEW_LINE> <INDENT> output[word] = num
sum occurances of each word
625941c6be8e80087fb20c69
def set_admin_password(self, instance, new_pass): <NEW_LINE> <INDENT> cmd="{\"execute\" :\"guest-set-root-password\", \"arguments\":{\"newpass\": \"%s\"}}" % new_pass <NEW_LINE> virt_dom = self._lookup_by_name(instance['name']) <NEW_LINE> libvirt_qemu.qemuAgentCommand(virt_dom, cmd, 10,libvirt_qemu.VIR_DOMAIN_QEMU_AGEN...
Set root/admin password for a specific instance name.
625941c6be7bc26dc91cd627
def from_envvar(): <NEW_LINE> <INDENT> options = { "development": DevelopmentConfig, "test": TestConfig, "production": ProductionConfig, } <NEW_LINE> try: <NEW_LINE> <INDENT> choice = os.environ["ENV"] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise KeyError("'ENV' is not set") <NEW_LINE> <DEDENT> if cho...
Get configuration class from environment variable.
625941c6435de62698dfdc71
def save(uploaded): <NEW_LINE> <INDENT> with Image.open(uploaded) as image: <NEW_LINE> <INDENT> if image.format != 'JPEG' and image.format != 'PNG': <NEW_LINE> <INDENT> raise Exception <NEW_LINE> <DEDENT> if image.width >= 100 and image.height >= 100: <NEW_LINE> <INDENT> thumbnail = image.copy() <NEW_LINE> if image.wid...
保存上传的图片,并生成缩略图
625941c6d18da76e235324fa
def parse_outline(lines, curr_line = 0, curr_indent = 0): <NEW_LINE> <INDENT> outline = [] <NEW_LINE> indent_re = re.compile(r'^\s*') <NEW_LINE> while curr_line < len(lines): <NEW_LINE> <INDENT> line = lines[curr_line] <NEW_LINE> indent = indent_re.match(line).end() <NEW_LINE> if line.strip() == '' or line.startswith('...
Reads in an outline file and generates an internal data structure of the outline. The structure is roughly a list of lists. Each entry is a list with two items: a string for the parent item, and a list of child entry. If an entry has no children, then the entry is just a string.
625941c621a7993f00bc7d12
def aroon_oscillator(df,n): <NEW_LINE> <INDENT> AOSC = talib.AROONOSC(df['High'], df['Low'], timeperiod=n) <NEW_LINE> AOSC_series = pd.Series(AOSC, name='AO_' + str(n)) <NEW_LINE> df = df.join(AOSC_series) <NEW_LINE> return df
Calculates Aroon oscillator using Ta-Lib library's built-in function. :param df: pandas.DataFrame :return: pandas.DataFrame
625941c699fddb7c1c9de3b6
def eta_carnot_cooling(self): <NEW_LINE> <INDENT> Tvector = self._cycle_states.T <NEW_LINE> return np.min(Tvector) / (np.max(Tvector) - np.min(Tvector))
Carnot efficiency Calculates the Carnot efficiency for a cooling process, :math:`\eta_c = rac{T_c}{T_h-T_c}`. Returns ------- float
625941c6e76e3b2f99f3a833
def resource_show(context, data_dict): <NEW_LINE> <INDENT> model = context['model'] <NEW_LINE> user = context.get('user') <NEW_LINE> resource = get_resource_object(context, data_dict) <NEW_LINE> package = resource.resource_group.package <NEW_LINE> if package.state == 'deleted': <NEW_LINE> <INDENT> userobj = model.User....
Resource show permission checks the user group if the package state is deleted
625941c656ac1b37e62641f7
def test_postprocessing(self): <NEW_LINE> <INDENT> kwargs = self._update_kwargs_item(lambda x: dict(prediction=x.tolist()), 'postprocessor', 'last') <NEW_LINE> server = ModelServer(self.model, self.predict, **kwargs) <NEW_LINE> app = server.app.test_client() <NEW_LINE> sample_data = self._get_sample_data() <NEW_LINE> r...
Test predictions endpoint with custom postprocessing callback.
625941c6f7d966606f6aa028
def execute(self, op): <NEW_LINE> <INDENT> self.fd = op.fd <NEW_LINE> op.state = 'running' <NEW_LINE> self.busy = True <NEW_LINE> try: <NEW_LINE> <INDENT> if (op.fd is None) and (op.name not in ('open', '_stop')): <NEW_LINE> <INDENT> raise RuntimeError("Calling a file operation {0} on None".format(op.name)) <NEW_LINE> ...
@param op: operation to execute @return: None
625941c66e29344779a62638
def input(self, record, inputLink=0): <NEW_LINE> <INDENT> assert False, "DataflowNode class not meant to be used directly."
Default behavior is assertion exception; descendants should override.
625941c6627d3e7fe0d68e74
def cert_as_of_request(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.certificate.history.as_of(self.date_requested) <NEW_LINE> <DEDENT> except Certificate.DoesNotExist: <NEW_LINE> <INDENT> return self.certificate.history.first() or self.certificate
Certificate as of date this change was requested
625941c62c8b7c6e89b357e6
def test_update_channel(self): <NEW_LINE> <INDENT> item = self.non_deleted_media.get(id='populated') <NEW_LINE> item.sms.delete() <NEW_LINE> item.channel.edit_permission.crsids.append(self.user.username) <NEW_LINE> item.channel.edit_permission.save() <NEW_LINE> new_channel = mpmodels.Channel.objects.create( title='new ...
Cannot change the channel of a media item, even if user has all the right edit permissions.
625941c699cbb53fe6792c0b
def setpassworddigest(self, passwd_digest): <NEW_LINE> <INDENT> self.password_digest = passwd_digest
Set password digest which is a text returned by auth WS.
625941c645492302aab5e2e7
def existing_url(module): <NEW_LINE> <INDENT> url_base = "/axapi/v3/debug/ssli" <NEW_LINE> f_dict = {} <NEW_LINE> return url_base.format(**f_dict)
Return the URL for an existing resource
625941c6d8ef3951e3243562
def recognize(models: dict, test_set: SinglesData): <NEW_LINE> <INDENT> warnings.filterwarnings("ignore", category=DeprecationWarning) <NEW_LINE> probabilities = [] <NEW_LINE> guesses = [] <NEW_LINE> for test_word in test_set.get_all_Xlengths().keys(): <NEW_LINE> <INDENT> test = test_set.get_all_Xlengths()[test_word] <...
Recognize test word sequences from word models set :param models: dict of trained models {'SOMEWORD': GaussianHMM model object, 'SOMEOTHERWORD': GaussianHMM model object, ...} :param test_set: SinglesData object :return: (list, list) as probabilities, guesses both lists are ordered by the test set word_id ...
625941c63317a56b86939c80
def test_pdb(example_path="examples", threshold=0.001): <NEW_LINE> <INDENT> p_atoms, P = rmsd.get_coordinates(example_path+'/ci2_1.pdb', 'pdb') <NEW_LINE> q_atoms, Q = rmsd.get_coordinates(example_path+'/ci2_2.pdb', 'pdb') <NEW_LINE> n_rmsd = rmsd.rmsd(P, Q) <NEW_LINE> Pc = rmsd.centroid(P) <NEW_LINE> Qc = rmsd.centroi...
A simple test for the PDB functionality :return: True if all test passed
625941c699fddb7c1c9de3b7
def testImplementMove(self, move): <NEW_LINE> <INDENT> return [PieceMove(PieceCoord(self.mapper[move[0]], int(move[1])-1), PieceCoord(self.mapper[move[2]], int(move[3])-1))]
Test version which takes a string instead of a move
625941c6dc8b845886cb5559
def iprand(): <NEW_LINE> <INDENT> return 'iprand'
Some ipython tests with random output. In [7]: 3+4 Out[7]: 7 In [8]: print('hello') world # random In [9]: iprand() Out[9]: 'iprand'
625941c63539df3088e2e370
def plot_studio_count_yearly(data, top_n=10): <NEW_LINE> <INDENT> yearly = data[["studio", "aired_from_year"]] <NEW_LINE> yearly = data[data["aired_from_year"] < 2018] <NEW_LINE> yearly = pd.concat([yearly["aired_from_year"], pd.get_dummies(yearly["studio"] .str.split(", ", expand=True), prefix="", prefix_sep="")], axi...
Plots the yearly count of the top_n studios Parameters ---------- data : DataFrame Pandas DataFrame that contains anime show data top_n : Integer Determines how many studios that will be placed onto the graph Notes ----- Visualization Type: Line Plot File Path: plots/rq3_studios_yearly.png If the top_n value ...
625941c66fece00bbac2d762
def test_twenty_rounds_joss_for_noncyclers(self): <NEW_LINE> <INDENT> seed = 4 <NEW_LINE> match = axl.Match( (axl.FirstByJoss(), axl.AntiCycler()), turns=20, seed=seed ) <NEW_LINE> match.play() <NEW_LINE> self.versus_test( axl.AntiCycler(), expected_actions=match.result, seed=seed )
Uses axelrod.strategies.axelrod_first.FirstByJoss strategy for first 20 rounds
625941c6dc8b845886cb555a
def calc_dot_size(self): <NEW_LINE> <INDENT> self.dx = max(self.resx / self.dpi, 2) <NEW_LINE> self.px = max((self.dx * self.dotpercent) / 100, 1) <NEW_LINE> self.dy = max(self.resy / self.dpi, 2) <NEW_LINE> self.py = max((self.dy * self.dotpercent) / 100, 1)
Calculate data point raster and size of point. Calculate data point raster (dx,dy) and size of the point (px,py) in the pixels of printer's resolution. Note that pixels, at least in theory, may be non-rectangular. https://github.com/BrnoPCmaniak/python-paperbak/blob/dfba2a395bfeec4dafe9566afa4eb96c68771423/old_cpp/Pr...
625941c65fc7496912cc39a3
def set_model_column(self, column): <NEW_LINE> <INDENT> self.widget.setModelColumn(column)
Set the model column for the widget.
625941c6ff9c53063f47c219