content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def terms_documents_matrix_ticcl_frequency(in_files): """Returns a terms document matrix and related objects of a corpus A terms document matrix contains frequencies of wordforms, with wordforms along one matrix axis (columns) and documents along the other (rows). Inputs: in_files: list of tic...
25e6cf8ca1696ebb1d5d7f72ddd90fe091e22030
8,032
def cvt_continue_stmt(node: pytree.Base, ctx: Ctx) -> ast_cooked.Base: """continue_stmt: 'continue'""" #-# Continue assert ctx.is_REF, [node] return ast_cooked.ContinueStmt()
1eefd660e9023aa69957cf1004369d6495048437
8,033
def nth_even(n): """Function I wrote that returns the nth even number.""" return (n * 2) - 2
26e1465a039352917647ae650d653ed9842db7f6
8,034
def _has__of__(obj): """Check whether an object has an __of__ method for returning itself in the context of a container.""" # It is necessary to check both the type (or we get into cycles) # as well as the presence of the method (or mixins of Base pre- or # post-class-creation as done in, e.g., ...
638b6ed823acf2a46ae5a5cda6d3565fad498364
8,035
def grayscale(img): """ Applies the Grayscale transform This will return an image with only one color channel but NOTE: to see the returned image as grayscale (assuming your grayscaled image is called 'gray') you should call plt.imshow(gray, cmap='gray') """ return cv2.cvtColor(img, cv2...
3c3b0508850c5cdaf2617ed37c6f5eea79be64d0
8,036
def get_pageinfo(response, tracktype='recenttracks'): """Check how many pages of tracks the user have.""" xmlpage = ET.fromstring(response) totalpages = xmlpage.find(tracktype).attrib.get('totalPages') return int(totalpages)
ed5c05bcc648d4a22c5f1b51b196743bf6883dff
8,037
def MIN(*args): """Return the minimum of a range or list of Number or datetime""" return _group_function(min, *args)
044d1d433901f6ed3308aad711a6bf7eca4e2301
8,038
def GF(order, irreducible_poly=None, primitive_element=None, verify_irreducible=True, verify_primitive=True, mode="auto", target="cpu"): """ Factory function to construct a Galois field array class of type :math:`\\mathrm{GF}(p^m)`. The created class will be a subclass of :obj:`galois.FieldArray` with meta...
d09dea199559aad111e6aa30a2c391da9ae6b551
8,039
import typing def remove_fields_with_value_none(fields: typing.Dict) -> typing.Dict: """ Remove keys whose value is none :param fields: the fields to clean :return: a copy of fields, without the none values """ fields = dict((key, value) for key, value in fields.items() if va...
22d7ac2a77248809c691bdb98f5f6ebaaf6d4f2b
8,040
def make_values(params, point): #240 (line num in coconut source) """Return a dictionary with the values replaced by the values in point, where point is a list of the values corresponding to the sorted params.""" #242 (line num in coconut source) values = {} #243 (line num in coconut source) for i, k...
8287b49e54cb08802350a3a15805dc20def10ece
8,041
def elbow_method(data): """ This function will compute elbow method and generate elbow visualization :param data: 2 columns dataframe for cluster analysis :return: Plotly Figures """ distortions = [] K = range(1, 10) for k in K: elbow_kmean = model_kmeans(data, k) distor...
5420ce252f8a89ae3540ce37cbfd4f31f0cbe93e
8,042
from typing import Callable def sa_middleware(key: str = DEFAULT_KEY) -> 'Callable': """ SQLAlchemy asynchronous middleware factory. """ @middleware async def sa_middleware_(request: 'Request', handler: 'Callable')\ -> 'StreamResponse': if key in request: raise DuplicateReq...
df4da137e45fcaa2962626a4f3676d9f7b9ecce9
8,043
def dice_loss(y_true, y_pred): """ dice_loss """ smooth = 1. intersection = K.sum(K.abs(y_true * y_pred), axis=-1) dice_coef = (2. * intersection + smooth) / (K.sum(K.square(y_true),-1) + \ K.sum(K.square(y_pred),-1) + smooth) return 1 - dice_coef
863f69071375f37fed3c8910e52c1ffbda14cd71
8,044
def webdriver_init(mobile): """ Initialize a mobile/desktop web driver. This initialize a web driver with a default user agent regarding the mobile demand. Default uer agents are defined by MOBILE_USER_AGENT and DESKTOP_USER_AGENT. :param mobile: The mobile flag :type conn:...
49215bfd5363b9e7e82329b42b97ad04402b7edb
8,045
import hashlib def calculate_file_hash(f, alg, buf_size): """BUF_SIZE - 64 kb need for large file""" h = hashlib.new(alg) for chunk in iter(lambda: f.read(buf_size), b""): h.update(chunk) return h.hexdigest()
6361ef8f18f5ae66e1d51503426c77f7505e10be
8,046
def update(A, B, DA, DB, f, k, delta_t): """Apply the Gray-Scott update formula""" # compute the diffusion part of the update diff_A = DA * apply_laplacian(A) diff_B = DB * apply_laplacian(B) # Apply chemical reaction reaction = A*B**2 diff_A -= reaction diff_B += reaction # A...
75c2004ea089d5b3a9f4ec71fc27510d1c0dc5c0
8,047
import typing import hashlib def sha512(data: typing.Optional[bytes] = None): """Returns a sha512 hash object; optionally initialized with a string.""" if data is None: return hashlib.sha512() return hashlib.sha512(data)
067fffc4c006d9c46e5037b07b86149ac15bb573
8,048
def get_entropy_of_maxes(): """ Specialized code for retrieving guesses and confidence of largest model of each type from the images giving largest entropy. :return: dict containing the models predictions and confidence, as well as the correct label under "y". """ high_entropy_list = get_high_en...
9a43ac44a61776d25d3b46a7fb733d95720e3beb
8,050
from typing import List from typing import Dict from typing import Any def get_all_links() -> List[Dict[str, Any]]: """Returns all links as an iterator""" return get_entire_collection(LINKS_COLLECTION)
1bda0ac68f778c77914163dd7855491cc04a2c97
8,051
def agent(states, actions): """ creating a DNN using keras """ model = Sequential() model.add(Flatten(input_shape=(1, states))) model.add(Dense(24, activation='relu')) model.add(Dense(24, activation='relu')) model.add(Dense(24, activation='relu')) model.add(Dense(actions, activation=...
b9f8415955cc1b01dbe46b94dd84ab3daa6811c2
8,052
def get_package_nvr_from_spec(spec_file): """ Return a list of the NVR required for a given spec file :param spec_file: The path to a spec file :type spec_file: str :return: list of nevra that should be built for that spec file :rtype: str """ # Get the dep name & version spec = rpm....
9f8c5e5451d9b7fd3721881645688781b221e08d
8,053
def rbo_ext(S, T, p): """Extrapolated RBO value as defined in equation (30). Implementation handles uneven lists but not ties. """ if len(S) > len(T): L, S = S, T else: L, S = T, S l, s = len(L), len(S) xl = overlap(L, S, l) xs = overlap(L, S, s) sum1 = sum(overlap(...
367c979f8ece073e86e9fdc48a26bb393f0236be
8,054
def index(request): """ View of index page """ title = _("Home") posts = Post.objects.all().order_by('-timestamp')[:5] return render(request, 'dashboard/index.html', locals())
a152bfad756be809c56e6dc203cb7cf9d29f4868
8,055
def incremental_str_maker(str_format='{:03.f}'): """Make a function that will produce a (incrementally) new string at every call.""" i = 0 def mk_next_str(): nonlocal i i += 1 return str_format.format(i) return mk_next_str
41ce6e7d7ba69922f92e73ee516e9c09fdbe0713
8,056
def get_time_slider_range(highlighted=True, withinHighlighted=True, highlightedOnly=False): """Return the time range from Maya's time slider. Arguments: highlighted (bool): When True if will return a selected frame range (if there's any se...
f05ca2bfec8bcfb41be9a0fa83a724d180dc545f
8,057
def update_IW(hyp_D_prev, xikk, xk, Pik_old): """ Do an update of Norm-IW conjugate in an exponential form. """ suff_D = get_suff_IW_conj(xikk, xk, Pik_old) hyp_D = hyp_D_prev + suff_D Dik = get_E_IW_hyp(hyp_D) return Dik, hyp_D
d787edf13e18cdbc1c6ff3a65168f32ff8c28b1f
8,058
def compute_state(observations, configuration): """ :param observations: :param configuration: :return StateTensor: """ StateTensorType = configuration.STATE_TYPE return StateTensorType([observations])
44a08caa02137438359c4cd764fff1700b6252b2
8,059
def supports_transfer_syntax(transfer_syntax: pydicom.uid.UID) -> bool: """Return ``True`` if the handler supports the `transfer_syntax`. Parameters ---------- transfer_syntax : uid.UID The Transfer Syntax UID of the *Pixel Data* that is to be used with the handler. """ return t...
65f85a47afc5002ed33e4ad787317d67b4dab218
8,060
def enhance_user(user, json_safe=False): """ Adds computed attributes to AD user results Args: user: A dictionary of user attributes json_safe: If true, converts binary data into base64, And datetimes into human-readable strings Returns: An enhanced dictionary of user at...
4b6fd08440c9c92d074e639f803b242f044f2ea3
8,061
from datetime import datetime import random def create_data(namespace_id, ocs_client): """Creates sample data for the script to use""" double_type = SdsType(id='doubleType', sdsTypeCode=SdsTypeCode.Double) datetime_type = SdsType( id='dateTimeType', sdsTypeCode=SdsTypeCode.DateTime) pressure...
c0b01e36e350d152d758a744735688d15826be06
8,062
def enhanced_feature_extractor_digit(datum): """Feature extraction playground for digits. You should return a util.Counter() of features for this datum (datum is of type samples.Datum). ## DESCRIBE YOUR ENHANCED FEATURES HERE... """ features = basic_feature_extractor_digit(datum) "*** YOU...
b98ef2caf6b51176fae18ae36dd0c316ab2d8ee7
8,063
from typing import Union def linear_resample(x: Union[ivy.Array, ivy.NativeArray], num_samples: int, axis: int = -1, f: ivy.Framework = None)\ -> Union[ivy.Array, ivy.NativeArray]: """ Performs linear re-sampling on input image. :param x: Input array :type x: array :param num_samples: The...
bd6b54ee5cafe5409eb6aa47da57db2ad3b7fff2
8,064
def update_milestones(repo, username=None, namespace=None): """Update the milestones of a project.""" repo = flask.g.repo form = pagure.forms.ConfirmationForm() error = False if form.validate_on_submit(): redirect = flask.request.args.get("from") milestones = flask.request.form.ge...
4869d70a4d8bd85436639dd3214f208822f7241b
8,066
def trapezoid_vectors(t, depth, big_t, little_t): """Trapezoid shape, in the form of vectors, for model. Parameters ---------- t : float Vector of independent values to evaluate trapezoid model. depth : float Depth of trapezoid. big_t : float Full trapezoid duration. ...
759c7cf946bf9ea998644bea9b28f46dea5a6e55
8,068
def get_rules(clf, class_names, feature_names): """ Extracts the rules from a decision tree classifier. The keyword arguments correspond to the objects returned by tree.build_tree. Keyword arguments: clf: A sklearn.tree.DecisionTreeClassifier. class_names: A list(str) containing the class n...
a4d9bc1964553d384f1c795e2ad4834a532ddbba
8,069
def file_parser(localpath = None, url = None, sep = " ", delimiter = "\t"): """ DOCSTRING: INPUT: > 'localpath' : String (str). Ideally expects a local object with a read() method (such as a file handle or StringIO). By default, 'localpath=dummy_file' parameter can be passed to auto-detect and parse...
a1f8cc5fceffdc2a20f745afbce44645634221bd
8,071
def node_to_truncated_gr(node, bin_width=0.1): """ Parses truncated GR node to an instance of the :class: openquake.hazardlib.mfd.truncated_gr.TruncatedGRMFD """ # Parse to float dictionary if not all([node.attrib[key] for key in ["minMag", "maxMag", "aValue", "bValue"]]): ...
0fd81e01140ec7b1a38f28c527139b61cc1c3a92
8,074
def nt(node, tag): """ returns text of the tag or None if the tag does not exist """ if node.find(tag) is not None and node.find(tag).text is not None: return node.find(tag).text else: return None
7ca5f83cf18f918f594374fa2aa875415238eef6
8,075
def set_user_favorites(username, **_): """ Sets the user's Favorites Variables: username => Name of the user you want to set the favorites for Arguments: None Data Block: { # Dictionary of "alert": [ "<name_of_query>": # Named queries ...
391ff8e9736bb2baddbf388c5a203cf9d2d7bdcc
8,076
def delete_token(token_id): """Revoke a specific token in the application auth database. :type token_id: str :param token_id: Token identifier :rtype: tuple :return: None, status code """ client_data = g.client_data if not valid_token_id(token_id): raise Malforme...
204f4ae2c0dc7c704f05baa86930bc7962d1b639
8,077
from typing import Optional async def update_country(identifier: Optional[str] = None, name: Optional[str] = None, capital: Optional[str] = None, country: UpdateCountryModel = Body(...), current_user: AdminModel = Depends(get_current_user)): """ Update a country by name or capital nam...
7805ca1d8e99e21b2558258e890f11fb4f697df9
8,078
def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ """method-1 time O(n), traverse all, get rest""" for i in range(len(nums)): res = target - nums[i] if res in nums: return [i, nums.index(res)] else: ret...
8c5cd095c7800fa5da698dffa0d76d3c00a8a3c1
8,079
from miniworld.util import ConcurrencyUtil def wait_until_uds_reachable(uds_path, return_sock=False): """ Wait until the unix domain socket at `uds_path` is reachable. Returns ------- socket.socket """ sock = ConcurrencyUtil.wait_until_fun_returns_true(lambda x: x[0] is True, uds_reachable, ...
574053ed1b4ccacda37bec58740ad497e690746a
8,082
def get_relation_count_df( dataset: Dataset, merge_subsets: bool = True, add_labels: bool = True, ) -> pd.DataFrame: """Create a dataframe with relation counts. :param dataset: The dataset. :param add_labels: Whether to add relation labels to the dataframe. :param merge_subs...
a15c22d0790c346cac3842f84a80ee7c27c4471a
8,083
def get_tests(run_id): """ Ручка для получения информации о тест (из тест-рана) Выходящий параметр: test_id """ client = APIClient('https://testrail.homecred.it') client.user = 'dmitriy.zverev@homecredit.ru' client.password = 'Qwerty_22' tests = client.send_get('get_tests/%s' % run_id) ...
a188e8a04dc72e485d5c519c09fcdbd8f2f18f31
8,084
def other(player): """Return the other player, for a player PLAYER numbered 0 or 1. >>> other(0) 1 >>> other(1) 0 """ return 1 - player
08503c35276cf86efa15631bb6b893d72cbae4d5
8,086
def _explored_parameters_in_group(traj, group_node): """Checks if one the parameters in `group_node` is explored. :param traj: Trajectory container :param group_node: Group node :return: `True` or `False` """ explored = False for param in traj.f_get_explored_parameters(): if pa...
71cbafbad0dcc3fa9294c0bede5f6a09941d452b
8,087
def _execute(query, data=None, config_file=DEFAULT_CONFIG_FILE): """Execute SQL query on a postgres db""" # Connect to an existing database. postgres_db_credentials = postgres_db(config_file) conn = psycopg2.connect(dbname=postgres_db_credentials["dbname"], ...
84884b6a0902ce7fe964b145f3124a1699f72453
8,088
from pathlib import Path def _construct_out_filename(fname, group_name): """ Construct a specifically formatted output filename. The vrt will be placed adjacent to the HDF5 file, as such write access is required. """ basedir = fname.absolute().parent basename = fname.with_suffix('.vrt').na...
117bb8470ab65f0b9fb11bb3151ae653e5e28d23
8,089
import json def _deposit_need_factory(name, **kwargs): """Generate a JSON argument string from the given keyword arguments. The JSON string is always generated the same way so that the resulting Need is equal to any other Need generated with the same name and kwargs. """ if kwargs: for ke...
9c8813f0be657b51a787d9badd2f677aca84a002
8,090
def not_equal(version1, version2): """ Evaluates the expression: version1 != version2. :type version1: str :type version2: str :rtype: bool """ return compare(version1, '!=', version2)
5dab948ec2a3eb8d3cb68fcd9887aedb394757df
8,091
def get_sp_list(): """ Gets all tickers from S&P 500 """ bs = get_soup('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies') sp_companies = bs.find_all('a', class_="external text") return sp_companies
be850de6fc787faaa05bbd3100dc82ce56cceb22
8,092
def get_params_nowcast( to, tf, i, j, path, nconst, depthrange='None', depav=False, tidecorr=tidetools.CorrTides): """This function loads all the data between the start and the end date that contains hourly velocities in the netCDF4 nowcast files in the specified dept...
4cf44961da3109593176476d8e4092a2c05b7a18
8,093
def convert_size(size): """ Helper function to convert ISPMan sizes to readable units. """ return number_to_human_size(int(size)*1024)
a28c8332d8f44071409436f4ec7e844a58837f49
8,094
def get_suppressed_output( detections, filter_id: int, iou: float, confidence: float, ) -> tuple: """Filters detections based on the intersection of union theory. :param detections: The tensorflow prediction output. :param filter_id: The specific class to be filtered. :param iou: The int...
b6a294611ec22fd48a7a72e51e66e43732c1d3f7
8,095
def tf_nan_func(func, **kwargs): """ takes function with X as input parameter and applies function only on finite values, helpful for tf value calculation which can not deal with nan values :param func: function call with argument X :param kwargs: other arguments for func :return: executed f...
d43e509a142bf78025d32984c9ecb0c0856e9a90
8,096
def deep_update(original, new_dict, new_keys_allowed=False, allow_new_subkey_list=None, override_all_if_type_changes=None): """Updates original dict with values from new_dict recursively. If new key is introduced in new_dict, then if new_keys_allo...
12573fd3efef4fc9d6c222ccc3ea525c131a2088
8,097
def queued_archive_jobs(): """Fetch the info about jobs waiting in the archive queue. Returns ------- jobs: dict """ jobs = pbs_jobs() return [ job for job in jobs if (job["job_state"] == "Q" and job["queue"] == "archivelong") ]
af4495f6484cf2e819655a1807a38556f62119a5
8,098
def getCustomKernelSolutionObj(kernelName, directory=globalParameters["CustomKernelDirectory"]): """Creates the Solution object for a custom kernel""" kernelConfig = getCustomKernelConfig(kernelName, directory) for k, v in kernelConfig.items(): if k != "ProblemType": checkParametersAreVa...
31cec952f3dc5afefa5a50bc8a54fe00eb3d3fe9
8,099
def _format_breed_name(name): """ Format breed name for displaying INPUT name: raw breed name, str OUTPUT name : cleaned breed name, str """ return name.split('.')[1].replace('_', ' ')
0c2680de9bd19e61d717fb84c1ce01e5095ddf35
8,101
def create_pid_redirected_error_handler(): """Creates an error handler for `PIDRedirectedError` error.""" def pid_redirected_error_handler(e): try: # Check that the source pid and the destination pid are of the same # pid_type assert e.pid.pid_type == e.destination_p...
3137c4d6447c5da9f500b3d4cd7a6a3a68325a92
8,103
def is_var_name_with_greater_than_len_n(var_name: str) -> bool: """ Given a variable name, return if this is acceptable according to the filtering heuristics. Here, we try to discard variable names like X, y, a, b etc. :param var_name: :return: """ unacceptable_names = {} if len(var_...
c4509b33cc7326c1709f526137e04a590cf3c7ad
8,104
from re import L def stacked_L(robot: RobotPlanar, q: list, q_goal: list): """ Stacks the L matrices for conviencne """ LL = [] LLinv = [] Ts_ee = robot.get_full_pose_fast_lambdify(list_to_variable_dict(q)) Ts_goal = robot.get_full_pose_fast_lambdify(list_to_variable_dict(q_goal)) fo...
a329ad79b9add95307195329b937a85cf9eeda50
8,105
from typing import Dict async def help() -> Dict: """Shows this help message.""" return { '/': help.__doc__, '/help': help.__doc__, '/registration/malaysia': format_docstring(get_latest_registration_data_malaysia.__doc__), '/registration/malaysia/latest': format_docstring(get_...
4d72c66069956c469aea1d39fd68e20454f68e40
8,106
def eliminate_arrays(clusters, template): """ Eliminate redundant expressions stored in Arrays. """ mapper = {} processed = [] for c in clusters: if not c.is_dense: processed.append(c) continue # Search for any redundant RHSs seen = {} for...
2d5a59d9d5758963e029cc102d6a123c62ed8758
8,107
def data_generator(batch_size): """ Args: dataset: Dataset name seq_length: Length of sequence batch_size: Size of batch """ vocab_size = 20000 (x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=vocab_size) x_train, y_train, x_test, y_test = tf.ragged.constan...
ed1edfd0cbeac01bd1fcad6cc1fe36a94dc006e8
8,108
from datetime import datetime def now(): """ Get current timestamp Returns: str: timestamp string """ current_time = datetime.now() str_date = current_time.strftime("%d %B %Y, %I:%M:%S %p") return str_date
4c487416fa119cae0c5310678dfd96e0f737b937
8,109
def open_mfdataset( fname, convert_to_ppb=True, mech="cb6r3_ae6_aq", var_list=None, fname_pm25=None, surf_only=False, **kwargs ): # Like WRF-chem add var list that just determines whether to calculate sums or not to speed this up. """Method to open RFFS-CMAQ dyn* netcdf files. P...
59639b4bb45d4c1306ea8ecfa1241b86247ce16b
8,110
def projection(projection_matrix: tf.Tensor, flattened_vector: tf.Tensor) -> tf.Tensor: """Projects `flattened_vector` using `projection_matrix`. Args: projection_matrix: A rank-2 Tensor that specifies the projection. flattened_vector: A flat Tensor to be projected Returns: A flat Ten...
7954247be2f3d130ac79f53e44b0509608fe85d6
8,111
def free_vars(e): """Get free variables from expression e. Parameters ---------- e: tvm.relay.Expr The input expression Returns ------- free : List[tvm.relay.Var] The list of free variables """ return _ir_pass.free_vars(e)
bfab6f5ff0ccadf8dba7af518401e6026efbcb20
8,112
def image_as_uint(im, bitdepth=None): """ Convert the given image to uint (default: uint8) If the dtype already matches the desired format, it is returned as-is. If the image is float, and all values are between 0 and 1, the values are multiplied by np.power(2.0, bitdepth). In all other situati...
a906eb7022a1823cd49bedb3858bac34e59fdf02
8,113
def unary_operator(op): """ Factory function for making unary operator methods for Factors. """ # Only negate is currently supported. valid_ops = {'-'} if op not in valid_ops: raise ValueError("Invalid unary operator %s." % op) @with_doc("Unary Operator: '%s'" % op) @with_name(u...
04bc43c2f5e84db29b7a913de35d7a366464dfda
8,114
def compute_cost_with_regularization(A3, Y, parameters, lambd): """ Implement the cost function with L2 regularization. See formula (2) above. Arguments: A3 -- post-activation, output of forward propagation, of shape (output size, number of examples) Y -- "true" labels vector, of shape (output size...
5904cab44af1768779ed983fa001876d14faeb1d
8,115
from operator import and_ def user_page(num_page=1): """Page with list of users route.""" form = SearchUserForm(request.args, meta={'csrf': False}) msg = False if form.validate(): search_by = int(request.args.get('search_by')) order_by = int(request.args.get('order_by')) search...
3acf9cc4a274de456ad5ea0ee609857f550867ee
8,117
def validate_input(data: ConfigType) -> dict[str, str] | None: """Validate the input by the user.""" try: SIAAccount.validate_account(data[CONF_ACCOUNT], data.get(CONF_ENCRYPTION_KEY)) except InvalidKeyFormatError: return {"base": "invalid_key_format"} except InvalidKeyLengthError: ...
56ced7cf0d3b02a484910b599c266e928303ddd7
8,118
import importlib def file_and_path_for_module(modulename): """Find the file and search path for `modulename`. Returns: filename: The filename of the module, or None. path: A list (possibly empty) of directories to find submodules in. """ filename = None path = [] try: ...
4e8d0edb3a5844bb3c523aed66f8eb7f0c646aaa
8,119
def hello_page(request): """Simple view to say hello. It is used to check the authentication system. """ text = "Welcome to test_project" if not request.user.is_anonymous: text = "Welcome '%s' to test_project" % request.user.username return HttpResponse(text, content_type='text/plain')
fee98ccca3c89d1f110bc828521cbc26af004325
8,120
from typing import Dict def hash_all(bv: Binary_View) -> Dict[str, Function]: """ Iterate over every function in the binary and calculate its hash. :param bv: binary view encapsulating the binary :return: a dictionary mapping hashes to functions """ sigs = {} for function in bv.functions:...
3a3a046c9c7fe786c55d3e0d3993679f8ee71465
8,121
from typing import Union from typing import List def apply_deformation( deformation_indices: Union[List[bool], np.ndarray], bsf: np.ndarray ) -> np.ndarray: """Return Hadamard-deformed bsf at given indices.""" n = len(deformation_indices) deformed = np.zeros_like(bsf) if len(bsf.shape) == 1: ...
87e6a3403190f1139fef223d374df5f7e5f59257
8,122
def index(request): """Return the index.html file""" return render(request, 'index.html')
7ac6c9418e332aebe29a25c3954152adca3f7716
8,123
from typing import Optional from typing import Iterable from typing import Dict from typing import Type import click def parse_custom_builders(builders: Optional[Iterable[str]]) -> Dict[str, Type[AbstractBuilder]]: """ Parse the custom builders passed using the ``--builder NAME`` option on the command line. :para...
95216d12dfeacf319464b4f14be249ab3f12f10a
8,125
def construct_user_rnn_inputs(document_feature_size=10, creator_feature_size=None, user_feature_size=None, input_reward=False): """Returns user RNN inputs. Args: document_feature_size: Integer, length of document features...
cdc42e86ff7fee9a7487d05badeae1ef995a3357
8,126
def numpy_read(DATAFILE, BYTEOFFSET, NUM, PERMISSION, DTYPE): """ Read NumPy-compatible binary data. Modeled after MatSeis function read_file in util/waveread.m. """ f = open(DATAFILE, PERMISSION) f.seek(BYTEOFFSET, 0) data = np.fromfile(f, dtype=np.dtype(DTYPE), count=NUM) f.close() ...
9fc4b2de3eecefc649cb78fe7d8b545a09b8f786
8,127
def _process_pmid(s: str, sep: str = '|', prefix: str = 'pubmed:') -> str: """Filter for PubMed ids. :param s: string of PubMed ids :param sep: separator between PubMed ids :return: PubMed id """ for identifier in s.split(sep): identifier = identifier.strip() if identifier.start...
9a1fc49bf570c81f10b6b5470620d7fc0b54275e
8,128
import ast def _get_import(name, module: ast.Module): """ get from import by name """ for stm in ast.walk(module): if isinstance(stm, ast.ImportFrom): for iname in stm.names: if isinstance(iname, ast.alias): if iname.name == name: ...
bc33a882c65f7fe44d446376db3a71631629ff04
8,129
from typing import Optional from typing import Tuple def number_of_qucosa_metadata_in_elasticsearch( host: str = SLUB_ELASTICSEARCH_SERVER_URL, http_auth: Optional[Tuple[str, str]] = None, index_name: str = "fulltext_qucosa", ) -> int: """Return the number of qucosa documents currently available at th...
9e3628998f7c93d12b4855ec2d2c88278b1a5e2a
8,131
def _tuple_to_string(tup): """ Converts a tuple of pitches to a string Params: * tup (tuple): a tuple of pitch classes, like (11, 10, 5, 9, 3) Returns: * string: e.g., 'et593' """ def _convert(pitch): pitch = mod_12(pitch) if pitch not in (0, 1, 2, 3, 4, 5, 6, 7...
61ee32199b85fe5ec645887641d6b28ff701eabd
8,133
def dashboard(): """Logged in Dashboard screen.""" session["redis_test"] = "This is a session variable." return render_template( "dashboard.jinja2", title="Flask-Session Tutorial.", template="dashboard-template", current_user=current_user, body="You are now logged in!...
48472e2ad8c3b81adab98524103959a812ab9b30
8,134
def choose_top_k(scores_flat, config): """Chooses the top-k beams as successors. """ next_beam_scores, word_indices = tf.nn.top_k(scores_flat, k=config.beam_width) return next_beam_scores, word_indices
e8bbf86c8452b0b2153f591968370612986673e2
8,135
def train_valid_test_split(data, proportions='50:25:25'): """ Splits the data into 3 parts - training, validation and test sets :param proportions: proportions for the split, like 2:1:1 or 50:30:20 :param data: preprocessed data :return: X_train, Y_train, target_rtns_train, X_valid, Y_valid, target_...
b8a9d160860aea9c224b72af32ef843b43b44656
8,136
def data(*args, **kwargs): """ The HTML <data> Element links a given content with a machine-readable translation. If the content is time- or date-related, the <time> must be used. """ return el('data', *args, **kwargs)
c948ea946b29369b78fbda0564a822d7b9bb0a06
8,139
import copy def get_crops(nodules, fmt='raw', nodule_shape=(32, 64, 64), batch_size=20, share=0.5, histo=None, variance=(36, 144, 144), hu_lims=(-1000, 400), **kwargs): """ Get pipeline that performs preprocessing and crops cancerous/non-cancerous nodules in a chosen proportion. Parameters ...
51bc314a8675790f83d0b6b7276e094986317187
8,141
def get_dict_from_args(args): """Extracts a dict from task argument string.""" d = {} if args: for k,v in [p.strip().split('=') for p in args.split(',')]: d[k] = v return d
8fb05329f6119393f94215808c6ab9b3116ec759
8,142
import warnings import cupy as cp from netver.utils.cuda_code import cuda_code def multi_area_propagation_gpu(input_domain, net_model, thread_number=32): """ Propagation of the input domain through the network to obtain the OVERESTIMATION of the output bound. The process is performed applying the linear combinat...
a81aad5e05b7054c5b7fc5016941ffc6abea5948
8,143
def opensslCmsSignedDataCreate( conveyedInfoFile, cert, privateKey ): """Create a signed CMS encoded object given a conveyed-info file and base64 encode the response.""" opensslCmdArgs = [ "openssl", "cms", "-sign", "-in", conveyedInfoFile, "-signer", cert, "-inkey",...
905ddbec7c252de6169f4fdedab19e0c6818fb39
8,144
def change_app_header(uri, headers, body): """ Add Accept header for preview features of Github apps API """ headers["Accept"] = "application/vnd.github.machine-man-preview+json" return uri, headers, body
3610d1d482e057ba73a1901aed8430ff35d98f3b
8,146
def fib_fail(n: int) -> int: """doesn't work because it's missing the base case""" return fib_fail(n - 1) + fib_fail(n - 2)
6e8138b7ce330c9ab191367e3911fe8146240c25
8,147
def int2str(num, radix=10, alphabet=BASE85): """helper function for quick base conversions from integers to strings""" return NumConv(radix, alphabet).int2str(num)
6a7b6e7e090cccc20a0e0e3196e81f79cc5dabc5
8,148
def randomize_onesample(a, n_iter=10000, h_0=0, corrected=True, random_seed=None, return_dist=False): """Nonparametric one-sample T test through randomization. On each iteration, randomly flip the signs of the values in ``a`` and test the mean against 0. If ``a`` is two-dimensi...
2af8b9592f82b14dda1f59e41663e7253eb7dbe8
8,149
from typing import Optional from typing import Dict def git_get_project( directory: str, token: Optional[str] = None, revisions: Optional[Dict[str, str]] = None ) -> BuiltInCommand: """ Create an Evergreen command to clones the tracked project and check current revision. Also, applies patches if the ...
b4cc4e3335c6c91556d02c76761082d95baee775
8,150