content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def make_bar_chart(columns, title='', x_axis=''): """Takes an array of dictionaries that have the keys 'column' and 'score'. The value for the 'column' key is a string representing the name of the column. The value for the 'score' key is an integer. """ short_names = (column['column'][:40] for...
82982324b42f93761fd6b1ad447d6c63bde9a478
3,597,548
def normalize_dataframe(df): """ Converts the total occurrences and total docs into percentages""" df.total_occurrences = df.total_occurrences * 100 / df.total_occurrences.sum() df.total_docs = df.total_docs * 100 / df.total_docs.sum() return df
081efaf887b4465bffca9ebe8d2c8cb11e32f720
3,597,549
def resnet_v1_block(scope, base_depth, num_units, stride): """Helper function for creating a resnet_v1 bottleneck block. Args: scope: The scope of the block. base_depth: The depth of the bottleneck layer for each unit. num_units: The number of units in the block. stride: The stride of t...
b23528acbdd39b45d847784262b256f13bb7275e
3,597,550
import json def load( file ): """Same as json.load() but turns unicode to ascii strings. """ return _toStr( json.load( file, object_hook=_toStr ), ignoreDicts=True )
e19603dc02a147689d55b41091bb035c0c0ee481
3,597,551
def generate_string_lines(input_field, output_field, field_data): """ :param input_field: :param output_field: :return: """ lines = [] lines.extend(utils.handle_general_case(input_field, output_field)) lines.extend(utils.handle_null_string_case(input_field, output_field)) lines.exten...
a1ad9405faee05381e355afa4f71563aee7a867e
3,597,552
def set_element(base, index, value): """Implementation of perl = on an array element""" base[index] = value return value
11940389f4f24868c5afc1e4dbbcbf370a1af102
3,597,554
def objective_function( x: list, method_name: str, gulp: ParametricGulp, lower_params: list, upper_params: list, n_cycles: int, tol_params: float, tol_cycles: int, tol_ignore: int, ) -> float: """ Create the interface between the ParametricGulp object and the scipy minimizati...
9f276271ffc2be69afa82ca2b005bdc4aa7bc8cf
3,597,555
def write(ft_handle: SpiSlaveHandle, write_data: bytes) -> int: """Write data to the transmit queue of the SPI slave device. NOTE: For some reasons, support lib will append a dummy byte (0x00) at the first byte automatically. This additional byte exists at all of the three transfer methods. Args: ...
cf3b72e64fe6cebe62a701166c6e8ef77243b748
3,597,556
def plot_bode(df, area=None, axes=None, label='', plot_func='scatter', cols=['Zmod', 'Zphz'], unit_scale='auto', invert_phase=True, invert_Zimag=True, **kw): """ Generate Bode plots. Parameters ---------- df : pandas DataFrame DataFrame of impedance data area : float, opti...
c7837902a4a1c9ec76470cf9ef0ebd6f73c7f09c
3,597,557
def download_carburator(): """Download scan of a carburator. https://www.laserdesign.com/sample-files/carburetor/ """ url = "http://3dgallery.gks.com/2012/carburator/carburator2.php" filename, _ = _retrieve_file(url, 'carburator.ply') return pyvista.read(filename)
007ffaa02ec5545d61f55c0b296f0de9b043c13c
3,597,558
def herding_relationship(x1, x2, v1, v2, phi=np.pi / 2): """Determine leader-follower relationship Args: x1: x2: v1: v2: phi: Angle between [0, pi] Returns: (bool ,bool): """ if length(v1) == 0 or length(v2) == 0: return False, False e_r...
483718be3205fead0de7daf80536fffd54dc7a1c
3,597,559
import click def command_line_input_output_file_arguments(f): """ Decorator for specifying input and output file arguments in a command """ f = click.argument("outfile", type=click.File("w"), default="-")(f) f = click.argument("infile", type=click.File("r"), default="-")(f) return f
832a527c900d6dc073f0e543d06c48696731c9d7
3,597,560
def extract_filename(string, remove_trailing_ftype=True, trailing_type_max_len=7): """ removes path (in front of the file name) and removes the file-type after the '.' (optional). returns: path & file_name""" A = string.replace("\\","/").split("/") path = ("/".join(A[:-1]))+"/" if len(path)==1: ...
17c27016a092c6f967974a1faf8dd5db7bd0c7dd
3,597,561
def create_blank_im(w, h, c=3, dtype=np.uint8): """Creates blank np image :param w: width :param h: height :param c: channels :param dtype: data type :returns (np.ndarray) """ if c == 1: im = np.zeros([h, w], dtype=np.uint8) else: im = np.zeros([h, w, c], dtype=np.uint8) return im
58049d8f9a66e033c770b16ffb63a8fe55715c70
3,597,562
import re def did_parse(did: str) -> DIDParts: """ parse a DID into it's parts. did:<method>:<id/id_hex>[/<path>[#<fragment>]] :param str did: DID to parse into seperate components :return: Dict of parts they are: method, id, id_hex, path, fragment ...
ba77586e393a51529a47093f344e8d842c0e5796
3,597,563
import collections def file_based_convert_examples_to_features( examples, label_list, max_seq_length, tokenizer, output_file, max_qa_length): """Convert a set of `InputExample`s to a TFRecord file.""" writer = tf.python_io.TFRecordWriter(output_file) for (ex_index, example) in enumerate(examples): ...
e8e95d0f9e629ecb7d0916d39c831a2bd75d781d
3,597,564
def expanded_velocities_from_horseshoe_vortices( points, back_right_vortex_vertices, front_right_vortex_vertices, front_left_vortex_vertices, back_left_vortex_vertices, strengths, ages=None, nu=0.0, ): """This function takes in a group of points, and the attributes of a group of ...
f1977d42d57b37e5c85b3b6dfb84b2517c014595
3,597,565
def verify_phone(request): """ #1.验证手机格式 #2.生成验证码 #3.保存验证码 #4.发送验证码 :param request: :return: """ phone_num = request.POST.get('phone_num') if is_phone_num(phone_num): # 生成验证码 # 发送验证码 if logics.send_verify_code(phone_num): return render_json(...
ba34eb1218009c678d6f4632618609afe49ab81b
3,597,568
from itertools import permutations from math import factorial from typing import List def iterables_and_iterators(n: int, arr: List[str], k: int) -> float: """ >>> iterables_and_iterators(4, ['a', 'a', 'c', 'd'], 2) 0.833333333333 >>> iterables_and_iterators(9, ... ['a', 'b', 'c', 'a', 'd', 'b', '...
bfa396a567d3de5d607f5f9ebfb89958923f4752
3,597,569
def shift(secret_no): """ :param secret_no: int, determine how will the alphabet letters be encrypt :return: str, encrypted alphabet letters """ new_alphabet = '' front_section = ALPHABET[:26-secret_no] back = ALPHABET[26-secret_no:] new_alphabet += back+front_section return new_alph...
a62aa9edc8dcf717ef30b1633e328d17da899051
3,597,570
import re def get_org(repourl): """ Simple function to parse the organization out of a GitHub URL """ dprint("Current repourl to search: " + repourl) # GitHub URLs can be: # http[s]://www.github.com/org/repo # or git@github.com:/org/repo pattern = re.compile(r"github.com[/...
b2922d0fc6fdeed152b624823b1851a14101e271
3,597,571
def _count(a, axis=None): """ Count the number of non-masked elements of an array. This function behaves like np.ma.count(), but is much faster for ndarrays. """ if hasattr(a, 'count'): num = a.count(axis=axis) if isinstance(num, np.ndarray) and num.ndim == 0: # In s...
c5bd3d0d13f4b6dce11a02b9021ffe6f5c1cfa37
3,597,572
import itertools def plot_confusion_matrix(cm, classes, normalize=False, title="Confusion matrix", cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ plt.imshow(cm, interpolation="nearest", cmap=cmap) plt.t...
f7f1a6682c21c030d4274cb48ae2aa27af2e7575
3,597,574
import itertools def get_scenarios(): """ Creates a list of all the combinations of transaction_costs, transaction_sizes, fall_triggers, and climb_triggers. :return: list of scenarios """ transaction_costs = [0.05] transaction_sizes = [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34...
e9dddd2b193f734afdbfa5c514c5b5047d2512af
3,597,575
def O2_dep_comp(oxygen_conc=None, depth=None): """ From Aandera Operating Manual - Oxygen Optodes Small correction for normal FOCI operations (<500m) but should be used for deep stations """ return oxygen_conc * (1.0 + (0.032 * depth) / 1000.0)
947fafe5b0fbc1e652eb1b3e14f223f73dc25368
3,597,576
async def fetch_open_orders(_stub, _client_id, _symbol): """ Get all open orders on a symbol. :param _stub: :param _client_id: :param _symbol: :return: https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#current-open-orders-user_data """ _active_orders = await _stub....
dd134d1c160a2207ad88f5f5327e2866d3587315
3,597,577
def transformLine(x, y, categUp, lineCoefs, learning_rate): """ According to the random point, update the Line """ # Check if the point is below or above the line # By reporting the point (x,y) to the equation ax+by+c : # If ax+by+c > 0 then the point is above the line, else it is below the line ...
72c44c53dc9069a81a228e8325bc182d0c540f1e
3,597,578
def try_func(inner): """Evaluate inner(), catching subclasses of CalefactionError. If nothing was caught, return (inner(), False). Otherwise, flash an appropriate error message and return (False, True). """ try: result = inner() except EVEAPIError: flash(Messages.EVE_API_ERROR, ...
ee34c239214622958469b887f1a63293d7ba1d7a
3,597,579
def profile_args(request, value): """Display a list of all arguments a user has been involved in.""" user = get_object_or_404(User, username=value) args = user.defendant_set.all() | user.plaintiff_set.all() pending = args.filter(status=0).order_by('-start_date') current = args.filter(status__ra...
d8de263796be8814e61a38389d9b8aea15c90258
3,597,580
from typing import Union def get_value( val: Union[None, bool, int, float, complex, str, bytes, tuple, list, dict, set] ) -> Union[None, bool, int, float, complex, str, bytes, tuple, list, dict, set]: """ Returns the number from a literal value if the value represents either an integer, real number or...
5b3fd9ff8346ffb9a1e61cb9c0d9c40971b567e9
3,597,582
import requests import xml def api_call(body, headers): """ Makes an HTTP Post to the SWS incidents API using the configured certificate """ with pfx_to_pem(CERTIFICATE, CERTIFICATE_PASSPHRASE) as cert: res = requests.post(url=SERVER_URL + "/SWS/incidents.asmx", cert=cert, data=body, headers=headers) ...
b4e42ce303410c1faa554732938bfd2d0d3cb524
3,597,583
def fancy_dendrogram(*args, **kwargs): """ adapted from: https://joernhees.de/blog/2015/08/26/scipy-hierarchical-clustering-and-dendrogram-tutorial """ max_d = kwargs.pop('max_d', None) if max_d and 'color_threshold' not in kwargs: kwargs['color_threshold'] = max_d ddata = hierarc...
2abc5c4b675d0c5bd04e5aa7571049cd7be5838f
3,597,584
def _normalize(mtx): """change scaling of data (in rows) such that trace(mtx*mtx') = 1 Parameters ---------- mtx : array_like Matrix to scale the data for. Notes ----- mtx' denotes the transpose of mtx """ mtx = np.asarray(mtx, dtype=float) return mtx / np.linalg.norm(...
2d950eddecaba07454e7ee095ef00c56751dfc0e
3,597,585
from typing import Union import array def is_sym(linop: Union[array, LinOp]) -> bool: """Return True if `linop` is symmetric""" mat = asmatrix(linop) return mat.shape[0] == mat.shape[1] and np.allclose(mat.T, mat)
eda4e793a56f4dd37d06162247467df17c636470
3,597,587
def mean_ruler( dp ): """ Ecuation. Josef Kittler [18] https://dspace.cvut.cz/bitstream/handle/10467/9443/1998-On-combining-classifiers.pdf?sequence=1 Soft Median Ruler Args: @dp: []_nxcxl """ p = dp.mean(2) return p
479adaf9b6e4270f9ec3709319ded9979f54111d
3,597,588
def axis_angle(R): """Returns the (axis,angle) pair representing R""" m = rotation_vector(R) return (vectorops.unit(m),vectorops.norm(m))
746d24668eb4c0bc127ab8f9a11b590e5a3c8f23
3,597,589
import re import logging def get_request_time_from_line(line, line_number): """ :param line: str with line of report :param line_number: current line number :return: float request_time """ request_time = re.findall('\d+.\d+$', line) if not request_time: logging.error( '...
3c2ed0a26c1b34b12db7bf76669273da057c5858
3,597,590
def boolean_to_string(boolean, obj: DataGetter = None): """ This function returns "NO" if `boolean` is False, and returns "YES" if `boolean` is True. """ return str(boolean)
44e1983c1b3d51281592dc368ab85f6dcf5ebe7c
3,597,591
def create_expreds(examples, predictions): """ Args: examples: dict predictions: dict Returns: expreds: dict examples: dict """ expreds = examples for example in expreds: if example in predictions: # # mark up predicted long answer for highli...
165bb38840b1f51ecf031fefe3ca75182b55d514
3,597,592
from typing import Sequence from typing import Any def _get_cont_out_labels(network_structure: Sequence[Sequence]) -> Any: """ Compute the contracted and free labels of `network_structure`. Contracted labels are labels appearing more than once, free labels are labels appearing exactly once. Computed lists a...
f749b67789a00fe1cf0b2491a0a476d3882de9be
3,597,593
def get_avg_repr(inp_reprs, indxs, indxs_mask): """ Returns the average representation based on passed indxs and mask. :param inp_reprs: [batch_size1, dim] :param indxs: [batch_size2, seq_len] :param indxs_mask: [batch_size2, seq_len] :return: [batch_size2, dim] """ sel_reprs = inp_repr...
7cf4cc78c108cfe58691fe7b0cec3b2c3608230c
3,597,594
import warnings def exp_cov( prices, returns_data=False, span=180, frequency=252, log_returns=False, **kwargs ): """ Estimate the exponentially-weighted covariance matrix, which gives greater weight to more recent data. :param prices: adjusted closing prices of the asset, each row is a date ...
e1b6a5037d16ff4b495b6c8331deddd6cd7246e3
3,597,595
def play_hand(hand, word_list, option_substitute_letter, option_replay_hand, block_substitute_letter=False ): """ Allows the user to play the given hand, as follows: * The hand is displayed. * The user may input a word. * ...
15c839027b7376e47fb249b9cb5ce0cddc65b2f9
3,597,596
from typing import Type from typing import Tuple def _generate_handler_help(handler: Type[ForeignDataWrapperDataSource]) -> Tuple[str, str]: """ Extract the long description and the parameters from a handler's class """ handler_help = ( handler.commandline_help or handler.get_name() + "\n\n" +...
72128b83a9fa3a80b32f9b5578ca92199f79c1f3
3,597,597
import hashlib def hashhex(s): """ Returns a heximal formated SHA1 hash of the input string. """ h = hashlib.sha1() h.update(s) return h.hexdigest()
a96fb004984a583c72fdbb7f90ce705858ab8f9d
3,597,598
def authentication_required(handler_method): """ Simple decorator to apply to rest method functions to require an authenticated user """ def ensure_authenticated(self, *args, **kwargs): user = get_user(self.request) if not (user and user.is_authenticated()): raise PermissionE...
e004dececba4b4d3682e2ad5d01ee7840621b146
3,597,599
def plot(scipp_obj, projection=None, axes=None, color=None, marker=None, linestyle=None, linewidth=None, **kwargs): """ Wrapper function to plot a scipp object. Possible inputs are: - Variable - Dataset - DataArray - num...
fbfa6b5e67cbbd2da6bd00ea147cb6189bfc613d
3,597,600
def calculate_price(start_date, student, duration, number_people, end_datetime, refrigerator): """ Calculate and return the price for given information :param start_date: Date object of the start :param student: Boolean indicating whether the student discount is applied :param duration: Duration of ...
c41cbbe34765c56f14ea4fb32a5dd50af36696fe
3,597,601
from scipy.signal import butter, filtfilt def highpassing(h, srate, f_max, order=4): """ Perform time-domain filtering with 4th order Butterworth filter on a given strain (time-domain) __________ fr : frequency axis, used to evaluate the position of the filter hfft : strain to be filte...
1717497935177d5b0ac28ebbe9655554f14352a9
3,597,603
import textwrap def split_contigs_fasta(contigs_fasta, segments_tiling_dict, sample): """ :param contigs_fasta: :param segments_tiling_dict: :param sample: :param out_dir: :return: """ # temp_files = [] segments_contigs_dict = dict() segments_contigs_files = dict() ...
9a1ca8ec07b0009e308c2a08b92d8a9e4b005945
3,597,604
def add_photo(param): """ 添加学生照片到photo :return: 0 - 插入失败,1 - 插入成功 """ ret = 1 try: db = persist.connection() cursor = db.cursor() except: raise NETWORK_ERR if exist('photo','student_id',param["student_id"]): delete('photo','student_id',param["student_id"...
9ef5dd0de4c74706cade8bbaf650d6c7587a27cb
3,597,605
def mk_dirs_if_missing( store_cls=None, *, key_condition=None, ): """Store decorator that will make the store create directories on write as needed""" name = getattr(store_cls, __name__, 'WrappedStoreWithConditionalDirMaking') return type(name, (MakeMissingDirsStoreMixin, store_cls), {})
32ba2bdf395b272ca45a68cb1feaf0e7c03656be
3,597,608
def var_dump(var): """ Dumps the value of the given object :param var: var to dump its value :return: dumped value of the given var """ if hasattr(var, '__dict__'): d = dict( __str__=str(var), __unicode__=str(var).encode('utf-8', 'strict'), __repr__=re...
e611326a1bd4b0bd47a58f1d3709a18f05a46af6
3,597,609
def createIDxfem(inputData, modelName): """ """ ID = {} ID["01_materialName"] = inputData["material"]["name"] a = inputData["crackParameters"]["a"] b = inputData["crackParameters"]["b"] crackRatio = "a/b = {0}/{1}".format(a, b) ID["02_crackRatio"] = crackRatio height = inputData["g...
2e214db5675abc9dbe03b0315f7b0beba1b36a14
3,597,610
def is_winner(board, player): """Checks if player has won""" # check horizontal spaces for x in range(BOARD_WIDTH - 3): for y in range(BOARD_HEIGHT): if board[x][y] == player and board[x + 1][y] == player and board[x + 2][y] == player \ and board[x + 3][y] == player: ...
6b891595088a53434528be456925c4375781b85a
3,597,611
import requests def get_session(api_key, user_id): """ Create a requests session to access the cloud API with the proper authentication :param str api_key: custom api key, if None will fallback to reading from the config :param str user_id: custom user id, if None will fallback to reading from the co...
aafe2b243e93f79609eab08c41cfa297db7f392b
3,597,612
def injectBehaviorInTrace(targetTrace, insertionProbability, multipleBehaviors=False): """ Injects malicious blocks of pre-defined malicious behaviors into a target trace with a the likelihood of [insertionProbability] :param targetTrace: The trace to inject the behaviors in :type targetTrace: list ...
d7e72ba0210e2f3dbb1ea7bb9469e25115114a4d
3,597,613
def gen_template(duration, sampling_frequency, pars, ref_geocent_time ): """ Generates a whitened waveform """ if sampling_frequency>4096: print('EXITING: bilby doesn\'t seem to generate noise above 2048Hz so lower the sampling...
9d90946755e2ee8f84943f0907e1dcb1867f5c16
3,597,614
import functools def authenticated(method): """Validates if the user is recognized before allowing access to a resource.""" @functools.wraps(method) def wrapper(self, *args, **kwargs): if self.current_user is None: raise NotFound() return method(self, *args, **kwargs) ...
83ace93021a7a2589d96455c22ac05f797a7b7cf
3,597,615
def traffic_commute_time_func(): """finds your traffic commute time index""" country_traffic_commute_time_index = float( df[df.country == YOUR_COUNTRY]["traffic_commute_time_index"], ) print( text_color( f"In your country traffic commute time " f"index is {country...
d5c50ebccb5e1a3b0801ae347ba5a5cc1453c0ef
3,597,617
def create_solver_data(specs): """Initialize solver data class from specs (exp_inputs)""" g = specs.graph # planning stuff deadline = specs.deadline theta = specs.theta horizon = specs.horizon solver_type = specs.solver_type timeout = specs.timeout solver_data = MySolverData(horizo...
b6b3a73eba9b09be4de2d1971a3d25a22cd1c274
3,597,618
def convert_coord(x_center, y_center, radius): """ Convert coordinates from central point to top left point :param x_center: x coordinate of the center :param y_center: y coordinate of the center :param radius: the radius of the ball :return: coordinates of top left point of the surface """ ...
95a6cfd91fd7a59d7995820d3d5fceba6ff985a1
3,597,619
async def handle_errors(update, error): """Обработка непредвиденных ошибок. Логируем ошибку, а также отправляем пользователю сообщение, что произошла непредвиденная ошибка """ message = update.message or update.callback_query.message await message.answer("Произошла ошибка") logger.exception...
296d54f88c69f03dab5e88d05db5fd9a6133ff8a
3,597,620
import uuid def R00003(ruleid, df, table, column, param, index, url, f): """ R00003 multi-condition rule matching, """ column_lists = column.split(" ") param_lists = param.split(" ") l = len(column_lists) oper_lists = param_lists[:l] value_lists = param_lists[l:] value_lists = [To...
efeafd02184424a08bbfcaa952510bfde8f0aa1d
3,597,621
def _get_col_values(X, c): """DataFrameとndarrayを統一的に扱うためのヘルパー: ndarrayの取得""" if isinstance(X, np.ndarray): return X[:, c] return X[c].values
3d84b7c073f0ee0c290be2922a4137b245407a54
3,597,622
import pprint def parse_input_event(msg_type, target, logs, nested_events, log_begin_idx): """ Parse input event logs :params msg_type :params target :params logs [Pair of (Down, Up)] :return: list of event.Event """ log_info = [util.extract_info(log) for log in logs] plid, pack...
6329c149685ac5e0460946323814a70eb92dd38d
3,597,623
def cosine(u, v): """ Calculates the cosine distance (1 - cosine similarity) between two vectors precondition: u.shape == v.shape :param u: vector of numbers :param v: vector of numbers :return: cosine distance between u and v """ if u.shape != v.shape: raise ValueErro...
6d9c8787d22668b669a16b167d15afaa8a9034b5
3,597,624
import pandas def oldest_trade(trades: pandas.DataFrame) -> pandas.Series: """ Get the oldest trade in the pandas.DataFrame. Args: trades: dataFrame of trades """ if trades.empty: return pandas.Series(index=trades.columns) return trades.loc[trades.time.idxmin()]
fbfd300939146f34b4c3db3939a26bf0ff63d4fb
3,597,625
def cnn_model_fn(features, labels, mode): """Model function for CNN.""" # Input Layer input_layer = tf.reshape(features, [-1, 28, 28, 1]) # Convolutional Layer #1 conv1 = tf.layers.conv2d( inputs=input_layer, filters=32, kernel_size=[5, 5], padding="same", activation=tf.nn.relu)...
f72d7451accadd5d1aae4a43c123a255d28b2302
3,597,626
from typing import Iterable def coerce_tuple(arg, *excludes): """ If the argument *arg* is: * None, return empty tuple * an Iterable but not instance of *excludes*, by default (basestring,) * anything else as one element tuple """ excludes = excludes or (basestring,) if arg is None: ...
b07ff9d5ed933cc3ebe479b193a90ae4b991daf0
3,597,627
def get_columns(): """Gets the list of songlist column headings""" if config.has_option("settings", "columns"): return config.getstringlist( "settings", "columns", const.DEFAULT_COLUMNS) else: # migrate old settings try: columns = config.get("settings", "head...
4bdeea7ebc2d4617329f3ffbe061eeb65df4ea01
3,597,628
def qrandn(mean: float, sd: float, q: float): """Sample a float value normally with ``mean`` and ``sd``. The value will be quantized, i.e. rounded to an integer increment of ``q``. Args: mean (float): Mean of the normal distribution. sd (float): SD of the normal distribution. q (floa...
4fd23683bbf74378ca10594bad3f711170059176
3,597,629
def get_usage_types(symbols): """Fetch UsageTypes for `symbols` and report unknown ones. If `symbols` is given as an empty list, fetch all UsageTypes instead. """ if symbols: uts = UsageType.objects.filter(symbol__in=symbols).order_by('symbol') known_symbols = [ut.symbol for ut in uts] ...
bc46ba2cf27916759e4977915c7c43409d6ee05f
3,597,630
def get_module_path(module): """ Gets the path of a Maya module, if it exists Args: module (unicode): Name of the module Returns: (unicode): Path to the module (empty if it doesn't exist) """ try: return cmds.moduleInfo(path=True, moduleName=module) except RuntimeErr...
4bcc37bedafee802e0a7c37a8eebf6701fd48692
3,597,631
def command_topic(current_buffer, args): """ Change the topic of a channel /slack topic [<channel>] [<topic>|-delete] """ server = servers.find(current_domain_name()) if server: arrrrgs = args.split(None, 1) if arrrrgs[0].startswith('#'): channel = server.channels.fin...
8c0074627a5bb3f5cadcc39aed368539a9c6d451
3,597,632
def WassersteinDualSimplex(h1, h2, M): """ Find the Wasserstein distance using the dual simplex """ n = len(h1) # Build model m = Model() m.setParam(GRB.Param.NumericFocus, 3) #m.setParam(GRB.Param.TimeLimit, 300) #m.setParam(GRB.Param.Presolve, 0) #m.setParam(GRB.Param.Threads, ...
9dd579224a7d8557d1ff44e61ada09f8861f8789
3,597,633
def get_parameter_from_atom_indices(zmat, indices, xyz_indexed=True): """ Get the zmat parameter from the atom indices. If indices are of length two, three, or four, an R, A, or D parameter is returned, respectively. If a requested parameter represents an angle split by a dummy atom, combine the tw...
7e5eab0a5ded8947f76c1fe15e573493430b1735
3,597,634
import pickle def prepare_dataloader(opt): """ Load data and prepare dataloader. """ def load_data(name, dict_name): with open(name, 'rb') as f: data = pickle.load(f, encoding='latin-1') num_types = data['dim_process'] data = data[dict_name] return data...
70c344803a257d448345a421dc23856f0cf3099e
3,597,635
def lorenz_system_log_likelihood_fn(params, observed_values, observation_scale, observation_index, observation_mask, use_markov_chain=False, dtype=tf.float32): """Likelihood of a series under the Lorenz System ...
7eac66651f773e064bf3ee31c20b2411159286c9
3,597,636
import gettext def get_day_name(day_no, locale): """ Gets the name of the given day [0, 6] in the given locale. :param day_no: The day in the week in the range [0, 6], with Monday being 0 :param locale: The language code :return: The name of the given day in the given locale """ previ...
969f8ba2a681903d2d46d1a4c1f055c75eab77b9
3,597,637
def flux_auto(y, s, k, a, t, e, r): """ One way to use flux package - Contemporaneous y[1:] variables are used as exogenous 'X' in pmdarima - This only works for k=1 :returns: x, s', w """ if s is None: s = dict() s = flux_hyperparams(s=s,r=r) s = in...
e993dd52d1940a53b3278b5300e36b67a05bac67
3,597,638
def chop(x,y,s0,s1): """Chop two 1-d numpy arrays from s0 to s1""" return x[s0:s1], y[s0:s1]
e43b4cbad862558862bb3539a4eac0add1bd14a1
3,597,639
def butter_bandpass_filter(data, width, fs): """ This function constructs as well as applies the specified linear phase finite impulse response (FIR) butterworth bandpass filter to the given shifted signal. The order of the filter is automatically selected based upon the value of ...
3fb875ff0557e09c1ef2fa48e13a4e5151ea4f18
3,597,640
def get_yos_sent(user): """Gets the number of Yo's sent by the user This is limited by 20 in order to minimize the ammount of data that needs to be stored in redis. At some point this should be a paginated list""" assert_account_permission(user, 'No permission to see Yo\'s') yos = Yo.objects(se...
e14d9688f775f1e148940917e1783e7870c87772
3,597,641
def psri(b3, b4, b6): """ Plant Senescence Reflectance Index (Merzlyak et al., 1999). .. math:: PSRI = (b4 - b3)/b6 :param b3: Green. :type b3: numpy.ndarray or float :param b4: Red. :type b4: numpy.ndarray or float :param b6: Red-edge 2. :type b6: numpy.ndarray or float :retu...
3be121d6e0852a6a83d307773ffacf8fddec9f9d
3,597,642
from typing import Optional from typing import List def format_query( song: Song, template: str, santitize: bool, file_extension: Optional[str] = None, short: bool = False, song_list: Optional[List[Song]] = None, ) -> str: """ Replace template variables with the actual values. """ ...
55f974214cdea93adceea65fa532c05891197f90
3,597,643
import fnmatch import re def multi_match(name, patterns, mode=any, regex=False): """ Compares *name* to multiple *patterns* and returns *True* in case of at least one match (*mode* = *any*, the default), or in case all patterns match (*mode* = *all*). Otherwise, *False* is returned. When *regex* is *T...
e4b5ee133b6b856b0bdf4ecf383138c9d9b9a034
3,597,646
from typing import Callable def mae(series1: TimeSeries, series2: TimeSeries, intersect: bool = True, reduction: Callable[[np.ndarray], float] = np.mean) -> float: """ Mean Absolute Error (MAE). For two time series :math:`y^1` and :math:`y^2` of length :math:`T`, it is computed as ...
06521cc354fbdca3fee780fdc5d6d5efa397a772
3,597,647
def absDiagCentered(inRaster,kernelDir): """ Function for calculating the absolute value of directional differences for lag o 1.4142 pixel. It take 2 inputs: inRaster (the input raster) and kernelDir (the directory where kernels are stored). The output, even if we have already derived the absolute value, can be use...
0ab02575e0f53f1e0f000ec46e81f27f6cebed70
3,597,648
def useragent(target_dir): """Fetch the resource""" try: ua = url_opener.open(target_dir) except IOError: print "FAIL -> Domain does not exist or is not responding" os._exit(os.EX_NOHOST) code = ua.getcode() response = ua.read() return(code, response)
c13dab29345d4e99293916465a05b70a6a0d4ff4
3,597,649
def taylor(*args): """ univariate Taylor series expansion taylor(IM ex, IM x, IM a, int order) -> IM taylor(DM ex, DM x, DM a, int order) -> DM taylor(SX ex, SX x, SX a, int order) -> SX Calculate the Taylor expansion of expression 'ex' up to order 'order' with respect to variable...
109e79015978310006eb00c3268e2b8fb899aa40
3,597,650
def no_nodes(G): """ returns the number of nodes in a undirected network """ return len(G)
9504cc092ae63069399124e478b6c9b20d3879c9
3,597,651
def search(): """Search for biomedical concept identifiers.""" return render_template('search.html')
76e7d733adb2f854f44e4562c924dcf26d032db1
3,597,653
import json def load_asdict(filename, *, format="yaml"): """ Load a YAML or JSON file into a dictionary of nested objects. The keywords and structure of the input are defined by the :ref:`spec:sec_ref`. :param filename: The path to the file to be loaded, or a file-like object with a ``rea...
5b33595d9afb1cde970d24e31c18bfe6df3560ab
3,597,654
def sslice(var, sindex, grd, Cpos='rho', vert=False): """ sslice, lon, lat = sslice(var, sindex, grd) optional switch: - Cpos='rho', 'u' or 'v' specify the C-grid position where the variable rely - vert=True/False If True, return the position of ...
f24667bb0d6ec11fe2c83948182a8278bace61f1
3,597,655
def XScale(*args): """Factor to scale X values from original curve""" # Getter if len(args) == 0: return lib.XYCurves_Get_Xscale() # Setter Value, = args lib.XYCurves_Set_Xscale(Value)
d504225be0b78a91bcc8072e6144afc948a1c069
3,597,656
from sklearn.mixture import GaussianMixture def gmm_clustering(cY, components, config): """Uses GMM models to cluster text lines based on their y values.""" Ms = list(range(1, 30)) lower_bounds = [] all_means = [] for m in Ms: gmm = GaussianMixture(n_components=m, random_state=0).fit(np.e...
ee7f6c929f2b2960748bfc14d9a7662468e3cc4b
3,597,657
def rms(input, framesize=1024, hopsize=512): """ Calculate RMS Parameters: Parameters: inData: ndarray input signal framesize: int framesize hopsize: int hopsize Returns: result: ndarray RMS of inData """ framed_data = se...
af1d2cc5dcfcce7c77068fee8f9f0293e4acf314
3,597,658
from typing import Optional def binarize_columns_range(df: pd.DataFrame, col_range: range, true_values: list, inplace: bool = True) -> Optional[DataFrame]: """ Transforms a set of columns (a dataframe) to binary values :param df: input dataframe :param col_range: range of co...
33e9b24eb6cce2ffdfa82e317df09c0648e3f2e6
3,597,659
def _embed_initial_state_kwargs(kwargs, embedding, qubits): """Embed the state(s) used for reverse annealing. The keyword argument storing the state(s) will be detected by name and handled appropriately. Args: kwargs (dict): Dictionary of keyword arguments, one of which must end with "initial_sta...
edf0690c3ff5f02ca8a9077648c1071a547b71ba
3,597,660