content
stringlengths
22
815k
id
int64
0
4.91M
def desktop_extra_assigner(self, user): """Assign the extra packages name of the selected desktop. Arguments --------- user: "Dictionary containing user's answers" Returns ------- "String containing question for the desktop extras" """ choice = ['Gnome extra', ...
5,311,900
def test_sort_2(): """a -> b""" graph = DiGraph(nodes=[B, A], edges=[(A, B)]) assert set(graph.nodes_names_map.keys()) == {"b", "a"} assert graph.edges_names == [("a", "b")] graph.sorting() assert graph.sorted_nodes_names == ["a", "b"]
5,311,901
def _get_openmm_parameters( force: openmm.Force, ) -> Dict[Tuple[int, ...], List[Tuple[unit.Quantity, ...]]]: """Returns the parameters stored in a given force. Args: force: The force to retrieve the parameters from. Returns: A dictionary of the retrieved parameters where each key is a...
5,311,902
def create_scene(info, color="cpk", scale=1.0, show_bonds=False): """Create a fresnel.Scene object. Adds geometries for particles, bonds, and box (or boundingbox). Parameters ---------- info : list List containing N, types, typeids, positions, N_bonds, bonds, box color : str, default "...
5,311,903
def crawl_malware_domains(url): """ This function crawls the malware domain indicator and returns all the dataset links to be downloaded and scraped later. @param url (string) url of the indicator web page @return """ print('Crawling site: ', url) downloader ...
5,311,904
def ip_address_middleware(get_response): """A Middleware to attach the IP Address and if its Routable to the request object. """ if asyncio.iscoroutinefunction(get_response): async def middleware(request): client_ip, is_routable = get_client_ip(request) request.client_ip...
5,311,905
def parse_datetime(datetime_str: Text) -> datetime.datetime: """ form string parse datetime """ for str_format in cfg.datetime_str_formats: try: datetime_object = datetime.datetime.strptime(datetime_str, str_format) return datetime_object except ValueError: co...
5,311,906
def time_nifti_to_numpy(N_TRIALS): """ Times how fast a framework can read a nifti file and convert it to numpy """ datadir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data') img_paths = [] for dtype in ['CHAR', 'DOUBLE', 'FLOAT', 'SHORT', 'UNSIGNEDCHAR', 'UN...
5,311,907
def get_gpu(): """Returns video device as listed by WMI. Not cached as the GPU driver may change underneat. """ wbem = _get_wmi_wbem() if not wbem: return None, None _, pythoncom = _get_win32com() dimensions = set() state = set() # https://msdn.microsoft.com/library/aa394512.aspx try: for ...
5,311,908
def findall(node, filter_=None, stop=None, maxlevel=None, mincount=None, maxcount=None): """ Search nodes matching `filter_` but stop at `maxlevel` or `stop`. Return tuple with matching nodes. Args: node: top node, start searching. Keyword Args: filter_: function called with every...
5,311,909
def mise_a_jour(): """ Met à jour la fenêtre. Les dessins ne sont affichés qu'après l'appel à cette fonction. """ global __canevas if __canevas is None: raise FenetreNonCree( "La fenêtre n'a pas été crée avec la fonction \"cree_fenetre\".") __canevas.update()
5,311,910
def zmap_time_to_datetime(year=None, month=None, day=None, hour=None, minute=None, second=None): """ Converts time in ZMAP format into python datetime object Returns: datetime object """ pass
5,311,911
def test_get_doc_types(doc: Doc) -> None: """Returns doc match types.""" doc[0]._.spaczz_ratio = 100 doc[1]._.spaczz_counts = (0, 0, 0) doc[2]._.spaczz_details = 1 assert doc._.spaczz_types == {"fuzzy", "regex", "token"}
5,311,912
def concat( objs: Union[ Iterable[FrameOrSeriesUnion], Mapping[Optional[Hashable], FrameOrSeriesUnion] ], axis=0, join="outer", ignore_index: bool = False, keys=None, levels=None, names=None, verify_integrity: bool = False, sort: bool = False, copy: bool = True, ) -> ...
5,311,913
def test_fold_effect_errors(): """ When one of the effects in the folding list fails, a FoldError is raised with the accumulator so far. """ effs = [Effect('a'), Effect(Error(ZeroDivisionError('foo'))), Effect('c')] dispatcher = [('a', lambda i: 'Ei')] eff = fold_effect(operator.add, 'Nil'...
5,311,914
def create_hash(): """ Creates a unique hash for each URL. :return: Hash """ _hash = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8)) if UrlShortenModel.find_by_hash(_hash): create_hash() return _hash
5,311,915
def str_or_list_like(x): """Determine if x is list-list (list, tuple) using duck-typing. Here is a set of Attributes for different classes | x | type(x) | x.strip | x.__getitem__ | x.__iter__ | | aa | <class 'str'> | True | True ...
5,311,916
def test_connect_encoder(dictionary_data, encoded_dictionary_data): """ Tests the custom connect encoder :param dictionary_data: The fixture used as the encoding input :param encoded_dictionary_data: The fixture used as the expected encoding result """ encoder = ConnectEncoder() actual_value...
5,311,917
def acoustics(solver_type='classic',iplot=True,htmlplot=False,outdir='./_output',problem='figure 9.4'): """ This example solves the 1-dimensional variable-coefficient acoustics equations in a medium with a single interface. """ from numpy import sqrt, abs import pyclaw if solver_type=='cla...
5,311,918
def get_carrier_gateway(carrier_gateway_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetCarrierGatewayResult: """ An example resource schema demonstrating some basic constructs and validation rules. :param str carrier_gateway_id: The ID of the ...
5,311,919
def _bootstrap_dm(ids, dm, new_names=None): """Makes a bootstrapped distance matrix Parameters ---------- ids: array-like A list of ids in the distance matrix. These do not have to be unique. dm : DistanceMatrix The distance matrix object to resample. new_names: array_li...
5,311,920
def ai(listAI, listHuman, list_all): """ AI计算落子位置 """ if len(listHuman) == 0: next_point[0] = 7 next_point[1] = 7 else: #listAI = listai #listHuman = listhuman for i in range(len(listAI)): listAIAndHuman.append(listAI[i]) for i in range(len(listHuman)): ...
5,311,921
def readprobes(path, probes_name="probes", time_name="0", name="U"): """read the data contained in the force file . create the forces variables in the Forcesfile object Args: path: str\n probes_name: str\n time_name: str ('latestTime' and 'mergeTime' are supported)\n name: s...
5,311,922
def list_as_range_strings(values): """ Format a list of single-range strings from a list of values; sorts input. :param values: :return: """ values.sort() # make sure numbers are consecutive value_groups = itertools.groupby(values, lambda n, c=itertools.count(): n - next(c)) return [lis...
5,311,923
def squared_distance(v: Vector, w: Vector) -> float: """Computes (v_1 - w_1) ** 2 + ... + (v_n - w_n) ** 2""" return sum_of_squares(subtract(v, w))
5,311,924
def fp2tan(xfp, yfp): """ Convert focal plane to tangent plane coordinates Args: xfp, yfp: CS5 focal plane coordinates in mm return xtan, ytan where xtan=sin(theta)*cos(phi), ytan=sin(theta)*sin(phi) """ #- phi=0 aligned with +xtan = -RA = +HA = +xfp phi = np.arctan2(yfp, xfp) ...
5,311,925
def bounding_box(fixtures, pose): """Get the axis aligned bounding box of the fixtures Args: fixtures (iterable): an iterable containing the fixtures to bound pose (tuple): an (x, y, theta) tuple. All fixtures will be transformed by this pose before the bounding box is c...
5,311,926
async def test_update_raceclass_by_id_different_id_in_body( client: _TestClient, mocker: MockFixture, token: MockFixture, raceclass: dict ) -> None: """Should return 422 HTTPUnprocessableEntity.""" EVENT_ID = "event_id_1" RACECLASS_ID = "290e70d5-0933-4af0-bb53-1d705ba7eb95" mocker.patch( "e...
5,311,927
def main(num): """ Run the program """ print(triplets_with_sum(num))
5,311,928
def dir_key(dir_name): """ Used for sorting """ p = parse_dir(dir_name) if p is None: return 0 abits, wbits, r = p return 1000*abits + 100*wbits + int(100*r)
5,311,929
def get_impact_from_xmlfile(element): """Gets the impact value of a step/testcase/suite from the testcase.xml/testsuite.xml/project.xml file """ return TCOBJ.get_impact_from_xmlfile(element)
5,311,930
def readlist(infile): """Read each row of file as an element of the list""" with open(infile, 'r') as f: list_of_rows = [r for r in f.readlines()] return list_of_rows
5,311,931
def tg_help_handler(update, context): """Send a message when the command /help is issued.""" logger.info('/help command received in chat: %s', update.message.chat) update.message.reply_markdown( 'Find out more on [Github](https://github.com/FiveBoroughs/Twilio2Telegram)')
5,311,932
def is_indvar(expr): """ An individual variable must be a single lowercase character other than 'e', followed by zero or more digits. :param expr: str :return: bool True if expr is of the correct form """ assert isinstance(expr, string_types), "%s is not a string" % expr return INDVAR_R...
5,311,933
def test_list_token_max_length_1_nistxml_sv_iv_list_token_max_length_2_1(mode, save_output, output_format): """ Type list/token is restricted by facet maxLength with value 6. """ assert_bindings( schema="nistData/list/token/Schema+Instance/NISTSchema-SV-IV-list-token-maxLength-2.xsd", in...
5,311,934
def estimate_ringing_samples(system, max_try=100000): """Estimate filter ringing. Parameters ---------- system : tuple | ndarray A tuple of (b, a) or ndarray of second-order sections coefficients. max_try : int Approximate maximum number of samples to try. This will be chang...
5,311,935
def read_popularity(path): """ :param path: a path of popularity file. A file contains '<id>,<rank>' rows. :return: a set of popularity object ids """ ids = set() for line in open(path): try: ident = int(line.split(",", maxsplit=1)[0]) except (AttributeError, IndexErr...
5,311,936
def classify(tree, input): """classify the input using the given decision tree""" # if this is a leaf node, return its value if tree in [True, False]: return tree # otherwise find the correct subtree attribute, subtree_dict = tree subtree_key = input.get(attribute) # None if input is mi...
5,311,937
def fmt_null_obj(obj): """将空对象转为空字符串(obj) \t\t@param: obj 传入对象 """ if not __check_null(obj): return '' if type(obj) in (list, tuple): # Change 'None' to '' obj_new = __fmt_null_ListTuple(obj) elif type(obj) == dict: # Change None's value to '' obj_new = __fmt_null...
5,311,938
def email_loeschen(request): """ Dekrementiert die Anzahl der Formulare für eine E-Mail in der mitgliedBearbeitenView oder mitgliedErstellenView nach Löschen eines Formulars. Aufgaben: * Erfassen der Anzahl der E-Mails * Rechteeinschränkung: Nur angemeldete Nutzer können den Vorgang auslösen ...
5,311,939
def extendDynaForm(dynaform, dynainclude=None, dynaexclude=None, dynaproperties=None, append=False): """Extends an existing dynaform. If any of dynainclude, dynaexclude or dynaproperties are not present, they are retrieved from dynaform (if present in it's Meta class). While it is rather u...
5,311,940
def _parse_write_checkpoint(write_checkpoint): """ Returns the appropriate value of ``write_checkpoint``. """ if isinstance(write_checkpoint, bool): if not write_checkpoint: write_checkpoint = "NONE" else: write_checkpoint = "ALL" if write_checkpoint.upper() not in ("...
5,311,941
def compute_shape_features(df_samples, sig, center='trough'): """Compute shape features for each spike. Parameters --------- df_samples : pandas.DataFrame Contains cycle points locations for each spike. sig : 1d array Voltage time series. center : {'trough', 'peak'} Cent...
5,311,942
def uCSIsCyrillic(code): """Check whether the character is part of Cyrillic UCS Block """ ret = libxml2mod.xmlUCSIsCyrillic(code) return ret
5,311,943
def ping(): """ Send a ping query --- tags: - ping parameters: - in: query name: time description: timestamp required: false type: integer - in: states name: states description: states required: false type: string responses: 200: description: pong received """ ret...
5,311,944
def process_catalog_gensample(gensample_files_glob="../data/gensample_hdf5_files/test_mix_23559_10000.hdf5", json_files_glob= "../data/gensample_hdf5_files/test_mix_23559_10000.json", kernel_size=400, debug=False, model_che...
5,311,945
def names_to_usernames(names): """ Take the given list of names and convert it to usernames. "John Doe" -> "john.doe" Each name is stripped before conversion, then split by spaces. If the name contains anything except letters and spaces, raise an exception. If duplicate names or invalid char...
5,311,946
def measurement_chain_with_equipment() -> MeasurementChain: """Get a default measurement chain with attached equipment.""" source = SignalSource( "Current measurement", output_signal=Signal(signal_type="analog", units="V"), error=Error(Q_(1, "percent")), ) ad_conversion = SignalT...
5,311,947
def get_all(): """ Get All Profiles --- /api/users/profiles_all: get: summary: Get all profiles Function security: - APIKeyHeader: [] tags: - Profile responses: '200': description: Returns all profiles '400': description: Us...
5,311,948
def initialize_detection_tables(detected_table, true_table, batch_index, batch_size, blend_index): """Initialize column entries of true objects and detection catalog to their default values. This is necessary since, if either true objects or detection table is empty, then there is no match in get_detec...
5,311,949
def test_cv_file_writer_file_name_null(): """test cv dataset writer when file_name is empty string.""" with pytest.raises(Exception) as e: FileWriter("") assert str(e.value) == "[ParamValueError]: error_code: 1347686402, " \ "error_msg: Invalid parameter value." \ ...
5,311,950
def list_ipp_command(args): """Listing all Internet Presence Provider Args: args (dict): usually demisto.args() """ management_group = args.get("management_group") policies = list_ipp(management_group).get("value") outputs = list() if policies: for policy in policies: ...
5,311,951
def compose_matrix(scale=None, shear=None, angles=None, translate=None, perspective=None): """Return transformation matrix from sequence of transformations. """ M = numpy.identity(4) if perspective is not None: P = numpy.identity(4) P[3, :] = perspective[:4] M ...
5,311,952
def value_to_cpp(type_, value): """ Convert a python value into a string representing that value in C++. This is equivalent to primitive_value_to_cpp but can process arrays values as well Warning this still processes only primitive types @param type_: a ROS IDL type @type type_: builtin.str ...
5,311,953
def make_reference(x, crop_size, ref_type): """ ref_type: {'bmf', 'bt'} bmf: Ball-Mid-Frame, normalize by where the ball is at mid-frame tb: Track-Ball, normalize by where the ball is at each frame """ print('Running DataUtils:make_reference') assert(crop_size[0] % 2 == ...
5,311,954
def test_metavar_kwarg(): """Check that fields accept metavar kwarg and store on the instance.""" test_types = ( DateField, DateTimeField, DecimalField, FieldList, FloatField, IntegerField, SelectField, SelectMultipleField, StringField, ...
5,311,955
def vessel_tip_coupling_data_to_str(data_list): """A list of vessel tip data elements is converted into a string.""" s = [] for v in data_list: s.append('VesselTipData(') s.append(' p = Point(x={}, y={}, z={}),'.format(v.p.x, v.p.y, v.p.z)) s.append(' vertex_id = {},'.format(v.vert...
5,311,956
def learn_skill(entity: EntityID, skill_name: str): """ Add the skill name to the entity's knowledge component. """ if not entity_has_component(entity, Knowledge): logging.warning(f"{get_name(entity)} has no Knowledge component and cannot learn {skill_name}.") return knowledge = get...
5,311,957
def user_labels_insert(*args): """ user_labels_insert(map, key, val) -> user_labels_iterator_t Insert new (int, qstring) pair into user_labels_t. @param map (C++: user_labels_t *) @param key (C++: const int &) @param val (C++: const qstring &) """ return _ida_hexrays.user_labels_insert(*args)
5,311,958
def forced_checkout_with_faux_obstructions(sbox): """co with faux obstructions ok with --force""" # Make a local tree that partially obstructs the paths coming from the # repos but has no true differences. expected_output = make_local_tree(sbox, False, False) expected_wc = svntest.main.greek_state.copy() ...
5,311,959
def RequestReasonInterceptor(): """Returns an interceptor that adds a request reason header.""" return HeaderAdderInterceptor(_GetRequestReasonHeader)
5,311,960
def db_jdbc_url(db: object) -> str: """Returns a JDBC url for a mara db alias""" raise NotImplementedError(f'Please implement jdbc_url for type "{db.__class__.__name__}"')
5,311,961
def mem_usage_pd(pd_obj: Union[pd.DataFrame, pd.Series], index: bool = True, deep: bool = True, details: bool = True) -> Dict[str, Union[str, Set[Any]]]: """ Calculate the memory usage of a pandas object. If `details`, returns a dictionary with the memory usage and type of each column ...
5,311,962
def LF_DG_METHOD_DESC(c): """ This label function is designed to look for phrases that imply a sentence is description an experimental design """ #TODO FIX for words that change the sentence menaing from methods to results if "we found" in get_tagged_text(c): return 0 if re.search(...
5,311,963
def gumbel_binary(theta, temperature=0.5, hard=False): """theta is a vector of unnormalized probabilities Returns: A vector that becomes binary as the temperature --> 0 """ u = Variable(torch.rand(theta.size())) z = theta + torch.log(u / (1 - u)) a = F.sigmoid(z / temperature) if ha...
5,311,964
def cmdFileOutput(q=1,c="uint",ca=1,o="string",s="uint"): """ http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/cmdFileOutput.html ----------------------------------------- cmdFileOutput is undoable, queryable, and NOT editable. This command will open a text file to receive all of the c...
5,311,965
def price_quantity_us_number(price): """Extract the numeric quantity of the price, assuming the number uses dot for decimal and comma for thousands, etc.""" p = re.sub('[^0-9.]', '', price.strip()) return p
5,311,966
def read_1_word_test(dut): """ Description: * Test ID: 1 Expected Results: * """ dut.rst <= 1 dut.test_id <= 1 setup_dut(dut) ADDR = 0x00 memory = Array('B', [0] * MEM_SIZE) memory[0] = 0x10 memory[1] = 0x32 memory[2] = 0x54 memory[3] = 0x76 ...
5,311,967
def ascendTree(leafNode, prefixPath): """查找元素条件模式基: 直接修改prefixPath的值,将当前节点leafNode添加到prefixPath的末尾,然后递归添,prefixPath就是一条从treeNode(包括treeNode)到根节点(不包括根节点)的路径加其父节点。""" if leafNode.parent != None: prefixPath.append(leafNode.name) ascendTree(leafNode.parent, prefixPath)
5,311,968
def build_global_regexes() -> typing.Dict[str, typing.Pattern]: """ Returns a list where each element is a tuple of ``(label, possible_regexes)``. """ nums = r'-?\d+' ip_atom = r'(({0})|({0}:)|(:{0})|({0}:{0})|({0}-{0})|(:))?'.format(nums) ip = r'^{0}(,{0})*$'.format(ip_atom) ip_qform = ...
5,311,969
def register_api(provider: str, api_dir: str = '.') -> object: """ decorator for registering api of the domain :param provider: :type provider: :param api_dir: :type api_dir: :return: :rtype: """ def generate(cls): if context['register_api']: import_str = 'f...
5,311,970
def _ratio_sample_rate(ratio): """ :param ratio: geodesic distance ratio to Euclid distance :return: value between 0.008 and 0.144 for ration 1 and 1.1 """ return 20 * (ratio - 0.98) ** 2
5,311,971
def plot_default(plots, cf, data, h, centering): """ Default plotting routine. Plots a series of figures containing height profiles from data. TODO: pass startLevel etc. to plot routine (style file?) """ logger.info('plot_default') # Initialise names out_dir, jpg_dir, plot_case_name, out_pdf...
5,311,972
def normalize_boolean(val): """Returns None if val is None, otherwise ensure value converted to boolean""" if val is None: return val else: return ensure_boolean(val)
5,311,973
def plot_moon(ax, obs_time, obs_loc): """ Put Moon on a given Axes instance """ moon = get_moon(obs_time, location=obs_loc) moon = SkyCoord(moon.ra, moon.dec, frame='gcrs').transform_to('icrs') ax.plot( [moon.ra.radian], [-moon.dec.value+45], label='Moon', linestyle='', color='ind...
5,311,974
def make_braced_expr(tokens): """Make a braced expr from a recursive, nested list of tokens.""" result = "" for e in tokens[1:-1]: if isinstance(e, list): result += "".join([getattr(t, 'value', t) for t in flatten(e)]) else: result.append(e.value) contents = ''....
5,311,975
def write_tags(f, gitpkg, since): """Writes all tags of a given package to the output file. Args: f: A :py:class:`File` ready to be written at gitpkg: A pointer to the gitlab package object since: Starting date as a datetime object """ tags = gitpkg.tags.list() # sort tags...
5,311,976
def basic_stats(G, area=None, clean_intersects=False, tolerance=15, circuity_dist="gc"): """ Calculate basic descriptive metric and topological stats for a graph. For an unprojected lat-lng graph, tolerance and graph units should be in degrees, and circuity_dist should be 'gc'. For a projected graph, ...
5,311,977
def trip_finder(hand): """ Takes a 5-card hand, concats, only takes ranks If we get 3 of a kind only, returns list: [6, trip rank, 0, 0, 0, 0] """ cards = ''.join(hand)[::2] if Counter(cards).most_common(1)[0][1] == 3: if Counter(cards).most_common(2)[1][1] == 1: return [6, Counter(cards).most_common(1)[0][...
5,311,978
def crossfadein(clip, duration): """ Makes the clip appear progressively, over ``duration`` seconds. Only works when the clip is included in a CompositeVideoClip. """ newclip = clip.copy() newclip.mask = clip.mask.fx(fadein, duration) return newclip
5,311,979
def python_android_patch() -> None: """Patches Python to prep for building for Android.""" import os from efrotools import pybuild os.chdir(sys.argv[2]) pybuild.android_patch()
5,311,980
def list_associated_stacks(FleetName=None, NextToken=None): """ Lists all stacks to which the specified fleet is associated. See also: AWS API Documentation :example: response = client.list_associated_stacks( FleetName='string', NextToken='string' ) :type Flee...
5,311,981
def get_feats(model, loader, logger, opt): """Obtain features and labels for all samples in data loader using current model. """ batch_time = AverageMeterV2('Time', ':6.3f') progress = ProgressMeter( len(loader), [batch_time], prefix='Test: ') # switch to evaluate mode ...
5,311,982
def match(*args, verbose=True, threshold=0.036*u.arcsec): """ Find sources that match up between any number of dendrocat objects. Parameters ---------- *args : `~dendrocat.Radiosource`, `~dendrocat.Mastercatalog`, or `~astropy.table.Table` object A catalog with which to compare radio sourc...
5,311,983
def mux_mkv (video_final_filename, video_transcoded_filename, audio_compressed_filename, verbose_flag=0, dry_run_flag=0): """This is depricated.""" cmd = 'mkvmerge -o %s --noaudio %s %s' % (video_final_filename, video_transcoded_filename, audio_compressed_filename) if verbose_flag: print cmd if not dry_...
5,311,984
def tray(debug): """ Launch pype tray. Default action of pype command is to launch tray widget to control basic aspects of pype. See documentation for more information. Running pype with `--debug` will result in lot of information useful for debugging to be shown in console. """ PypeLa...
5,311,985
def show_user(func): """Register a function to be displayed to the user as an option""" global USER_FUNCTIONS try: key = re.search(r'\[(.+?)\]', func.__doc__).group(1) except AttributeError as e: key = func.__name__ print(e) USER_FUNCTIONS[key] = func retur...
5,311,986
def _StoreMetadataToFile(payload_dir, metadata_obj): """Stores metadata object into the metadata_file of the payload_dir""" file_dict = {SHA1_ATTR: metadata_obj.sha1, SHA256_ATTR: metadata_obj.sha256, SIZE_ATTR: metadata_obj.size, ISDELTA_ATTR: metadata_obj.is_...
5,311,987
def run_proc(data_dir, img_list, name, start_idx, end_idx): """Handle one mp process.""" print( "Run child process %s (%s) start:%d end: %d" % (name, os.getpid(), start_idx, end_idx) ) download_images(data_dir, img_list, name, start_idx, end_idx) print("Run child process %s done" % (...
5,311,988
def check_balancing_time_gran(param_name, granmap, entity, comp='coarser', find_EC_=lambda x, y: y[-1]): """check if given granularity map specifies granularity appropriately as specified by c...
5,311,989
def plot_integer_part(xs, ns, alpha, show=True): """Plot the integer part of real numbers mod alpha.""" fig = plt.figure() ax = plt.gca() xmin, xmax = alpha * (xs[0] // alpha), alpha * (xs[-1] // alpha) + alpha newxticks = np.linspace(xmin, xmax, int((xmax - xmin) // alpha) + 1) ax.xaxis.set_ma...
5,311,990
def array_to_sentence(vocab_dict, array: np.array, cut_at_eos=True): """ Converts an array of IDs to a sentence, optionally cutting the result off at the end-of-sequence token. :param array: 1D array containing indices :param cut_at_eos: cut the decoded sentences at the first <eos> :return: lis...
5,311,991
def make_time_scheme(dt, trend): """ Implémentation d'un schéma de RK4 sous forme de réseau de neurones """ import keras state = keras.layers.Input(shape = trend.input_shape[1:]) # k1 k1 = trend(state) # k2 _tmp_1 = keras.layers.Lambda(lambda x : 0.5*dt*x)(k1) input_k2 = kera...
5,311,992
def print_parameters(opt): """ Generate a string with the options pretty-printed (used in the --verbose mode). """ return str(cg.ParamBlock(opt, ''))
5,311,993
def test_atom_creation() -> None: """Test atom creation related operations and properties""" relation = R.my_atom assert len(relation.terms) == 0 assert isinstance(relation, BaseAtom) relation = relation("a", "b") assert len(relation.terms) == 2 assert isinstance(relation, BaseAtom) re...
5,311,994
def read_scores(scores_dir, targets): """ Return a pandas DataFrame containing scores of all decoys for all targets in <targets>. Search in <scores_dir> for the label files. """ frames = [] for target in targets: df = pd.read_csv(os.path.join(scores_dir, '{:}.dat'.format(target)), ...
5,311,995
def compute_regularizer_fft(n, weight_tv, weight_l2): """Precompute 2D filter regularizer (total variation + L2) in Fourier domain. This function implements w^2 in eq. 23 of the paper: Fast Fourier Color Constancy, Barron and Tsai, CVPR 2017 https://arxiv.org/abs/1611.07596 Args: n: specifies the square...
5,311,996
def put(program, tag, *urls): """Usage: tag [url ...] Put the urls[s] to the given tag. Urls may be quoted whitespace-separated lists of replicas. """ from disco.util import listify program.ddfs.put(tag, [listify(i) for i in program.input(*urls)])
5,311,997
async def read_data(*, file_path: Path) -> Optional[Box]: """Return the data read from file_path.""" if not file_path.is_file(): return None lock = FileLock(f"{file_path.as_posix()}.lck") with lock.acquire(): async with aiofiles.open(file_path) as fh: # type: ignore raw_data...
5,311,998
def savefacedata(request): """Save face data""" if request.method == "GET": return render(request, "savefacedata.html", {"form": FaceDataForm()}) else: try: fd = get_object_or_404(FaceData, user=request.user) form = FaceDataForm(request.POST, request.FILES, ins...
5,311,999