content
stringlengths
22
815k
id
int64
0
4.91M
def flatten_dict(value): # type: (typing.Mapping[str, Any]) -> Dict[str, Any] """Adds dots to all nested fields in dictionaries. Raises an error if there are entries which are represented with different forms of nesting. (ie {"a": {"b": 1}, "a.b": 2}) """ top_level = {} for key, val in value...
56,200
def new_text(): """ Write a new text post page """ form = CreatePostForm() if form.validate_on_submit(): t = datetime.utcnow() textpost = TextPost(author=current_user._get_current_object(), title=form.title.data, timestamp=t, text=form.text.data, ...
56,201
def Created_Session(msg): """ 创建会话并返回会话id """ try: response = core.create_session() except grpc.RpcError as e: details = e.details() logger.error("error details:{details}") return {"flag": False, "details": details, } session_id = response.session_id logger.i...
56,202
def get_steering_policy_attachment(steering_policy_attachment_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSteeringPolicyAttachmentResult: """ This data source provides details about a specific Steering Policy Attachment resource in Ora...
56,203
def install_latest_brew_formula(log, formula): """Install or upgrade a brew formula""" # Check formula info for install/up-to-date status out, err = subprocess.Popen( [ get_brew(), 'info', '--json=v1', formula ], stdout=subprocess.PIPE,...
56,204
def get_parsing_plan_log_str(obj_on_fs_to_parse, desired_type, log_only_last: bool, parser): """ Utility method used by several classes to log a message indicating that a given file object is planned to be parsed to the given object type with the given parser. It is in particular used in str(ParsingPlan), b...
56,205
def download_images(content, dump_path): """ download images from content :param content: html content :param dump_path: path to dump updated html :return: """ echo.push_subroutine(sys._getframe().f_code.co_name) echo.clog(f'Start Parsing Images') # parse images try: soup = BeautifulSoup(content, 'lxml')...
56,206
def original_text_sector( run: Optional[Run] = None, clustered: bool = True, ): """the text sector for each company from the original clustering. If the companies were not included in that the text sector clustering, this will be `None` for each company.""" run = run or get_run("ClusterReassignF...
56,207
def test_agb_ejected_masses(agb_nugrid, m, z, elt, answer): """Get items right from the table.""" my_answer = agb_nugrid.elemental_ejecta_mass(m, z, elt) assert my_answer == approx(answer, rel=1E-3)
56,208
def flatten_errors(error_message: Union[Dict, List, str]) -> str: """Flatten Cerberus' error messages.""" def flatten_dict(error_dict: Dict) -> str: """Return a string version of the dict.""" return ", ".join([f"{key}: {flatten_errors(value)}" for key, value in error_dict.items()]) def flat...
56,209
def get_best_estimators(classification): """ Loads the estimators that are pickled in `grid` folder Note that if you want to use different or more estimators, you can fine tune the parameters in `grid_search.py` script and run it again ( may take hours ) """ grid_dir = os.path.join(os.path.d...
56,210
def get_byuserid(u_id, categories): """Render all gifts created by a user of id u_id. Arguments: u_id (int): the id of the desired user. categories (object): generally passed through the @include_categories decorator, contains all categories in the data...
56,211
def index(request): """ This view redirects user to home if logged in else it redirects user to login page. """ if request.user.is_authenticated: return HttpResponseRedirect('home') return HttpResponseRedirect('login')
56,212
def _classname(class_): """Returns the full name for a class. Has option for overriding some class names to hide internal details. The overrides are stored in the `_class_aliases` dictionaries. """ rawname = "{}.{}".format(class_.__module__, class_.__name__) if rawname in _class_aliases: ...
56,213
def fracsimplify(numerator, denominator): """ Simplify a fraction. :type numerator: integer :param numerator: The numerator of the fraction to simplify :type denominator: integer :param denominator: The denominator of the fraction to simplify :return: The simplified fraction ...
56,214
def polar_adjust_scale(lon, lat, s=1): """Rescale lon, lat by contracting or expanding from the north pole. This is necessary to compensate for the not quite complete coverage of the projection For the test PufferSphere, s=0.833 is a good compensation s sets the scaling factor. """ r = (np.pi/2...
56,215
def save_mnist(dataset_name): """Save dataset as a .pkl file and remove .gz files.""" data = [] for name in MNIST_URL[:2]: with gzip.open(name[1], 'rb') as f: data.append(np.frombuffer(f.read(), np.uint8, offset=16).reshape(-1, 28 * 28)) for name...
56,216
def rsa_keygen(private_key): """Create a new SSH key""" private_key = expanduser(private_key) rsa_keygen = ['ssh-keygen', '-t', 'rsa', '-N', '', '-f', private_key] call(rsa_keygen)
56,217
def process_jobs_output(final_df): """ preprocess the dataframe before creating pdf :param final_df: final dataframe :type final_df: pandas.DataFrame :return: processed dataframe """ output_df = final_df.copy() output_df['job_title'] = np.where(output_df['job_title'].str.len() > 30, o...
56,218
def save_parts(fig, fpath, grouped_axes=None, dpi=None): """ FIXME: this works in mpl 2.0.0, but not 2.0.2 Args: fig (?): fpath (str): file path string dpi (None): (default = None) Returns: list: subpaths CommandLine: python -m wbia.plottool.draw_func2 sav...
56,219
def _vector2xy(v, pole): """Return stereographic coordinates (X, Y) of 3D unit vectors. (X, Y) is both zero for vectors with z equal to the projection pole. Parameters ---------- v : Vector3d If it's not a unit vector, it will be made into one. pole : int -1 or 1, where -1 (1) ...
56,220
def find_unique_addresses(address_request_json): """ Finds unique addresses in a provided address request json returned from the ReCollect service :param address_request_json: json object returned from ReCollect address request service :return: list of unique addresses """ logger.deb...
56,221
def defer_group_class(node: c.SchemaNode, kw: dict) -> t.Type[IGroupModel]: """Colander helper deferred to assign the current group model. :param node: Colander SchemaNode :param kw: Keyword arguments. :return: IGroupModel """ request = kw.get("request") assert request, "To use this widget ...
56,222
def test_pedido_detail_allowed_methods( method, allowed, adminClient, detail_url ): """Testa os métodos permitidos da view de conjunto dos pedidos""" pedido = mixer.blend(Pedido) res = getattr(adminClient, method)(detail_url(pedido.id)) assert (res.status_code != status.HTTP_405_METHOD_NOT_ALLOWED) ...
56,223
async def search_roles_count(conn, search_query): """Get a count of all search fields for roles in one query.""" resource = ( await roles_search_name(search_query) .union(roles_search_description(search_query)) .distinct() .count() .run(conn) ) return resource
56,224
def train(args, base_model=None, loaders=None, loaders_len=None, is_fold=-1, is_train=True): """ :param args: :return: """ if loaders is None: loaders, loaders_len = load_data(args) print(loaders_len) postfix = '' if is_fold == -1 else '-kf{}'.format(is_fold) # if args.batch_s...
56,225
def get_db_engine() -> Engine: """ Opens a new database connection if there is none yet for the current application context. """ if not hasattr(g, "dbengine"): engine = create_engine(application.config["SQLALCHEMY_DATABASE_URI"], echo=ENV_LOG_FLAG) engine.connect() g.dbengine...
56,226
def main(): """ Purpose: Test the function Args: N/A Returns: N/A """ # sample address address = "R Street Northwest & 19th Street Northwest, Washington, DC" # address = "4915 Sheriff Rd NE, Washington, DC 20019" print(f"Testing using address: {address}") ...
56,227
async def async_destroy_model(model_name): """Remove a model from the current controller. :param model_name: Name of model to remove :type model_name: str """ controller = Controller() await controller.connect() logging.debug("Destroying model {}".format(model_name)) await controller.de...
56,228
def get_subset(container, subset_bounds): """Returns a subset of the given list with respect to the list of bounds""" subset = [] for bound in subset_bounds: subset += container[bound[0]: bound[1]] return subset
56,229
def check_compiled(module): """Check whether given module has been compiled. Args: module: string, module name """ check_module = __import__(module, globals(), locals(), -1) ext = os.path.splitext(check_module.__file__)[-1] if ext in ('.py', '.pyc'): raise RuntimeError( "Profiling uncompiled...
56,230
def _encode_decimal128(name, value, dummy0, dummy1): """Encode bson.decimal128.Decimal128.""" return b"\x13" + name + value.bid
56,231
def buildstamp(p5_connection=None): """ Syntax: srvinfo buildstamp Description: Returns the build time-stamp of the P5 release Return Values: -On Success: The build time-stamp """ method_name = "buildstamp" return exec_nsdchat([module_name, method_name], p5_connection)
56,232
def changeoOb(attrname, G, A, i): """change statistic for binary exogenous attribute oOb (outcome attribute related to binary attribute on same node) [*] """ return 0 if G.binattr[attrname][i] == NA_VALUE else G.binattr[attrname][i]
56,233
def is_cli_command(ctx: Context) -> bool: """ Check if command is run from CLI Args: ctx: Click context object Returns: True if run as CLI command, False otherwise """ return ctx.parent.info_name == "model-navigator"
56,234
def IsPlatformSupported(opts): """Checks that this platform and build system are supported. Args: opts: The options parsed from the command line. Returns: True if the platform and build system are supported. """ # Haven't tested the script out on any other platforms yet. supported = ['posix', 'nt'...
56,235
def is_prime_mr(n): """ Miller-Rabin primality test. A return value of False means n is certainly not prime. A return value of True means n is very likely a prime. Source: http://rosettacode.org/wiki/Miller-Rabin_primality_test#Python >>> is_prime_mr(2) True >>> is_prime_mr(8) Fal...
56,236
def call(command, **kwargs): """ 参考subprocess.call Args: command: shell命令 kwargs: 其他参数 """ if "print_command" in kwargs: print_command = kwargs["print_command"] del kwargs["print_command"] else: print_command = IS_PRINT_COMMAND def sub_func(*args, **...
56,237
def lat_lon2point(df): """Create shapely point object of latitude and longitude.""" return Point(df['Wikipedia', 'longitude'], df['Wikipedia', 'latitude'])
56,238
def _get_exp_uri(): """Return expected basic result for OpenUri action.""" return OrderedDict( ( ("@type", "OpenUri"), ("name", "Open URL"), ( "targets", [OrderedDict((("os", "default"), ("uri", "http://www.python.org")))], ...
56,239
def save_json(node): """Load tvm object as json string. Parameters ---------- node : Node A TVM Node object to be saved. Returns ------- json_str : str Saved json string. """ return _api_internal._save_json(node)
56,240
def normalize_text(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): return re.sub(r"\b(a|an|the)\b", " ", text) def white_space_fix(text): return " ".join(text.split()) def remove_punc(text): exclude = set(string.punctuation) return "".joi...
56,241
def computeBits(image, start, end, newName): """ Compute the bits of an image :param start: start bit :type start: int :param end: end bit :type end: int :param newName: new name for the band :type newName: str :return: A function which single argument is the image and returns a single ...
56,242
def test_set_tf_matrix(): """TensorFlowのレイヤーに行列を突っ込む""" inputs = tf.keras.Input( shape=(28, 28, 5), ) tf_conv2d = tf.keras.layers.Conv2D(filters=64, kernel_size=3)(inputs) model = tf.keras.Model(inputs=inputs, outputs=tf_conv2d) print(len(model.layers[1].get_weights())) print([type(i...
56,243
def test_service_stopped_instead_of_listening(eventloop): """Test the case when process stops instead of starting and listening to the endpoint. Check that in such cases `Launcher` raises `RuntimeError` exception and stops. """ test_service = { 'name': 'TestService', 'endpoi...
56,244
def roulette (samples, weights = None , count = None): """Sampling with replacement, using the roulette wheel algorithm described in Udacity CS373 unit 3.20""" # http://www.udacity.com/view#Course/cs373/CourseRev/feb2012/Unit/182001/Nugget/215003 if not count: count = len(samples) if not we...
56,245
def get_html_connector_kwargs_options_from_args(args): """Take a parsed ArgumentParser and return a dict of argument.""" if not args.password: args.password = getpass.getpass( "Please enter the password for {} with login {}:\n".format(args.url, args.login) ) return { "url...
56,246
def config_cli(): """Configuration related actions."""
56,247
def test_delete_collection(mdb): """ Confirm that collection deletions work as intended. Checks: * DATA_MANAGEMENT can delete any entry. * Users in editors with DATA_EDIT can delete the entry. * No other users can delete entries. """ session = requests.Session() collections = [entry...
56,248
def test_build_supplement_tree(): """Integration test""" with XMLBuilder('APPENDIX') as ctx: ctx.HD("Supplement I to Part 737-Official Interpretations", SOURCE='HED') ctx.HD("Section 737.5 NASCAR", SOURCE='HD2') ctx.P("1. Paragraph 1") ctx.P("i. Paragraph i; A. Sta...
56,249
def benchmark(problems, algorithms, stop_criterion, runs=10, seeds=None): """A function to perform multiple algorithms on multiple soltions. Note that the problems, algorithms and the stop criterion all need to have the method reset method properly implemented for this function to work properly. The lo...
56,250
def list_huisnummers_adapter(obj, request): """ Adapter for rendering a list of :class:`crabpy.gateway.crab.Huisnummer` to json. """ return { 'id': obj.id, 'status': { 'id': obj.status.id, 'naam': obj.status.naam, 'definitie': obj.status.definitie ...
56,251
def fetch_production(zone_key, session=None, target_datetime=None, logger=None): """ Requests the last known production mix (in MW) of a given country Arguments: zone_key (optional) -- used in case a parser is able to fetch multiple countries session (optional) -- request session passed in orde...
56,252
def generate_vocab_from_token_count(token_count, max_vocab_size=1000000, min_count=0, unk_tk=UNK_TK, start_tk=START_TK, decode_tk=DECODE_TK,...
56,253
def timesketch_list_saved_searches( data: Optional[Text] = '') -> Dict[str, api_search.Search]: """List up all available saved searches. Args: data (str): Not used. Returns: A dict with a list of available saved searches. """ connect() state_obj = state.state() sketch = state_obj.get_from_ca...
56,254
def codePath(): """Returns path to the program sources""" if not frozen: return os.path.dirname(__file__) return ( os.environ.get('RESOURCEPATH') # pylint: disable=protected-access if frozen == "macosx_app" else sys._MEIPASS)
56,255
def compute_signature_bindings(signature): """ Return an exhaustive list of all possible bindings compatible with the given signature, i.e. list of sorts. """ domains = [s.domain() for s in signature] for binding in itertools.product(*domains): yield binding
56,256
def get_coords(gals): """ Takes list of galaxies and looks up their coordinates by name. If no name found: warn, skip, remove galaxy from list Returns: gals: list of galaxies minus those that weren't found start_coord: list of coordinates corresponding to center of g...
56,257
def yesnoquery(message): """ Displays `message` and waits for user Y/N input. Returns Boolean where true means Y. """ useryn = None while useryn is None: if not isinstance(message, str): raise ValueError("Must pass a valid string to query") useryn =...
56,258
def check_numeric_or_single_arg_callable(value, name=""): """Ensure a numeric of single arg callable.""" is_numeric = isinstance(value, Number) is_callable = callable(value) if is_callable and len(signature(value).parameters) != 1: raise ValueError(f"{name} callable must have a single argument")...
56,259
def material(): """ Factory associated with PowerLaw3D. """ return PowerLaw3D()
56,260
def formatExtendedTraceback(exc): """Format a traceback for the given exception as a string. The traceback will include the source line of each frame, as usual, but also the values of local variables in the frames. """ return ''.join(listExtendedTraceback(exc)).rstrip('\n')
56,261
def main(config_path): """Main. Args: config_path (str): path to config file The config file should have '.ini' suffix """ # pylint: disable=too-many-locals config = load_config(config_path=config_path) cell = create_cell_using_config(config) release_params = get_releas...
56,262
def run(prm: Dict[str, Any]) -> None: """ Run the postprocessing defined by the configuration parameters. It assumes that the dictionary of parameters was validated via a ConfigChecker instance. :param prm: the parsed parameters """ prm = PostprocessingChecker( initial_params=prm, ...
56,263
def joke() -> None: """To tell a joke""" try: jokeslist = ["My friend was explaining electricity to me, but I was like, wat ?", "I failed math so many times at school, I can’t even count", "Never trust atoms; they make up everything", "The f...
56,264
def _normalize_ad_ts_sid(df, ndays=0, nhours=8, target_tz='utc'): """规范`asof_date`、`timestamp`、`sid` 操作: 股票代码 -> sid(int64) date(date) -> asof_date(timestamp) date(date) + ndays -> timestamp(timestamp) 确保timestamp >= asof_date """ if AD_FIELD_NAME in df.columns: ...
56,265
def set_app_settings(app): """ Use existing env vars if loaded """ if None in [ get("client_id"), get("cognito_domain"), get("client_secret"), ]: cognito_credentials = load_cognito_settings() set("cognito_domain", cognito_credentials["cognito_domain"]) ...
56,266
def banner(version, color=True): """ Banner, just for fanciness Parameters: version (int): Version of SéCh3r """ _banner = """ / __ ____ () _ / () |) __/ ,_ /\ |/| |/\ \/ | /(_)|_/\___/| |/\__/ |/ """[1:] if color: print(f"{rst}{bold}{_b...
56,267
def convertHDF5Mesh(h5Mesh, group='mesh', indices='cell_indices', pos='coordinates', cells='topology', marker='values', marker_default=0, dimension=3, verbose=True, useFenicsIndices=False): """ Converts instance of a hdf5 mesh to a :gimliapi:`GIMLI::Me...
56,268
def test_rasr_fit_to_randn_distribution_cutoff3(): """Check fit against approximate estimation of the mixing and threshold matrices for given cutoff""" np.random.seed(seed=10) srate = 250 cutoff = 3 window_len = int(0.5 * srate) window_interval = int(window_len * 0.34) X = np.diag(np.arange(...
56,269
def lnLikelihoodGaussian(parameters, values, errors, weights=None): """ Calculates the total log-likelihood of an ensemble of values, with uncertainties, for a Gaussian distribution. INPUTS parameters : model parameters (see below) values : data values errors : data unc...
56,270
def process_news_articles(news_return) -> json: """ Function to process data into a json file 'news_articles.json' Loads data into a json to be stored or used later" Arguments: news_return: List of news articles as dictionaries """ articles = news_return['articles'] with open(...
56,271
def g(r, r_i, r_c, a, gamma): """ Non-orthogonalized radial functions """ def g_(r, r_i, r_c, a): return (r-r_i)**(2)*(r_c-r)**(a+2)*np.exp(-gamma*(r/r_c)**(1/4)) # return (r-r_i)**(5)*(r_c-r)**(a+2) r_grid = np.arange(r_i, r_c, (r_c-r_i)/1e3) N = np.sqrt(np.sum(g_(r_grid,r_i,r_...
56,272
def formatProccessingTime(ss, verbose: int = 1, estimate: bool = True, keep_seconds=False): """ Format processing time to string Args: ss: Time in seconds or a string """ if isinstance(ss, (str, bytes)): res = ss else: if ss < 0: res = '-1' elif ss < 60: ...
56,273
def lorenz(xyz, t, sigma, beta, rho): """The most famous of the strange attractors.""" x, y, z = xyz dx = sigma * (y - x) # dt dy = x * (rho - z) - y # dt dz = x * y - beta * z # dt return dx, dy, dz
56,274
def seq_to_array(seq, k=1, overlap=True): """Converts a DNA sequence into a Numpy vector. If :math:`k>1`, then it creates a vector of the :math:`k`-mers. Args: seq (~skbio.sequence.DNA or str): The sequence to convert. k (int, optional): The :math:`k` value to use. Defaults to 1. ov...
56,275
def add_classes_to_geojson(geojson, class_map): """Add missing class_names and class_ids from label GeoJSON.""" geojson = copy.deepcopy(geojson) features = geojson['features'] for feature in features: properties = feature.get('properties', {}) if 'class_id' not in properties: ...
56,276
def calNewGeoLocationNE(initialPOINT, yNORTH, xEAST): """ This function is used to calculate new GEO Point which is 'y' meters north and 'x' meters east of a Reference point. Knowing the lat/long of reference point and y and x distance , it returns a POINT class object with new location lat/long value. This functi...
56,277
def solve_RMits(data, xs, flx, k, slvr_opts, filename=None): """Solve the Ronen Method by non-linear iterations based on CMFD and diffusion.""" # unpack data Db = xs[-1] # retrieve Db which does not change with CMFD ss = xs[1] # check for scattering anisotropy in input xs data lin_anis = False...
56,278
def add_quantiles_functions_to_pymc_class(pymc_class): """ add quantiles methods to a pymc class Input: pymc_class <class> """ #turn pymc node into the final wfpt_node def compute_quantiles_stats(self, quantiles=(0.1, 0.3, 0.5, 0.7, 0.9)): """ compute quantiles statistic...
56,279
def cfpq_matrix( graph: MultiDiGraph, cfg: CFG, start_nodes: Set[int] = None, final_nodes: Set[int] = None, start_var: Variable = Variable("S"), ) -> Set[Tuple[int, int]]: """ Context-Free Path Querying based on Matrix Multiplication Parameters ---------- graph: MultiDiGraph ...
56,280
def test_cmaketoolchain_path_find(package, find_package): """Test with user "Hello" and also ZLIB one, to check that package ZLIB has priority over the CMake system one Also, that user cmake files in the root are accessible via CMake include() """ client = TestClient() conanfile = textwrap.dede...
56,281
def run(args): """run the gcinspector""" files = None if args.files: files = args.files.split(",") g = GCInspector(diag_dir=args.diag_dir, files=files, start=args.start, end=args.end) if args.reporter == "summary": g.print_report(interval=args.interval, top=args.top_k) elif args....
56,282
def test_recovery_tag_origin(): """ """ species = SpeciesFactory() report = ReportFactory() tagdoc_base = "25{}2" should_be = {k: v for k, v in TAG_ORIGIN_CHOICES} for k, origin in should_be.items(): tagdoc = tagdoc_base.format(k) recovery = RecoveryFactory(report=report, ...
56,283
def is_file_ro(filename: Path) -> Path: """Verifies file exists and can be open for read-only Args: filename (Path): path/filename to check """ try: with open(filename) as f: f.read() f.close() return filename except IOError as x: if x.err...
56,284
def project_create(): """View for an AJAX endpoint that creates a new project""" project = Project(name=request.form["name"]) errors = [] current_user.add_project(project, role=ProjectsUsers.ROLE_ADMIN) project.path = os.path.join(app.config["UPLOAD_DIR"], str(project.id)) project.save() os....
56,285
def filter_reg(reg: IRParam) -> Optional[Register]: """Filters a possible register object. returns None if not a register.""" if isinstance(reg, Dereference) and isinstance(reg.to, Register): return reg.to if isinstance(reg, Register): return reg return None
56,286
async def test_set_config_unique_id( opp: OpenPeerPower, component_factory: ComponentFactory ) -> None: """Test upgrading configs to use a unique id.""" person0 = new_profile_config("person0", 0) await component_factory.configure_component(profile_configs=(person0,)) config_entry = MockConfigEntry...
56,287
def get_init_data(file_name): """ Args: file_name: Returns: camera starting position, imu starting position """ init_file = INIT_PATH + file_name + '.json' init_data = read_json_file(init_file) return init_data['cam_start'], init_data['imu_start']
56,288
def get_aspect_ratio (video_source_filename): """This returns the aspect ratio of the original video. This is usualy 1.78:1(16/9) or 1.33:1(4/3). This function is very lenient. It basically guesses 16/9 whenever it cannot figure out the aspect ratio. """ cmd = "mplayer '%s' -vo png -ao null -fra...
56,289
def ot3_remote_everything_commit_id( ot3_default: Dict[str, Any], robot_set_source_type_params: Callable ) -> RuntimeComposeFileModel: """Get OT3 configured for local source and local robot source.""" return robot_set_source_type_params( robot_dict=ot3_default, source_type=SourceType.REMOTE,...
56,290
def _pull_nested_paragraphs_to_top(tree): """Flatten nested paragraphs in pre-ordered traversal Requires _retain_only_pars to be run first. Modifies input tree inplace. Parameters ---------- tree : :py:class:`lxml.etree._Element` etree element for valid NLM XML """ # Since _re...
56,291
def pick_typo(next_letter: str) -> Union[str, None]: """Picks a typo according to the next letter to type. This function uses `is_typo()` to determine wether or not there will be a typo. Plausible typos are defined in the `PLAUSIBLE_TYPOS` global variable. If `next_letter` is not a key in the ...
56,292
def _get_tag_by_name(tag_name: str, auth_id: int, db: Session): """ Returns tag data by passing the tag name Args: tag_name (str): Tag Name auth_id (int): User Id db (Session): sqlAlchemy connection object Returns: sql_object : Tag data """ return db.query(TagDB).fi...
56,293
def writeInitDnsService(outfile, dnsDiff, state): """ Specify the initial state a DHCP service in the new configuration file, depending on how it has changed compared to the old config (diff) Keyword arguments: outfile -- file handle pointing to the problem file iface -- dictionary lis...
56,294
def sshconnect_ex1(ssh: SSH): """ SSH example using :class:`ssh2.SSHConnect` with SSH configuration file (:code:`~/.ssh/config`). """ return ssh.execute("ls -l")
56,295
def make_probe(x_com, y_com, z_com, type, target_id): """Function to make a new probe""" new_probe = Probe() new_probe.x_com = x_com new_probe.y_com = y_com new_probe.z_com = z_com new_probe.type = type new_probe.target_id = Target.objects.get(pk=target_id) new_probe.save()
56,296
def main(): """Main Entrypoint"""
56,297
def list_org_inner_pub_repos(org_id, username, start=None, limit=None): """ List org inner pub repos, which can be access by all org members. """ try: shared_repos = seafserv_threaded_rpc.list_org_inner_pub_repos(org_id) except SearpcError: shared_repos = [] for repo in shared_r...
56,298
def select_special_student(sql_special): """ 特殊sql语句的查询 并将其结果封装为Student类型的列表 :param sql_special: 特殊的sql条件 :return: list(Student) """ if sql_special is None: return None connection = sqlite3.connect(r'sqlite/student_system.db') cursor = connection.cursor() # 这里使用了sql拼接,可能会存在s...
56,299