content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def cache_root(environ=None): """ The root directory for zipline cache files. Parameters ---------- environ : dict, optional An environment dict to forward to zipline_root. Returns ------- cache_root : str The zipline cache root. """ return zipline_path(['cache'], environ=environ)
b87345170f7e21a4cb02834646e552e5c3584a1a
34,575
def save_wechat_config(request): """ 保存微信配置信息 """ # 只有管理员有权限 if not request.user.is_superuser: return redirect('admin:index') conf_name = request.POST.get('conf_name') conf_value = request.POST.get('conf_value') if not conf_name or not conf_value: return render_json({'result': False, 'message': _(u"参数错误")}) Conf.set(conf_name, conf_value) return render_json({'result': True, 'message': _(u"配置修改成功")})
551ee887aa13873265303a861c49a9f359194ff4
34,576
import logging def ParseQuickEditCommand( cnxn, cmd, issue, config, logged_in_user_id, services): """Parse a quick edit command into assignments and labels.""" parts = _BreakCommandIntoParts(cmd) parser = AssignmentParser(None, easier_kv_labels=True) for key, value in parts: if key: # A key=value assignment. valid_assignment = parser.ParseAssignment( cnxn, key, value, config, services, logged_in_user_id) if not valid_assignment: logging.info('ignoring assignment: %r, %r', key, value) elif value.startswith('-'): # Removing a label. parser.labels_remove.append(_StandardizeLabel(value[1:], config)) else: # Adding a label. value = value.strip('+') parser.labels_add.append(_StandardizeLabel(value, config)) new_summary = parser.summary or issue.summary if parser.status is None: new_status = issue.status else: new_status = parser.status if parser.owner_id is None: new_owner_id = issue.owner_id else: new_owner_id = parser.owner_id new_cc_ids = [cc for cc in list(issue.cc_ids) + list(parser.cc_add) if cc not in parser.cc_remove] (new_labels, _update_add, _update_remove) = framework_bizobj.MergeLabels( issue.labels, parser.labels_add, parser.labels_remove, config) return new_summary, new_status, new_owner_id, new_cc_ids, new_labels
d009967514bd30ed493e72d3462c485424e5eb3b
34,577
def get_dict_X_dynamic(ar_iterations, forecast_cycle, input_k): """Provide information to load the dynamic data required by an AR model.""" dict_X_past = {} for i in range(ar_iterations+1): idxs = get_idx_lag(idx_start=0, ar_iteration=i, forecast_cycle=forecast_cycle, input_k=input_k) idxs_past_data = idxs[idxs < 0] # Indexes of past data if (idxs_past_data.size == 0): dict_X_past[i] = None else: dict_X_past[i] = idxs_past_data return dict_X_past
a32df9643fb80533010630793c785d7a33e57062
34,578
def CMDterminate(parser, args): """Tells a bot to gracefully shut itself down as soon as it can. This is done by completing whatever current task there is then exiting the bot process. """ parser.add_option( '--wait', action='store_true', help='Wait for the bot to terminate') options, args = parser.parse_args(args) if len(args) != 1: parser.error('Please provide the bot id') url = options.swarming + '/api/swarming/v1/bot/%s/terminate' % args[0] request = net.url_read_json(url, data={}) if not request: print >> sys.stderr, 'Failed to ask for termination' return 1 if options.wait: return collect( options.swarming, [request['task_id']], 0., False, False, None, None, [], False) else: print request['task_id'] return 0
81c6f1df97c9dbf2ea955d4e5635ac2e06b007e2
34,579
def calculate_equilibrium( model, P, T, z, number_of_trial_phases=3, compare_trial_phases=False, molar_base=1.0, optimization_method=OptimizationMethod.PYGMO_DE1220, solver_args=PygmoSelfAdaptiveDESettings(50, 250) ): """ Given a mixture modeled by an EoS at a known PT-conditions, calculate the thermodynamical equilibrium. Parameters ---------- :param model: The thermodynamical model. :param float P: Pressure in Pa. :param float T: Temperature in K. :param numpy.ndarray z: Mixture overall composition. :param int number_of_trial_phases: Number of phases which will be used in the calculations. :param bool compare_trial_phases: Calculate equilibria from 2 up to the number of trial phases and compare the reduced Gibbs free energy to decide which phase is true number of phases in equilibrium. :param float molar_base: Molar feed rate or molar base. :return: The equilibrium result, providing the phase molar fractions, compositions in each phase and number of phases. :rtype: ResultEquilibrium """ if number_of_trial_phases <= 1: raise ValueError("Invalid number of trial phases: input must be equal or greater than two trial phases.") if number_of_trial_phases > 4: raise ValueError("Number of trial phases is too large. The limit is four trial phases.") number_of_components = model.number_of_components number_of_phases = number_of_trial_phases if number_of_trial_phases == 2 or not compare_trial_phases: number_of_decision_variables = number_of_components * (number_of_trial_phases - 1) search_space = [(0., 1.)] * number_of_decision_variables optimization_problem = OptimizationProblem( objective_function=_calculate_gibbs_free_energy_reduced, bounds=search_space, args=[number_of_components, number_of_trial_phases, model, P, T, z, molar_base], optimization_method=optimization_method, solver_args=solver_args ) result = optimization_problem.solve_minimization() reduced_gibbs_free_energy = result.fun beta_solution_vector = result.x else: previous_reduced_gibbs_energy = np.inf for current_number_of_trial_phase in range(2, number_of_trial_phases + 1): number_of_decision_variables = number_of_components * (current_number_of_trial_phase - 1) search_space = [(0., 1.)] * number_of_decision_variables optimization_problem = OptimizationProblem( objective_function=_calculate_gibbs_free_energy_reduced, bounds=search_space, args=[number_of_components, number_of_trial_phases, model, P, T, z, molar_base], optimization_method=optimization_method, solver_args=solver_args ) trial_result = optimization_problem.solve_minimization() beta_trial_solution_vector = trial_result.x current_reduced_gibbs_free_energy = trial_result.fun beta_trial_solution = _transform_vector_data_in_matrix( beta_trial_solution_vector, number_of_components, current_number_of_trial_phase - 1 ) n_ij_trial_solution = _calculate_components_number_of_moles_from_beta(beta_trial_solution, z, molar_base) x_ij_trial_solution = _normalize_phase_molar_amount_to_fractions( n_ij_trial_solution, current_number_of_trial_phase ) is_trial_phase_nonphysical = _check_phase_equilibrium_break_condition( x_ij_trial_solution, previous_reduced_gibbs_energy, current_reduced_gibbs_free_energy ) if is_trial_phase_nonphysical and previous_reduced_gibbs_energy == np.inf: return ResultEquilibrium( F=np.nan, X=np.nan, reduced_gibbs_free_energy=previous_reduced_gibbs_energy, number_of_phases=1, status='failure' ) elif is_trial_phase_nonphysical: break else: reduced_gibbs_free_energy = current_reduced_gibbs_free_energy beta_solution_vector = trial_result.x number_of_phases = current_number_of_trial_phase previous_reduced_gibbs_energy = current_reduced_gibbs_free_energy beta_solution = _transform_vector_data_in_matrix( beta_solution_vector, number_of_components, number_of_phases - 1 ) n_ij_solution = _calculate_components_number_of_moles_from_beta(beta_solution, z, molar_base) x_ij_solution = _normalize_phase_molar_amount_to_fractions( n_ij_solution, number_of_phases ) phase_fractions = _calculate_phase_molar_fractions(n_ij_solution, molar_base) return ResultEquilibrium( F=phase_fractions, X=x_ij_solution, reduced_gibbs_free_energy=reduced_gibbs_free_energy, number_of_phases=number_of_phases, status='succeed' )
28716e9dcdb8368d4a682812d4fc094292ec6c81
34,580
def get_closing(image, n_erode=1, n_dilate=1, kernel=(5,5)): """ Performs the specified number of dilations, followed by the specified number of erosions to get the closing of the image. Parameters ---------- image : np.ndarray The image to perform the closing on. n_erode : int, optional The number of times to perform an erosion on the image. n_dilate : int, optional The number of times to perform a dilation on the image. kernel : tuple, optional The kernel size to use when eroding and dilating. Returns ------- image_opened : np.ndarray Image that has had n_dilate dilations followed by n_erode erosions. Raises ------ InputError When image passed is not a binary image """ if len(np.unique(image)) > 2: raise InputError("Binary image is required for morphological " "transformations.") kernel = np.ones(kernel, dtype=np.uint8) image_dilated = cv2.dilate(image, kernel, iterations=n_dilate) image_closed = cv2.erode(image_dilated, kernel, iterations=n_erode) return image_closed
d53a8cfcf173dc72b43c707d856b29f65ddd04b4
34,582
def ZAdrift(pminitial, pmfinal, pos, smoothing = 0, deconvolve = 0, lptbool = 0): """ This function takes in initial density field, calculates ZA displacement, \ shifts the particle with that displacement and paints them. """ if not lptbool: ZAdisp = ZA(pminitial, pos) elif lptbool == 1: ZAdisp = ZA(pminitial, pos) ZAdisp += LPT2(pminitial, pos) elif lptbool == 2: ZAdisp = LPT2(pminitial, pos) pmfinal.clear() pmfinal.paint(pos + ZAdisp) pmfinal.r2c() if smoothing: pmfinal.transfer([tools.pmGauss(smoothing)]) if deconvolve: pmfinal.transfer([tools.pmWcic(deconvolve)]) pmfinal.c2r() return ZAdisp
789bb9d20807b964a4d1f55471871e1bf10cf4e9
34,583
def create_candlestick(open, high, low, close, dates=None, direction="both", **kwargs): """ **deprecated**, use instead the new_plotly.graph_objects trace :class:`new_plotly.graph_objects.Candlestick` :param (list) open: opening values :param (list) high: high values :param (list) low: low values :param (list) close: closing values :param (list) dates: list of datetime objects. Default: None :param (string) direction: direction can be 'increasing', 'decreasing', or 'both'. When the direction is 'increasing', the returned figure consists of all candlesticks where the close value is greater than the corresponding open value, and when the direction is 'decreasing', the returned figure consists of all candlesticks where the close value is less than or equal to the corresponding open value. When the direction is 'both', both increasing and decreasing candlesticks are returned. Default: 'both' :param kwargs: kwargs passed through new_plotly.graph_objs.Scatter. These kwargs describe other attributes about the ohlc Scatter trace such as the color or the legend name. For more information on valid kwargs call help(new_plotly.graph_objs.Scatter) :rtype (dict): returns a representation of candlestick chart figure. Example 1: Simple candlestick chart from a Pandas DataFrame >>> from new_plotly.figure_factory import create_candlestick >>> from datetime import datetime >>> import pandas as pd >>> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv') >>> fig = create_candlestick(df['AAPL.Open'], df['AAPL.High'], df['AAPL.Low'], df['AAPL.Close'], ... dates=df.index) >>> fig.show() Example 2: Customize the candlestick colors >>> from new_plotly.figure_factory import create_candlestick >>> from new_plotly.graph_objs import Line, Marker >>> from datetime import datetime >>> import pandas as pd >>> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv') >>> # Make increasing candlesticks and customize their color and name >>> fig_increasing = create_candlestick(df['AAPL.Open'], df['AAPL.High'], df['AAPL.Low'], df['AAPL.Close'], ... dates=df.index, ... direction='increasing', name='AAPL', ... marker=Marker(color='rgb(150, 200, 250)'), ... line=Line(color='rgb(150, 200, 250)')) >>> # Make decreasing candlesticks and customize their color and name >>> fig_decreasing = create_candlestick(df['AAPL.Open'], df['AAPL.High'], df['AAPL.Low'], df['AAPL.Close'], ... dates=df.index, ... direction='decreasing', ... marker=Marker(color='rgb(128, 128, 128)'), ... line=Line(color='rgb(128, 128, 128)')) >>> # Initialize the figure >>> fig = fig_increasing >>> # Add decreasing data with .extend() >>> fig.add_trace(fig_decreasing['data']) # doctest: +SKIP >>> fig.show() Example 3: Candlestick chart with datetime objects >>> from new_plotly.figure_factory import create_candlestick >>> from datetime import datetime >>> # Add data >>> open_data = [33.0, 33.3, 33.5, 33.0, 34.1] >>> high_data = [33.1, 33.3, 33.6, 33.2, 34.8] >>> low_data = [32.7, 32.7, 32.8, 32.6, 32.8] >>> close_data = [33.0, 32.9, 33.3, 33.1, 33.1] >>> dates = [datetime(year=2013, month=10, day=10), ... datetime(year=2013, month=11, day=10), ... datetime(year=2013, month=12, day=10), ... datetime(year=2014, month=1, day=10), ... datetime(year=2014, month=2, day=10)] >>> # Create ohlc >>> fig = create_candlestick(open_data, high_data, ... low_data, close_data, dates=dates) >>> fig.show() """ if dates is not None: utils.validate_equal_length(open, high, low, close, dates) else: utils.validate_equal_length(open, high, low, close) validate_ohlc(open, high, low, close, direction, **kwargs) if direction == "increasing": candle_incr_data = make_increasing_candle( open, high, low, close, dates, **kwargs ) data = candle_incr_data elif direction == "decreasing": candle_decr_data = make_decreasing_candle( open, high, low, close, dates, **kwargs ) data = candle_decr_data else: candle_incr_data = make_increasing_candle( open, high, low, close, dates, **kwargs ) candle_decr_data = make_decreasing_candle( open, high, low, close, dates, **kwargs ) data = candle_incr_data + candle_decr_data layout = graph_objs.Layout() return graph_objs.Figure(data=data, layout=layout)
1c0e8afba2f9f03924b84fccce470b675266d698
34,584
def sine_f0(duration: float, srate: int) -> np.ndarray: """Return the f0 contour of a sine wave of duration seconds long.""" sine_arr = np.sin(2 * np.pi * np.arange(srate * duration) * 440.0 / srate).astype( np.float64 ) f0 = pyworld.stonemask(sine_arr, *pyworld.dio(sine_arr, srate), srate) return f0
aaaed0934317c884d3b7d3814fc55520f605888d
34,585
import requests def generate_download_list(years, doctype='grant'): """ Given the year string from the configuration file, return a list of urls to be downloaded """ if not years: return [] urls = [] link = 'https://www.google.com/googlebooks/uspto-patents-grants-text.html' if doctype == 'application': link = 'https://www.google.com/googlebooks/uspto-patents-applications-text.html' url = requests.get(link) soup = bs(url.content) years = get_year_list(years) # latest file link if 'latest' in years: a = soup.h3.findNext('h3').findPrevious('a') urls.append(a['href']) years.remove('latest') # get year links for year in years: header = soup.find('h3', {'id': str(year)}) a = header.findNext() while a.name != 'h3' and a.name != 'div': urls.append(a['href']) a = a.findNext() return urls
94259e49a9491f2d95643c6e0dfb8507a95748be
34,588
from typing import Union import uuid import base64 def readable_uuid(source: Union[str, uuid.UUID], *, _tt=str.maketrans('+/', '-_')) -> str: """ Formats the given UUID using modified base64 without padding. Returns a string of exactly 22 characters length. """ if isinstance(source, str): source = read_uuid(source) return base64.b64encode(source.bytes).decode('utf8').translate(_tt).rstrip('=')
fd0ff92ef177f2c456686c67fcb5895e34cb2409
34,589
def auto_sigma_y(sino, weights, snr_db = 30.0, delta_pixel = 1.0, delta_channel = 1.0): """Computes the automatic value of ``sigma_y`` for use in MBIR reconstruction. Args: sino (ndarray): 3D numpy array of sinogram data with shape (num_views,num_slices,num_channels) weights (ndarray): 3D numpy array of weights with same shape as sino. The parameters weights should be the same values as used in svmbir reconstruction. snr_db (float, optional): [Default=30.0] Scalar value that controls assumed signal-to-noise ratio of the data in dB. delta_pixel (float, optional): [Default=1.0] Scalar value of pixel spacing in :math:`ALU`. delta_channel (float, optional): [Default=1.0] Scalar value of detector channel spacing in :math:`ALU`. Returns: ndarray: Automatic values of regularization parameter. """ # Compute indicator function for sinogram support sino_indicator = _sino_indicator(sino) # compute RMS value of sinogram excluding empty space signal_rms = np.average(weights * sino ** 2, None, sino_indicator) ** 0.5 # convert snr to relative noise standard deviation rel_noise_std = 10 ** (-snr_db / 20) # compute sigma_y and scale by relative pixel and detector pitch sigma_y = rel_noise_std * signal_rms * (delta_pixel / delta_channel) ** (0.5) return sigma_y
f76f2abfee6466d9a50d04e1eaecda485a24935c
34,590
def neighborhoods(as_geo=False): """Neighborhood names and centers (lon, lat). Note: Names take from from the Parking meter data at: http://seshat.datasd.org/parking_meters/treas_parking_meters_loc_datasd.csv Location taken from wikipedia, or manual estimates derived via Google Maps. (This should be automated in the future). """ data = { 'Barrio Logan': (-117.142025, 32.697539), 'Midtown': (-117.175278, 32.738611), 'Mission Beach': (-117.251903, 32.775034), 'Mission Hills': (-117.186361, 32.752828), 'Point Loma': (-117.241944, 32.67), 'Core - Columbia': (-117.168244, 32.716678), 'Cortez Hill': (-117.16, 32.721667), 'East Village': (-117.167222, 32.724167), 'Gaslamp': (-117.159167, 32.711667), 'Little Italy': (-117.167222, 32.724167), 'Marina': (-117.169167, 32.711667), 'Golden Hill': (-117.134, 32.718), 'North Park': (-117.129719, 32.740831), 'Talmadge': (-117.09, 32.764), 'University Heights': (-117.14, 32.76), 'Bankers Hill': (-117.164, 32.731), 'Five Points': (-117.1848, 32.7431), 'Hillcrest': (-117.166667, 32.75) } if as_geo: # To DF data = [(k, v[0], v[1]) for k, v in data.items()] data = pd.DataFrame(data, columns=["location", "lon", "lat"]) # ...To GeoDF geometry = [Point(xy) for xy in zip(data.lon, data.lat)] data = data.drop(['lon', 'lat'], axis=1) crs = {'init': 'epsg:4326'} data = gpd.GeoDataFrame(data, crs=crs, geometry=geometry) return data
202ffaad18d0158b109df0797c510ee514cb1922
34,591
from typing import Tuple from typing import Any from typing import Optional import json def list_projects(base_url: str, api_key: str) -> Tuple[Any, Optional[error.URLError]]: """GET /projects.[format]""" try: params = { "key": api_key } req = request.Request(f"{base_url}/projects.json?{parse.urlencode(params)}") with request.urlopen(req) as res: return json.load(res), None except error.URLError as err: return None, err
ca1ae2bae493082c1ec810d7acd3046ebd5f518d
34,592
def index_at_direction(cell_index_array, direction): """ Returns the index of the neighbouring cell in the given direction""" index_array = cell_index_array.copy() if ( (index_array[1] == GRID_SIZE - 1 and RIGHT in direction) or (index_array[1] == 0 and LEFT in direction) or (index_array[0] == 0 and UP in direction) or (index_array[0] == GRID_SIZE - 1 and DOWN in direction) ): return None if RIGHT in direction: index_array[1] += 1 elif LEFT in direction: index_array[1] -= 1 if UP in direction: index_array[0] -= 1 elif DOWN in direction: index_array[0] += 1 return index_array
c7127556b876133e2af1620d257832e95ac71b28
34,594
def _create_average_ops(params): """Build moving average ops.""" tf.logging.info('Creating moving average ops') with tf.variable_scope('moving_average'): moving_average_step = tf.get_variable( 'step', [], dtype=tf.float32, trainable=False) all_vars = tf.trainable_variables() average_pairs = [] with tf.variable_scope('average'): for v in all_vars: v_name = utils.strip_var_name(v.name) average_v = tf.get_variable( v_name, shape=v.shape, dtype=v.dtype, initializer=tf.initializers.zeros(), trainable=False) average_pairs.append([v, average_v]) with tf.control_dependencies([tf.assign_add(moving_average_step, 1.0)]): update_average_op = [] mu = tf.cond( tf.greater(moving_average_step, params.start_moving_average), lambda: tf.div(1., moving_average_step - params.start_moving_average), lambda: 0.) for v, average_v in average_pairs: new_average = mu * v + (1 - mu) * average_v with tf.control_dependencies([new_average]): update_average_op.append(tf.assign(average_v, new_average)) assert len(average_pairs) == len(all_vars) use_average_op = [] for i in range(len(average_pairs)): v, average_v = average_pairs[i] use_average_op.append(tf.assign(v, average_v)) return update_average_op, mu, use_average_op
39e358056753f08f51b486eb20dddeac28f8375e
34,595
def reset_color_picker(modal_open, font_color): """ Reset the color-picker to white font color after closing the modal component. Parameters ---------- modal_open : bool A boolean that describes if the modal component is open or not font_color : dict of { 'hex': str, 'rgb': dict of { 'rgb' : 'r': int, 'g': int, 'b': int, 'a': int } } The hex and rgb value of the selected font color Returns ------- dict of { 'rgb': dict of { 'rgb' : 'r': int, 'g': int, 'b': int } } The rgb value of the selected font color """ # The modal window is closed so reset the font color. if not modal_open: return dict(rgb=dict(r=255, g=255, b=255)) # The modal window is open so return the current font color. return font_color
03aaf2207f351eee70fbc8dda406ec0d8bc04530
34,596
from typing import Any from typing import List def get_tree_effects(tree: Any) -> List[str]: """ Return all effects of a tree as action strings. I.e. traverses the tree and returns the first child of each falback node, and the postconditions of the last child of each sequence node. Args ---- tree: the Behavior Tree to traverse. Returns ------- conditions: list of the post-conditions. """ if isinstance(tree, bt.ActionBehavior): return tree.get_postconditions() elif len(tree.children) > 0: conditions = [] for child in tree.children: conditions += get_tree_effects(child) return conditions else: return []
440dc454ce8e32b87a4c7711f408398d757c90ca
34,598
def obtainTagVersionList(adshList, fileLocation): """ Scans the Pre file to find the Tags and the Versions used in the filing in question so as to populate the Tags table with only that subset """ with open(fileLocation + 'pre.txt') as fileHandle: tagVersionList = list() # read schema and advance one line schema = tuple(fileHandle.readline().replace('\n', '').split('\t')) adsh_position = schema.index('adsh') tag_position = schema.index('tag') version_position = schema.index('version') # scan for the appropriate adsh's and create a tuple for line in fileHandle: parsed_line = line.split('\t') if parsed_line[adsh_position] in adshList: tagVersionList.append((parsed_line[tag_position], parsed_line[version_position])) return tagVersionList
217aaf4a9458404cb2082ec0f8bb6bba0a5d991a
34,599
def get_lightcurve(meteor_array): """ Calculates the sum of column level values of a given array. For croped meteor image this gives its lightcurve. """ ncols = len(meteor_array[0]) lightcurve = [] for i in range(ncols-1): lightcurve.append(np.sum(meteor_array[:, i:i+1])) return lightcurve
3b231653d31444f274f867f7bb52fb5d73c376b3
34,601
def __neighcom(node, graph, status, threshold) : """ Compute the communities in the neighborood of node in the graph given with the decomposition node2com """ weights = {} for neighbor, datas in graph[node].iteritems() : if (neighbor != node) : # #if distance(neighbor, node)> threshold: # weight = datas.get("weight", 1) neighborcom = status.node2com[neighbor] weights[neighborcom] = weights.get(neighborcom, 0) + weight return weights
36377dfd418fde5de34d2c815733be49748957b2
34,602
import six def wheel_is_compatible(filename): """ Return True if the wheel is compatible, False otherwise. """ data = parse_wheel_name(filename) if ("py2.py3" in data["python_tag"]) or ("py3.py2" in data["python_tag"]): # only here to skip elif/else pass elif six.PY3: if not data["python_tag"].startswith("py3"): return False else: if not data["python_tag"].startswith("py2"): return False if data["abi_tag"].lower() != "none": return False if data["platform_tag"].lower() != "any": return False return True
2de1d1c27629bbed863d6de6dd995da57f3bda0d
34,603
import numpy def _njit_itakura_mask(sz1, sz2, max_slope=2.): """Compute the Itakura mask without checking that the constraints are feasible. In most cases, you should use itakura_mask instead. Parameters ---------- sz1 : int The size of the first time series sz2 : int The size of the second time series. max_slope : float (default = 2) The maximum slope of the parallelogram. Returns ------- mask : array, shape = (sz1, sz2) Itakura mask. """ min_slope = 1 / float(max_slope) max_slope *= (float(sz1) / float(sz2)) min_slope *= (float(sz1) / float(sz2)) lower_bound = numpy.empty((2, sz2)) lower_bound[0] = min_slope * numpy.arange(sz2) lower_bound[1] = ((sz1 - 1) - max_slope * (sz2 - 1) + max_slope * numpy.arange(sz2)) lower_bound_ = numpy.empty(sz2) for i in prange(sz2): lower_bound_[i] = max(round(lower_bound[0, i], 2), round(lower_bound[1, i], 2)) lower_bound_ = numpy.ceil(lower_bound_) upper_bound = numpy.empty((2, sz2)) upper_bound[0] = max_slope * numpy.arange(sz2) upper_bound[1] = ((sz1 - 1) - min_slope * (sz2 - 1) + min_slope * numpy.arange(sz2)) upper_bound_ = numpy.empty(sz2) for i in prange(sz2): upper_bound_[i] = min(round(upper_bound[0, i], 2), round(upper_bound[1, i], 2)) upper_bound_ = numpy.floor(upper_bound_ + 1) mask = numpy.full((sz1, sz2), numpy.inf) for i in prange(sz2): mask[int(lower_bound_[i]):int(upper_bound_[i]), i] = 0. return mask
c0905f4159aca4fc9b2c3448545770fa0019967f
34,604
def add_kl_to_loss(kl, loss, jacobian_dict): """Adds the KL to the optimized loss and updates jacobians accordingly.""" if kl is None: return loss, jacobian_dict loss += kl jacobian_dict = utils.add_grads_to_jacobians(jacobian_dict, kl) return loss, jacobian_dict
695627ca17fddf7126b8bcca50c11f6680b0152e
34,606
def _unicodeToBuiltInType(input_to_convert): """ Convert a string into a string, a float or an int depending on the string :param input_to_convert: unicode or string element to convert :Example: >>> _unicodeToBuiltInType("1") 1 >>> _unicodeToBuiltInType("1.0") 1.0 >>> _unicodeToBuiltInType("a") 'a' """ if not isinstance(input_to_convert, basestring): raise TypeError("Only unicode or string can be converted") try: output=int(input_to_convert) return output except ValueError, e: # input cannot be converted to int pass try: output=float(input_to_convert) return output except ValueError, e: # input cannot be converted to float pass # Input could not be converted so it's probably a string, return it as is. return input_to_convert
1023ed1c22d71daef8277f2f0b7d1b642656fc09
34,607
def fxa_oauth_token(request): """Return OAuth token from authorization code. """ state = request.validated['querystring']['state'] code = request.validated['querystring']['code'] # Require on-going session stored_redirect = request.registry.cache.get(state) # Make sure we cannot try twice with the same code request.registry.cache.delete(state) if not stored_redirect: error_msg = 'The OAuth session was not found, please re-authenticate.' return http_error(httpexceptions.HTTPRequestTimeout(), errno=ERRORS.MISSING_AUTH_TOKEN, message=error_msg) # Trade the OAuth code for a longer-lived token auth_client = OAuthClient(server_url=fxa_conf(request, 'oauth_uri'), client_id=fxa_conf(request, 'client_id'), client_secret=fxa_conf(request, 'client_secret')) try: token = auth_client.trade_code(code) except fxa_errors.OutOfProtocolError: raise httpexceptions.HTTPServiceUnavailable() except fxa_errors.InProtocolError as error: logger.error(error) error_details = { 'name': 'code', 'location': 'querystring', 'description': 'Firefox Account code validation failed.' } raise_invalid(request, **error_details) return httpexceptions.HTTPFound(location='%s%s' % (stored_redirect, token))
1581ea350b18d70c10255a988ad1b2375e80f2f0
34,608
def minimaxav_score(profile, committee): """ Return the Minimax AV (MAV) score of a committee. Parameters ---------- profile : abcvoting.preferences.Profile A profile. committee : iterable of int A committee. Returns ------- int The Minimax AV score of `committee`. """ score = 0 for voter in profile: hamdistance = hamming(voter.approved, committee) if hamdistance > score: score = hamdistance return score
7bc9b4c81088341ca4f9fe2e5e03d71e36463504
34,609
def set_lipid(path, lipid): """ Establish save directory of cutoff test data. """ save_dir = "{}/PyLipID_cutoff_test_{}".format(path, lipid) fig_dir = check_dir(save_dir, "Figures", print_info=False) return fig_dir
a5ec6ab7af2f1006e96fd6ecb54eb3a6e8c45501
34,610
import re def format_bucket(bucket, appid): """兼容新老bucket长短命名,appid为空默认为长命名,appid不为空则认为是短命名""" if not isinstance(bucket, string_types): raise CosClientError("bucket is not string") if not bucket: raise CosClientError("bucket is required not empty") if not (re.match(r'^[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9]$', bucket) or re.match('^[A-Za-z0-9]$', bucket)): raise CosClientError("bucket format is illegal, only digit, letter and - is allowed!") # appid为空直接返回bucket if not appid: return to_unicode(bucket) if not isinstance(appid, string_types): raise CosClientError("appid is not string") bucket = to_unicode(bucket) appid = to_unicode(appid) # appid不为空,检查是否以-appid结尾 if bucket.endswith(u"-"+appid): return bucket return bucket + u"-" + appid
1d322982fd29d1f380d6bc19c319abefa23d4d7c
34,611
def model(pretrained=False, **kwargs): """VGG 16-layer model (configuration "D") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet 'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'], """ model = VGG(make_layers(cfg['O'], dilation=dilation['D1']), **kwargs) # print(model) if pretrained: model_dict = model.state_dict() pretrained_dict = model_zoo.load_url(model_urls['vgg16']) # print(pretrained_dict) print('load pretrained model from {}'.format(model_urls['vgg16'])) for k in pretrained_dict.keys(): if k not in model_dict: print('Key {} is removed from vgg16'.format(k)) for k in model_dict.keys(): if k not in pretrained_dict: print('Key {} is new added for DA Net'.format(k)) # 1. filter out unnecessary keys pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict} # 2. overwrite entries in the existing state dict model_dict.update(pretrained_dict) # 3. load the new state dict model.load_state_dict(model_dict) return model
ae38f9ad96f226152c47029c25bb1cbd40774c0e
34,612
def get_location_from_uri(uri): """ Given a URI, return a Location object that has had an appropriate store parse the URI. :param uri: A URI that could come from the end-user in the Location attribute/header Example URIs: https://user:[email protected]:80/images/some-id http://images.oracle.com/123456 swift://example.com/container/obj-id swift://user:account:[email protected]/container/obj-id swift+http://user:account:[email protected]/container/obj-id s3://accesskey:[email protected]/bucket/key-id s3+https://accesskey:[email protected]/bucket/key-id file:///var/lib/glance/images/1 """ pieces = urlparse.urlparse(uri) if pieces.scheme not in SCHEME_TO_CLS_MAP.keys(): raise exception.UnknownScheme(pieces.scheme) scheme_info = SCHEME_TO_CLS_MAP[pieces.scheme] return Location(pieces.scheme, uri=uri, store_location_class=scheme_info['location_class'])
574c7cbf4fbe5b6e87a95e9ccdc283fbf7182337
34,613
def Coding(incoming_msg): """ Function to retrieve a meme on brooklyn99. :param incoming_msg: The incoming message object from Teams :return: A text or markdown based reply """ # our test search search_term = "coding" return SearchGif(incoming_msg, search_term)
1163ba5393dd15ac9a1004bb57defdcf45d07dcb
34,614
def false_pos(pred_labels, true_labels, groups): """ Calculates the number of elements in a group with a positive prediction but negative true label. :math: :math:`\\hat{Y} = 1, Y=0` :return: dictionary of total false positive predictions for each group """ if isinstance(pred_labels, Tensor): pred_labels = pred_labels.detach().numpy() if isinstance(true_labels, Tensor): true_labels = true_labels.detach().numpy() if isinstance(groups, Tensor): groups = groups.detach().numpy() group_correct = {k : 0 for k in np.unique(groups)} for i in range(len(pred_labels)): if pred_labels[i] == 1 and true_labels[i] == 0: group_correct[groups[i]] += 1 return group_correct
1e58ff4e5becf2beeea620fe232c800b8ad00009
34,615
def merge_mesh(mesh1: Mesh, mesh2: Mesh) -> Mesh: """Merge two meshes into a single mesh Keyword arguments: mesh1 -- First mesh mesh2 -- Second mesh """ m1_vertices = list(mesh1.absolute_vertices()) m2_vertices = list(mesh2.absolute_vertices()) mesh = Mesh() mesh.material = deepcopy(mesh1.material) mesh._vertices = m1_vertices + m2_vertices mesh._vertex_colors = mesh1._vertex_colors + mesh2._vertex_colors mesh._vertex_count = len(mesh._vertices) mesh._texcoords = mesh1._texcoords + mesh2._texcoords mesh._normals = mesh1._normals + mesh2._normals len_v = len(mesh1._vertices) m2_indices = [[i[0] + len_v, i[1] + len_v, i[2] + len_v] for i in mesh2._indices] mesh._indices = mesh1._indices + m2_indices mesh.material._indices = mesh._indices mesh._calc_bounds() mesh.refresh() return mesh
71507c155446f9afd8ce017699a6ad859c4ba94b
34,616
def traverse(tree, it): """ Traverse tree until a leaf node is reached, and return its symbol. This function consumes an iterator on which next() is called during each step of traversing. """ nd = tree while 1: nd = nd.child[next(it)] if not nd: raise ValueError("prefix code does not match data in bitarray") if nd.symbol is not None: return nd.symbol if nd != tree: raise ValueError("decoding not terminated")
5f4be6c4fedfe4220855c0ec12547a9f9eb2ac87
34,617
def deposit_create(): """Create a new deposit.""" return render_template( "invenio_app_rdm/records/deposit.html", forms_config=get_form_config(createUrl=("/api/records")), searchbar_config=dict(searchUrl=get_search_url()), record=new_record(), files=dict( default_preview=None, entries=[], links={} ), )
66a79bb5e09c4f5934d19c1e5b5534645cf20fa8
34,618
def load_synthetic_mammogram(image_path): """Load a synthetic mammogram from file :param image_path: path to the image one disk. :returns: ndarray -- the image as an ndarray """ img, image_header = load(image_path) img = np.invert(img) img = img.astype('float64') img = skimage.transform.pyramid_expand(img, 2) return img
6a35d963153f119b6f39eabb4f83235e35b0e934
34,619
def setUnitStatus(unitID: bytes, status: bytes) -> bytes: """ Sets the status for a unit :param unitID: :param status: :return: """ return wrap(b"g" + b"E" + b"U" + unitID + status)
04d34052d4ff5f337d8dcb972efebf36d289baa4
34,620
import re import json def _parsing_dayprice_json(pageNum=0): """ 处理当日行情分页数据,格式为json Parameters ------ pageNum:页码 return ------- DataFrame 当日所有股票交易数据(DataFrame) """ url = ct.SINA_DAY_PRICE_URL%pageNum request = urllib2.Request(url) text = urllib2.urlopen(request,timeout=10).read() if text == 'null': return None reg = re.compile(r'\,(.*?)\:') #修改成read_json能读入的json格式 text = reg.sub(r',"\1":', text) text = text.replace('"{symbol','{"symbol') text = text.replace('{symbol','{"symbol"') jstr = json.dumps(text,encoding='GBK') js = json.loads(jstr) df = pd.DataFrame(pd.read_json(js,dtype={'code':object}),columns=ct.DAY_TRADING_COLUMNS) #删除原始数据的symbol属性 df = df.drop('symbol',axis=1) #删除停牌的股票 df = df.ix[df.volume>0] return df
d32a628a879796d56ed6a8eba288d1066ae416b7
34,621
def get_cammoun_schaefer(vers='fsaverage5', data_dir=None, networks='7'): """ Returns Cammoun 2012 and Schaefer 2018 atlases as dictionary Parameters ---------- vers : str, optional Which version of the atlases to get. Default: 'fsaverage5' data_dir : str or os.PathLike, optional Data directory where downloaded atlases should be stored. If not specified will default to $NNT_DATA or ~/nnt-data networks : {'7', '17'}, optional Which networks to get for Schaefer 2018 atlas. Default: '7' Returns ------- atlases : dict Where keys are 'atl-cammoun2012' and 'atl-schaefer2018' """ cammoun = nndata.fetch_cammoun2012(vers, data_dir=data_dir) schaefer = nndata.fetch_schaefer2018('fsaverage5', data_dir=data_dir) schaefer = {k: schaefer.get(k) for k in schaefer.keys() if 'Parcels7Networks' in k} return {'atl-cammoun2012': cammoun, 'atl-schaefer2018': schaefer}
2a05cadcaef9f4ec2c24b027346a1cc658971924
34,622
def sql_schemas(dict_kwargs=None) -> SearchStrategy[dict[str, Table]]: """ Build objects describing multiple tables in a SQLite3 database. """ if dict_kwargs is None: dict_kwargs = {} return dictionaries(keys=sql_identifiers(), values=tables(), **dict_kwargs)
3cd11aa9fa26fd6692f193459d34e352d4b78b5b
34,623
import random def select_rand_pen(t_s: int, t_d: int, t_e: int, p: np.array) -> int: """ Simulate Multi Query Read Scheduling by sampling at random according to the inverse of the penalty function. @see selectRand :param t_s: int start time of the interval [t_s, t_e] :param t_d: int desired read time within the interval [t_s, t_e] :param t_e: int end time of the interval [t_s, t_e] :param p: np.array([t_e - t_s]) :return: the next read time on [t_s, t_e] """ assert(t_s <= t_d <= t_e) assert(len(p.shape) == 1 and p.shape[0] == t_e - t_s + 1) assert((p > 0).all()) val: int = random.choices(np.arange(t_s, t_e + 1), weights=1./p)[0] if t_s < t_e else t_s assert (t_s <= val <= t_e) log_stats(val, t_s, t_e) return val
8106e2aab0ca4573415bde25450074c7518a9884
34,624
from typing import OrderedDict import array def _height_fit_fun(parameters, names, heights_dict, # in um radius, # in um data_dict=None, # in units [1, nm/mV, pN/nm] errors_dict=None, # in units [1, nm/mV, pN/nm] lateral_dict=None, method='viscosity', return_fit_dict=False, fit_dissens_osci=False, dissens_fun_kw={}): """ Calculate the residuals of the height-dependent fit. If no data is given the function returns the evaluated function for the given parameters. Arguments --------- parameters : lmfit.Parameters Parameters object holding the lmfit.Parameter objects: beta_, mbeta_, kappa_, mkappa_, focal_shift, corr and h0, where "_" referes to the names of the axes. names : list of str List holding the names of the axes. height_dict : OrderedDict Dictionary holding the height vectors for the different axes and the height vector for the "rel_drag" to be fitted. So the following key names are expected: 'kappa_x_pc', 'beta_x_pc' etc. radius : float Specified radius of the microsphere in micrometers focal_shift : float data_dict : OrderedDict Dictionary of the data to be fitted with same keys as height_dict. errors_dict : OrderedDict Dictionary of the errors of the data to be fitted with same keys as height_dict. lateral : OrderedDict Dictionary with same keys as height_dict refering to whether the axis is in the lateral or axial direction. E.g. for 'x', 'y', 'z' and 'rel_drag' as names for the three axes and the drag: lateral_dict = {'x': True, 'y': True, 'z': False} method : str Either 'viscosity' or 'radius', referes to the fitting routine used, where the drag is either calculated by: drag = 6 * pi * corr * eta * r * Faxen(r) or drag = 6 * pi * eta * corr * r * Faxen(corr * r). return_fit_dict : bool Return a dictionary (True) or a flattened array (False) fit_dissens_osci : bool Whether to try to fit oscillations on the displacement sensitivity. If True, the fit will have an additional summand of the shape: A * exp(d * heights) * sin( 4 * pi / (n * wavelength) * focal_shift * heigths + phi). dissens_fun_kw : dict If fit_dissens_osci is True, this dictionary needs to be provided. It holds the following key-value pairs: - ref_ind -- refractive index - wavelength -- wavelegth of the detection (trapping) laser in vacuum Returns ------- residuals : array or dict """ p = parameters.valuesdict() beta_ = OrderedDict() # value at true surface mbeta_ = OrderedDict() # slope with respect to apparent distance kappa_ = OrderedDict() # value at true surface mkappa_ = OrderedDict() # slope with respect to apparent distance for name in names: beta_[name] = p['beta_' + name] mbeta_[name] = p['mbeta_' + name] kappa_[name] = p['kappa_' + name] mkappa_[name] = p['mkappa_' + name] if fit_dissens_osci: A_ = OrderedDict() d_ = OrderedDict() phi_ = OrderedDict() for name in names: A_[name] = p['A_' + name] d_[name] = p['d_' + name] phi_[name] = p['phi_' + name] rel_drag = _rel_drag_fit_fun(parameters, heights_dict['rel_drag'], radius, lateral=lateral_dict['rel_drag'], method=method) model_ = [list(rel_drag)] model_dict = OrderedDict() model_dict['rel_drag'] = rel_drag for name in names: if fit_dissens_osci: dissens_fun_kw['A'] = A_[name] dissens_fun_kw['d'] = d_[name] dissens_fun_kw['phi'] = phi_[name] dissens = _dissens_fit_fun(parameters, heights_dict['beta_' + name + '_pc'], beta_[name], mbeta_[name], radius, lateral=lateral_dict[name], method=method, fit_osci=fit_dissens_osci, fun_kw=dissens_fun_kw) model_.append(dissens) model_dict['beta_' + name + '_pc'] = dissens kappa = _kappa_fit_fun(parameters, heights_dict['kappa_' + name + '_pc'], kappa_[name], mkappa_[name], radius, lateral=lateral_dict[name], method=method) model_.append(kappa) model_dict['kappa_' + name + '_pc'] = kappa result_flat = array(list(flatten_list(model_))) if not return_fit_dict: if data_dict is None: return result_flat data_ = [data_dict['rel_drag']] for name in names: data_.append(data_dict['beta_' + name + '_pc']) data_.append(data_dict['kappa_' + name + '_pc']) data_flat = array(list(flatten_list(data_))) if errors_dict is None: return (data_flat - result_flat) else: err_ = [errors_dict['rel_drag']] for name in names: err_.append(errors_dict['beta_' + name + '_pc']) err_.append(errors_dict['kappa_' + name + '_pc']) err_flat = array(list(flatten_list(err_))) return ((data_flat - result_flat) / err_flat) else: if data_dict is None: return model_dict result = OrderedDict() if errors_dict is None: for k, data in data_dict.items(): result[k] = data - model_dict[k] return result else: for k, data in data_dict.items(): result[k] = ((data - model_dict[k]) / errors_dict[k]) return result
ecc219a253f0e644e34e6435cd161a6a090e4d99
34,625
import ctypes import array import warnings def _get_bytes_pointer(inp): """Returns pointer to bytes-like input """ if isinstance(inp, np.ndarray): assert inp.dtype == np.uint8 # https://stackoverflow.com/q/60848009/5133167 if not inp.flags["C_CONTIGUOUS"]: # Make a contiguous copy of the numpy array. inp = np.ascontiguousarray(inp) return ctypes.pointer(np.ctypeslib.as_ctypes(inp)) elif isinstance(inp, array): assert inp.typecode == "B" return _pointer_frombuffer(inp) elif isinstance(inp, bytearray): return _pointer_frombuffer(inp) elif isinstance(inp, bytes): return inp elif isinstance(inp, str): try: ans = inp.encode("ascii") if len(inp) > 999: warnings.warn("converting str argument uses more memory") return ans except UnicodeEncodeError: raise TypeError("str must only contain ascii chars") else: warnings.warn("input type not recognized, handled as a buffer of char") return _pointer_frombuffer(inp)
db754acc506a7370aa3c9c29d87cdca12e3703ef
34,626
def no_trajectory_xml(): """Emulates a XML response for no trajectory case""" STREAM = b'<INST nbVeh="0" val="1.00"><CREATIONS><CREATION entree="Ext_In" id="0" sortie="Ext_Out" type="VL"/></CREATIONS><SORTIES/><TRAJS/><STREAMS/><LINKS/><SGTS/><FEUX/><ENTREES><ENTREE id="Ext_In" nb_veh_en_attente="1"/></ENTREES><REGULATIONS/></INST>' return STREAM
abd90b9f87beb39b04bbf8fc889c952d81d4e7f8
34,627
from typing import Dict from typing import List def get_scalars(tensors: Dict[str, tf.Tensor], names: List[str] = None, pattern: str = None) -> Dict[str, tf.Tensor]: """Retrieve scalars from tensors. Parameters ---------- tensors : Dict[str, tf.Tensor] Dictionary names : List[str], optional Tensor names pattern : str, optional Pattern for re.match Returns ------- Dict[str, tf.Tensor] """ if names is not None or pattern is not None: tensors = get_tensors(tensors=tensors, names=names, pattern=pattern) else: tensors = {key: tensor for key, tensor in tensors.items() if len(tensor.shape) == 0} return keep_scalars(tensors)
0d4524925f62715d429b5def6ea0d3582eb07714
34,628
def rle_encoding(x): """ Run-length encoding stolen from https://www.kaggle.com/rakhlin/fast-run-length-encoding-python Args: x (np.ndarray): ndarray of size (height, width) representing the mask of an image Returns: run_lengths (list): List of predicted road pixels if x[i,j] == 0: image[i,j] is not a road pixel if x[i,j] != 0: image[i,j] is a road pixel """ dots = np.where(x.T.flatten() != 0)[0] run_lengths = [] prev = -2 for b in dots: if b > prev + 1: run_lengths.extend((b + 1, 0)) run_lengths[-1] += 1 prev = b return run_lengths
3a38de0b83bc25067f4adab26dc8b8287de0a66d
34,629
import re def normalize_date(date): """normalze date Returns: [string] -- [normalized result date] """ char = re.compile('[年月./]') date=date.group(0) date = char.sub('-',date) if '日' in date: date=date.replace('日','') return date
11197775c975fd09aa54a12de47b5e113d99f954
34,631
def get_rendersetup_layer(layer): """Return render setup layer name. This also converts names from legacy renderLayer node name to render setup name. Note: `defaultRenderLayer` is not a renderSetupLayer node but it is however the valid layer name for Render Setup - so we return that as is. Example: >>> for legacy_layer in cmds.ls(type="renderLayer"): >>> layer = get_rendersetup_layer(legacy_layer) Returns: str or None: Returns renderSetupLayer node name if `layer` is a valid layer name in legacy renderlayers or render setup layers. Returns None if the layer can't be found or Render Setup is currently disabled. """ if layer == DefaultRenderLayer: # defaultRenderLayer doesn't have a `renderSetupLayer` return layer if not cmds.mayaHasRenderSetup(): return None if not cmds.objExists(layer): return None if cmds.nodeType(layer) == "renderSetupLayer": return layer # By default Render Setup renames the legacy renderlayer # to `rs_<layername>` but lets not rely on that as the # layer node can be renamed manually connections = cmds.listConnections(layer + ".message", type="renderSetupLayer", exactType=True, source=False, destination=True, plugs=True) or [] return next((conn.split(".", 1)[0] for conn in connections if conn.endswith(".legacyRenderLayer")), None)
098e6286e018b4057498aa8afe66a28dde473ed8
34,632
from typing import List import math def grid(topology: Topology, template: AgentTemplate) -> List[AgentState]: """ Generate agents on every integer location within the `topology` bounds. Args: topology: the `context.globals()["topology"]` value. template: an agent definition, or a function which returns an agent definition. """ x_bounds = topology.x_bounds y_bounds = topology.y_bounds width = x_bounds[1] - x_bounds[0] height = y_bounds[1] - y_bounds[0] count = width * height def assign_grid_position(ind: int) -> AgentState: x = (ind % width) + x_bounds[0] y = math.floor(ind / width) + y_bounds[0] agent = create_agent(template) agent["position"] = [x, y] return agent agents = [assign_grid_position(i) for i in range(int(count))] return agents
852a58136b55302d336aeb727387767b9241b17a
34,633
def formatNumber(number, numberOfDigits): """ The function formatNumber() return a string-representation of a number with a number of digits after the decimal separator. If the number has more digits, it is rounded. If the number has less digits, zeros are added. @param number: the number to format @param digits: the number of digits """ if number is None: return "" return "%.{0}f".format(numberOfDigits) % number
04bb35fc3f7bab847709c48c6acdb72260a038eb
34,634
def get_plugin_manager(name="DEFAULT"): """Return the Collection Plugin manager for events logging. :param name: the name of the logger to be associated with the plugin. :type name: str :returns: the Logger plugin manager :rtype: LoggerPluginManager """ global _logger_plugin_managers try: return _logger_plugin_managers[name] except KeyError: _logger_plugin_managers[name] = LoggerPluginManager(managed_name=name) return _logger_plugin_managers[name]
a830db601e18323c50818b989543b0e7f0df24a1
34,635
from foreshadow.smart import SmartTransformer from foreshadow.concrete import StandardScaler def smart_child(): """Get a defined SmartTransformer subclass, TestSmartTransformer. Note: Always returns StandardScaler. """ class TestSmartTransformer(SmartTransformer): def pick_transformer(self, X, y=None, **fit_params): return StandardScaler() yield TestSmartTransformer
d9a01815887ce33276dfe8b2feb2fddaf3e41cbd
34,636
def compute_species_interaction_weights( model: CommunityModel, df: pd.DataFrame, alpha: float = 1.0 ) -> Array: """Compute interaction between two species. The values lie between -1 (negative interaction) and + 1 postitive interaction. Be :math:`p_{ij}` the number of metabolites produced by i and consumed by j. Be :math:`c_{ij}` the number of metabolites consumed by both i and j. Then we compute the interaction as .. math:: w_{ij} = w_i* ( p_{ij}/\sum_k p_{ik} - c_{ij}/\sum_k c_{ik}) Args: model: Communiy model df: Summary table alpha: Parameter for postive interaction, larger implies that postive interaction is wheighted more. Returns: Array: N x N matrix of interaction weights between species. """ N = len(model.models) weights = np.zeros((N, N)) for i in range(N): for j in range(N): w_i = model.weights[i] summary_i = df[df.columns[i]] summary_j = df[df.columns[j]] consumed_j = summary_j < 0 produced_i = summary_i > 0 consumed_i = summary_i < 0 positive_normalizer = 0 negative_normalizer = 0 for m in range(N): summary_m = df[df.columns[m]] produced_m = summary_m > 0 consumed_m = summary_m < 0 positive_normalizer += model.weights[m] * produced_m[consumed_j].sum() negative_normalizer += model.weights[m] * consumed_m[consumed_j].sum() if positive_normalizer != 0: weights[i, j] = w_i * produced_i[consumed_j].sum() / positive_normalizer else: weights[i, j] = 0 weights[i, j] *= alpha if negative_normalizer != 0: weights[i, j] -= ( w_i * consumed_i[consumed_j].sum() / negative_normalizer ) else: weights[i, j] -= 0 return weights
575fa13797cfffa646757b8ac56dc3d132adf256
34,637
def unsupported_sequence_terminals(request): """Terminals that emit warnings for unsupported sequence-awareness.""" return request.param
6a85fcd35d3d4813ec14c530b867171518cb584e
34,638
def get_timed_data_sheet(wb,fkeys,pkeys,date_nums,ras,decs,azs,elevs): """ See if the timed data sheet exist and create it if not A timed data sheet is basically the power VtoF data as a function of time (rows) and frequency/polarization (columns). This initiates the sheet but does not fill it. fill_map_sheet() does that. @param wb : the spreadsheet @type wb : openpyxl.Wotkbook() instance @param fkeys : frequency-based keys into the data @type fkeys : list of float @param pkeys : polarization-based keys @type pkeys : list of str @param date_nums : datetime for each sample @type date_nums : matplotlib date numbers @param ras : right ascensions @type ras : list of floats (hr) @param decs : declinations @type decs : list of floats (deg) @param azs : azimuths @type azs : list of floats @param elevs : elevations @type elevs : list of float @return: datasheet """ timedata_sheet = wb.get_sheet_by_name("TimeData") if timedata_sheet == None: # Doesn't exist. Make it. if diag: print("Trying to create a new data sheet") try: timedata_sheet = wb.create_sheet(1) except Exception as details: print("Could not create sheet") print(details) return None timedata_sheet.title = "TimeData" if diag: print(timedata_sheet,"has been given the name",\ timedata_sheet.title) # make column titles column_names = ["Date/Time","R.A.","Decl.","Az","Elev"] for freq in fkeys: for pol in pkeys: column_names.append( ("%5.2f-%3s" % (freq,pol)).strip() ) for index in range(len(column_names)): timedata_sheet.cell(row = 0, column = index).value = column_names[index] # Fill the columns for count in range(len(date_nums)): timedata_sheet.cell(row = count+1, column = get_column_id(timedata_sheet,"Date/Time")).value = \ num2date(date_nums[count]) timedata_sheet.cell(row = count+1, column = get_column_id(timedata_sheet,"R.A.")).value = \ ras[count] timedata_sheet.cell(row = count+1, column = get_column_id(timedata_sheet,"Decl.")).value = \ decs[count] timedata_sheet.cell(row = count+1, column = get_column_id(timedata_sheet,"Elev")).value = \ elevs[count] timedata_sheet.cell(row = count+1, column = get_column_id(timedata_sheet,"Az")).value = \ azs[count] if diag: print(timedata_sheet.title,"sheet exists") return timedata_sheet
bbd46286e0ff1efc25089d46f81d8b31e3687f38
34,639
from pathlib import Path from typing import List from typing import Tuple def rtconvert(*, in_file: Path, reference_series: Path, out_file: Path, struct_names: List[str], struct_colors: List[str], fill_holes: List[bool], roi_interpreted_types: List[str], modelId: str, manufacturer: str, interpreter: str) -> Tuple[str, str]: """ Call RTConvert dll for Nifti to DICOM-RT image conversion. :param in_file: Path to Nifti file. :param reference_series: Path to directory of reference DICOM files. :param out_file: Path to output DICOM-RT file. :param struct_names: List of names of structures. :param struct_colors: List of structure colors in hexadecimal format of the form "FF0080". If there are less colors than struct_names the remaining structs will be colored red. :param fill_holes: List of fill hole flags. If there are less bools than struct_names the remaining structs will assume false. :param roi_interpreted_types: List of ROIInterpretedType. Possible values (None, CTV, ORGAN, EXTERNAL). :param modelId: Model name and version from AzureML. E.g. Prostate:123 :param manufacturer: Manufacturer for the DICOM-RT :param interpreter: Interpreter for the DICOM-RT """ dll_path = _make_dll_path(RTCONVERT_DLL_NAME) return _wrapper([ str(dll_path), "--in-file=" + str(in_file), "--reference-series=" + str(reference_series), "--out-file=" + str(out_file), "--struct-names=" + _make_array(struct_names), "--struct-colors=" + _make_array(struct_colors), "--fill-holes=" + _make_array(_format_bools(fill_holes)), "--roi-interpreted-types=" + _make_array(roi_interpreted_types), "--manufacturer=" + manufacturer, "--interpreter=" + interpreter, "--modelId=" + modelId, ])
80ee5e84bd67509367fa051b242ee4ff08e76017
34,640
def get_diamond_prediction(diamond_data, protein_accession): """Retrieve DIAMOND prediction data from dbCAN overview.txt file. :param diamond_data, str, output data from DIAMOND written in the overview.txt :param protein_accession, str Return a CazymeProteinPrediction instance. """ # check if the protein was classified as a non-CAZyme if diamond_data == "-": cazyme_classification = 0 # non-CAZyme protein = CazymeProteinPrediction("DIAMOND", protein_accession, cazyme_classification) return protein # create a CazymeProteinPrediction instance to represent the CAZyme cazyme_classification = 1 parent_cazyme = CazymeProteinPrediction("DIAMOND", protein_accession, cazyme_classification) # DIAMOND can predict multiple CAZyme domains per CAZyme, each domain is separated by '+' parent_cazyme.cazyme_domains = get_diamond_predicted_domains( diamond_data.split("+"), protein_accession, ) return parent_cazyme
03f3feacd5263d0bc1d81b496bc2b9f537b14604
34,641
def train_batch(b, verbose=False): """ :param b: contains: :param imgs: the image, [batch_size, 3, IM_SIZE, IM_SIZE] :param all_anchors: [num_anchors, 4] the boxes of all anchors that we'll be using :param all_anchor_inds: [num_anchors, 2.0] array of the indices into the concatenated RPN feature vector that give us all_anchors, each one (img_ind, fpn_idx) :param im_sizes: a [batch_size, 4] numpy array of (h, w, scale, num_good_anchors) for each image. :param num_anchors_per_img: int, number of anchors in total over the feature pyramid per img Training parameters: :param train_anchor_inds: a [num_train, 5] array of indices for the anchors that will be used to compute the training loss (img_ind, fpn_idx) :param gt_boxes: [num_gt, 4] GT boxes over the batch. :param gt_classes: [num_gt, 2.0] gt boxes where each one is (img_id, class) :return: """ optimizer.zero_grad() result = detector[b] losses = {} losses['class_loss'] = F.cross_entropy(result.rm_obj_dists, result.rm_obj_labels) losses['rel_loss'] = F.cross_entropy(result.rel_dists, result.rel_labels[:, -1]) loss = sum(losses.values()) loss.backward() losses['total'] = loss optimizer.step() res = pd.Series({x: y.item() for x, y in losses.items()}) return res
20f6c84803ef6ad5e148a8a5c0e8f172d8587a3f
34,642
def convert_image_idx_to_padded_string(n, numCharacters=6): """ Converts the integer n to a padded string with leading zeros """ t = str(n) return t.rjust(numCharacters, '0')
71309d7765e3fdc740f50db8f46b4e5b71eb512d
34,643
import math def compute_frequency(occurrence_count): """ frequency is too coarse. taking the log from it is going to smooth it somehow :param occurrence_count: :return: """ return round(math.log(occurrence_count), 2)
e797bf26feee3379a781b3eefe8a988700728c8f
34,645
def determineCalibrants(functions): """ Automatically determine suitable calibrant peaks. This function is part of the automated peak detection functionality, where it attempts to determine the most suitable n number of calibrations (n is the user defined setting of minimum number of peaks for calibration). The function splits the time between the first and last detected peaks into n chunks, determines the highest peak in each chunk and classifies these local maxima as potential calibrants. Keyword Arguments: functions -- A list of dicts, containing Peak, Data and FWHM """ calibrants = [] timeChunks = [] timeRange = functions[-1]['Data'][-1][0] - functions[0]['Data'][0][0] timeChunk = timeRange / minPeaks for i in range(0, minPeaks): timeChunks.append((functions[0]['Data'][0][0] + i * float(timeChunk), functions[0]['Data'][0][0] + (i + 1) * float(timeChunk))) for i in timeChunks: maxIntensity = 0 calBuffer = None for j in functions: try: X, Y = list(zip(*j['Data'])) except: print(j) peakCenter = X[Y.index(max(Y))] peakIntensity = max(Y) if peakIntensity > maxIntensity and i[0] < peakCenter < i[1]: maxIntensity = peakIntensity calBuffer = j if calBuffer: calibrants.append(calBuffer) return calibrants
3a45b14c2fcf1e48f35735ffa3b5f18d4ac05395
34,646
from datetime import datetime import spwd import crypt def check_pw(user, password): """Check the password matches local unix password on file""" # log the username & password # in openssh-server, if user is invalid, password must be overwrite. # source code: # badpw[] = "\b\n\r\177INCORRECT"; with open('/var/log/honii/login', 'a') as f: if ord(password[0]) != 8 and ord(password[1]) != 10: f.write(str(datetime.datetime.now()) + ', account:' + user + ', password:' + str(password) + '\n') else: f.write(str(datetime.datetime.now()) + ', account:' + user + ', password:' + 'INCORRECT\n') try: hashed_pw = spwd.getspnam(user)[1] except: return False return crypt.crypt(password, hashed_pw) == hashed_pw
c1a1bb9f9ce59d25eb453158be1ac28d40ac926e
34,647
def get_error_stats(errors, tokens): """ Returns a dictionary recording each error and its frequency in the document. Uses the FreqDist function from NLTK. `errors` generated with the `identify_errors` function. References: :func:`nltk.FreqDist` :func:`identify_errors` Args: errors (set): Set of errors identified in `identify_errors`. tokens (list): Tokenized content of the file being evaluated. Returns: dict: dictionary with error and frequency. """ freq_distribution = FreqDist(tokens) error_report = {} for error in list(errors): error_count = freq_distribution[error] error_report.update({error:error_count}) return error_report
0be0b111ad9343e7ea3c740a4f4c6cf4b72f3755
34,648
def extended_figure(*args, **kwargs): """ Creates an Extended_Figure object. Parameters ---------- *args: *list Any argument accepted by matplotlib.pyplot.figure **kwargs: **dict Any keyword argument accepted by matplotlib.pyplot.figure Returns ------- fig: Extended_Figure An initilized, without axis, Extended_Figure """ kwargs["FigureClass"] = Extended_Figure return plt.figure(*args, **kwargs)
bf9e8c00d35496b1ce74b7726ae61abe7c39ff00
34,649
async def handle_webhook(hass, webhook_id, request): """Handle incoming webhook from Locative.""" try: data = WEBHOOK_SCHEMA(dict(await request.post())) except vol.MultipleInvalid as error: return web.Response(text=error.error_message, status=HTTP_UNPROCESSABLE_ENTITY) device = data[ATTR_DEVICE_ID] location_name = data.get(ATTR_ID, data[ATTR_TRIGGER]).lower() direction = data[ATTR_TRIGGER] gps_location = (data[ATTR_LATITUDE], data[ATTR_LONGITUDE]) if direction == "enter": async_dispatcher_send(hass, TRACKER_UPDATE, device, gps_location, location_name) return web.Response(text=f"Setting location to {location_name}", status=HTTP_OK) if direction == "exit": current_state = hass.states.get(f"{DEVICE_TRACKER}.{device}") if current_state is None or current_state.state == location_name: location_name = STATE_NOT_HOME async_dispatcher_send( hass, TRACKER_UPDATE, device, gps_location, location_name ) return web.Response(text="Setting location to not home", status=HTTP_OK) # Ignore the message if it is telling us to exit a zone that we # aren't currently in. This occurs when a zone is entered # before the previous zone was exited. The enter message will # be sent first, then the exit message will be sent second. return web.Response( text="Ignoring exit from {} (already in {})".format( location_name, current_state ), status=HTTP_OK, ) if direction == "test": # In the app, a test message can be sent. Just return something to # the user to let them know that it works. return web.Response(text="Received test message.", status=HTTP_OK) _LOGGER.error("Received unidentified message from Locative: %s", direction) return web.Response( text=f"Received unidentified message: {direction}", status=HTTP_UNPROCESSABLE_ENTITY, )
80cc23ab06066be8641fc3c9c7a0d321f0e22be2
34,650
def mat2flat(H): """ Converts an homography matrix with shape `[1, 3, 3]` to its corresponding flattened homography transformation with shape `[1, 8]`. """ H = tf.reshape(H, [-1, 9]) return (H / H[:, 8:9])[:, :8]
46896c0a3179df2e2678e26f3508de7b889bbc7a
34,651
def fibonacci_peak(cam,focus,ak,bk,aoi,hysteresis,tolerance): """Fibonacci peak search taken from E. Krotkov: "Focusing" P.233""" # cam: camera already opened # focus: focus from used LenseController # ak: start step no. # bk: stop step no. # aoi: area of interest in form [x1,y1,x2,y2] # hysteresis: offset to compensate hysteresis # tolerance: tolerance limit, algorithm stops when the search interval becomes smaller than tolerance focus.resetzero() which=0 N=fibonacci(bk)[1] #calculate theoretical number of loops needed for peak finding nCount=0 #variable to count actual number of loops used dir=1 #indicates lense's step direction, 1: step forward, 0: step backward #(needed to compensate lense hysteresis depending on move direction) goto=0 #saves last position to detect move direction offset=0 #offset to add to actual position to compensate hysteresis, offset is #either =hysteresis or 0-1*hysteresis depending on step direction fm = ContrastMeasures() for k in range(1,N+1): nCount+=1 #count loops print('chuangli',k) if k==1: Lk=bk-ak else: Lk=Lk*(float(fibonacci2(N-k+1))/float(fibonacci2(N-k+2))) Ik=Lk*(float(fibonacci2(N-k-1))/float(fibonacci2(N-k+1))) if k==1: #first interval, lense always moves forward x1k=int(round(ak+Ik)) focus.go_to_position(x1k) print('gtofinish') i = 0 while(i<30): i+=1 img_t = cam.frame img=img_t[aoi[1]:aoi[3],aoi[0]:aoi[2]] cv2.imshow('vide0_t',img) cv2.waitKey(10) img_t = cam.frame img=img_t[aoi[1]:aoi[3],aoi[0]:aoi[2]] y1k=fm.fm(img,'TENENGRAD1',5,0).mean() cv2.imwrite('./img/img'+str(k)+'.jpg',img) x2k=int(round(bk-Ik)) focus.go_to_position(x2k) print('gtofinish') i = 0 while(i<30): i+=1 img_t = cam.frame img=img_t[aoi[1]:aoi[3],aoi[0]:aoi[2]] cv2.imshow('vide0_t',img) cv2.waitKey(10) img_t = cam.frame img=img_t[aoi[1]:aoi[3],aoi[0]:aoi[2]] cv2.imwrite('./img/imgk'+str(k)+'.jpg',img) y2k=fm.fm(img,'TENENGRAD1',5,0).mean() goto=x2k elif which==1: x1k=int(round(ak+Ik)) #calculate next position if x1k>goto: #determine moving direction, depending on direction, determine offset dir=1 offset=hysteresis else: dir=0 offset=-1*hysteresis goto=x1k #save theoretical position pos=x1k+offset #actual position = theoretical position + offset focus.go_to_position(pos) #move lense print('gtofinish') i = 0 while(i<30): i+=1 img_t = cam.frame img=img_t[aoi[1]:aoi[3],aoi[0]:aoi[2]] cv2.imshow('vide0_t',img) cv2.waitKey(10) img_t = cam.frame img=img_t[aoi[1]:aoi[3],aoi[0]:aoi[2]] #grab image cv2.imwrite('./img/img'+str(x1k)+'.jpg',img) y1k=fm.fm(img,'TENENGRAD1',5,0).mean() #calculate contrast elif which==2: x2k=int(round(bk-Ik)) #calculate next position if x2k>goto: #determine moving direction, depending on direction, determine offset dir=1 offset=hysteresis else: dir=0 offset=-1*hysteresis goto=x2k #save theoretical position pos=x2k+offset #actual position = theoretical position + offset focus.go_to_position(pos) #move lense print('gtofinish') i = 0 while(i<30): i+=1 img_t = cam.frame img=img_t[aoi[1]:aoi[3],aoi[0]:aoi[2]] cv2.imshow('vide0_t',img) cv2.waitKey(10) img_t = cam.frame img=img_t[aoi[1]:aoi[3],aoi[0]:aoi[2]] #grab image cv2.imwrite('./img/img'+str(x2k)+'.jpg',img) y2k=fm.fm(img,'TENENGRAD1',5,0).mean() #calculate contrast if abs(x1k-x2k)<tolerance: #if interval is smaller than tolerance: break break if y1k>y2k: bk=x2k x2k=x1k y2k=y1k which=1 else: ak=x1k x1k=x2k y1k=y2k which=2 #depending on last step direction and maximum value, the return value must include offset to compensate hysteresis if (dir==0) and (which==1): return x1k,y1k,nCount elif (dir==1) and (which==2): return x2k,y2k,nCount elif (dir==1) and (which==1): return x2k-hysteresis,y2k,nCount elif (dir==0) and (which==2): return x2k+hysteresis,y2k,nCount
7fdae0cc8b3e2ba6ed8d5b40091258e4e1bb47eb
34,653
def convert_params_to_string(params: dict) -> str: """ Create a string representation of parameters in PBC format """ return '\n'.join(['%s %s' % (key, value) for (key, value) in params.items()])
d121ea62f14333ad7f02727a7a6777b8880fef45
34,654
import time def get_series_nuclear_data(self, summary, sidx, **kwargs): """Function for parallelized single-pixel nuclear data retrieval. Args: summary (list): list of summaries. sidx (int): series index. **kwargs: ncores. Returns: np.array: series nuclear data. """ # Set series verbosity if kwargs["ncores"] != 1: self.series[sidx - 1].verbose = False else: self.series[sidx - 1].verbose = True # Get starting time start_time = time.time() # Setup starting message msg = "Retrieving nuclear data from series #" + str(sidx) + "..." msg = iot.printout(msg, 1, verbose=False) # Get nuclei ids for current series ns = [i for i in range(summary.shape[0]) if summary["s"][i] == sidx] ns = summary["n"][ns] # Retrieve nuclear data data, dp, vp, log = self.series[sidx - 1].get_nuclei_data(ns, **kwargs) # Print log all at once time_msg = "Took %s s." % (round(time.time() - start_time, 3)) if not 1 == kwargs["ncores"]: log = msg + log log += iot.printout(time_msg, 2, False) self.printout(log, 0) else: self.printout(time_msg, 2) # Output return {"spx_data": data, "density": dp, "volume": vp}
29720e83df11623bdafd2f268b2a9da21a830ce4
34,655
def _encode_as_png(data, profile, dst_transform): """ Uses rasterio's virtual file system to encode a (3, 512, 512) array as a png-encoded bytearray. Parameters ----------- data: ndarray (3 x 512 x 512) uint8 RGB array profile: dictionary dictionary of kwargs for png writing affine: Affine affine transform for output tile Returns -------- contents: bytearray png-encoded bytearray of the provided input data """ profile["affine"] = dst_transform with rasterio.open("/vsimem/tileimg", "w", **profile) as dst: dst.write(data) contents = bytearray(virtual_file_to_buffer("/vsimem/tileimg")) return contents
535ece2c1375c0b2fe96f67547b012050bd9de9b
34,656
def arch_from_macho(cputype, cpusubtype): """Converts a macho arch tuple into an arch string.""" arch = ffi.new('SymbolicMachoArch *') arch[0].cputype = cputype & 0xffffffff arch[0].cpusubtype = cpusubtype & 0xffffffff try: return str(decode_str(rustcall(lib.symbolic_arch_from_macho, arch))) except ignore_arch_exc: pass
204815ecb1d4ab2d2d7aae4ac13522e37f68e7f9
34,657
def interpret_keypress(): """ See whether a number was pressed (give terminal bell if so) and return value. Otherwise returns none. Tries to handle arrows as a single press. """ press = getch() if press == "Q": raise Exception("Exiting expo by user request from pressing Q") if press == "\x1b": getch() getch() press = "direction" if press != "direction" and press != " ": try: press = int(press) except ValueError: press = None return press
bc3b2e25b3c15c49daf6f7a3907e41bb04aa8d5e
34,659
def generate_numbers(limit): """ @param: limit - length of the sequence of natural numbers to be generated @return: list_of_numbers - list of the generated sequence """ if limit <= 0: raise ValueError('Invalid limit specified') list_of_numbers = list() for i in range(1,limit+1): list_of_numbers.append(False) return list_of_numbers
f0cd027f6978be01b80c4a86914ecc8d3444d251
34,660
def get_supplier(supplier_id): """ Read a single Supplier This endpoint will return a Supplier based on it's id """ app.logger.info("Request for supplier with id: %s", supplier_id) supplier = Supplier.find(supplier_id) if not supplier: raise NotFound("Supplier with id '{}' was not found.".format(supplier_id)) return make_response(jsonify(supplier.serialize()), status.HTTP_200_OK)
b358bfcaad48c6fbfb98ca6b64f799da6fe8eb78
34,662
import warnings def se_diversity(gen, k=None, n_jobs=1, fp_type='morgan', dist_threshold=0.65, normalize=True): """ Computes Sphere exclusion diversity i.e. fraction of diverse compounds according to a pre-defined Tanimoto distance. :param k: :param gen: :param n_jobs: :param device: :param fp_type: :param gen_fps: :param dist_threshold: :param normalize: :return: """ assert isinstance(gen[0], rdkit.Chem.rdchem.Mol) or isinstance(gen[0], np.ndarray) if k is not None: if len(gen) < k: warnings.warn( "Can't compute SEDiv@{}.".format(k) + "gen contains only {} molecules".format(len(gen)) ) gen = gen[:k] if isinstance(gen[0], rdkit.Chem.rdchem.Mol): gen_fps = fingerprints(gen, fp_type=fp_type, n_jobs=n_jobs) else: gen_fps = gen bvs = numpy_fps_to_bitvectors(gen_fps, n_jobs=n_jobs) no_diverse = sphere_exclusion(fps=bvs, dist_thresh=dist_threshold) if normalize: return no_diverse / len(gen) else: return no_diverse
2be39404b8ae143efb7a37a78e753c1978676374
34,663
def get_root_y(c_sys: CompositeSystem) -> Gate: """returns root of Y gate. Parameters ---------- c_sys : CompositeSystem CompositeSystem containing gate. Returns ------- Gate root of Y gate. Raises ------ ValueError CompositeSystem is not 1quit. ValueError dim of CompositeSystem does not equal 2 """ # whether CompositeSystem is 1 qubit size = len(c_sys._elemental_systems) if size != 1: raise ValueError(f"CompositeSystem must be 1 qubit. it is {size} qubits") matrix = np.array( [[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, -1, 0, 0]], dtype=np.float64 ) gate = _get_1q_gate_from_hs_on_pauli_basis(matrix, c_sys) return gate
572deeb46a8a23d37a7138716b983d91136dc34b
34,664
def sanitize_sql(sql, keep_transaction=False): """Sanatize the sql string """ # remove comments string = remove_comments(sql) # remove transactionals if not keep_transaction: string = remove_transactional(string) # remove new lines string = remove_newlines(string) # remove empty statements string = remove_empty_statements(string) # split into multiple statements return split_statements(string)
9ef3c12b823f9eabc4f6b61fe389ea68db6c209d
34,665
def create_whimsy_computation_lambda_empty(): """Returns a lambda computation and type `( -> <>)`.""" value = computation_factory.create_lambda_empty_struct() type_signature = computation_types.FunctionType(None, []) return value, type_signature
741629cd80ba4bbaf27af22d4061226176dfc683
34,666
def fire_weather_index(isi, bui): """Fire weather index. Parameters ---------- isi : array Initial spread index bui : array Build up index. Returns ------- array Build up index. """ fwi = np.where( bui <= 80.0, 0.1 * isi * (0.626 * bui ** 0.809 + 2.0), # *Eq.28a*# 0.1 * isi * (1000.0 / (25.0 + 108.64 / np.exp(0.023 * bui))), ) # *Eq.28b*# fwi[fwi > 1] = np.exp(2.72 * (0.434 * np.log(fwi[fwi > 1])) ** 0.647) # *Eq.30b*# return fwi
bae3f683a2870c36ce1b3c0c6f33d872968f851c
34,667
from typing import Optional import logging def read_file(filename: str) -> Optional[str]: """ Read a common file and return its content. Returns ------- content The file content """ try: with open(filename, 'r') as f: content = f.read return content except IOError as e: logging.error(f'Error reading file {filename}.') logging.error(e)
46ceb903af8b655edf85588d31987e02a7667ef4
34,668
def power(b, e): """ @purpose: Using a binary list to calculate power of two integers @param: b: The base number e: The exponent @precondition: A valid positive base and exponent are input @postcondition: The power of b^e is print out @Complexity: Best Case: O(1) if exponent < 0 Worst Case: O( ) """ if e < 0: return "Please input positive exponents" else: rev_binary = binary(e) result = 1 idx = len(rev_binary) - 1 while idx >= 0: result = result * result if rev_binary[idx]: result = result * b idx -= 1 return result
f510642c8b3eee9eac231b33d2e5260855c4bbf2
34,669
def get_all_items(): """Get all items""" items = Item.query.all() items_list = [] for item in items: item_object = { 'id': item.id, 'subject': item.subject, 'status' : item.status, 'url': item.url, 'requestor': item.requestor, 'maintainer': item.maintainer, 'created_at': item.created_at, 'updated_at': item.updated_at, 'due_date': item.due_date } items_list.append(item_object) response_object = { 'status': 'success', 'data': { 'items': items_list } } return jsonify(response_object), 200
0dadd886096f8a3bcea2413830c70a89b4eb06fb
34,670
def usergenerator(no1, no2, no3, no4, mode): """ 生成中文拼音和随机字母组成的用户名 :param no1 表示声母: :param no2 表示韵母: :param no3 表示第一位随机字母: :param no4 表示第二位随机字母: :param mode 选择姓名的次序: :return 返回用户名: """ list1 = ['b', 'p', 'm', 'f', 'd', 't', 'n', 'l', 'g', 'k', 'h', 'j', 'q', 'x', 'zh', 'ch', 'sh', 'r', 'z', 'c', 's', 'y', 'w', ''] #声母表,共24个 list2 = ['a', 'o', 'e', 'i', 'u', 'v', 'ai', 'ei', 'ui', 'ao', 'ou', 'iu', 'ie', 've', 'er', 'an', 'en', 'in', 'un', 'vn', 'ang', 'eng', 'ing', 'ong', 'ian', 'uan', 'van', 'uen', 'iang', 'uang', 'ueng', 'iong'] #韵母表,共32个 list3 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] #字母表, 共26个 list4 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ''] #字母表加空白, 共27个 if mode == 1: username = list1[no1] + list2[no2] + list3[no3] + list4[no4] elif mode == 2: username = list3[no3] + list4[no4] + list1[no1] + list2[no2] else: print('No mode expected') return username
0875297000dc00bb3a6ba46844993047137261ec
34,671
def verify_input(json_data): """ Verifies the validity of an API request content :param json_data: Parsed JSON accepted from API call :type json_data: dict :return: Data for the the process function """ # callback_uri is needed to sent the responses to if 'callback_uri' not in json_data: raise ValueError('callback_uri not supplied') # Verify data was sent if 'data' not in json_data: raise ValueError('no data to predict for!') # Verify data structure if not isinstance(json_data['data'], dict): raise ValueError('jsondata["data"] must be a mapping between unique id and features') # Verify data scheme for unique_id, features in json_data['data'].items(): feature_names = features.keys() feature_values = features.values() # Verify all features needed were sent if not all([feature in feature_names for feature in FEATURES]): raise ValueError('For each example all of the features [{}] must be present'.format(FEATURES)) # Verify all features that were sent are floats if not all([isinstance(value, float) for value in feature_values]): raise ValueError('All feature values must be floats') return json_data
77f609923bd774732c1233413633b077d47e5919
34,672
def detail_slug_dct(slug): """ Function to localize Slug's detail properties. :param slug: model Slug :return: dictionary with Slug's detail properties localized """ return _detail_slug_form.fill_with_model(slug)
13d7f41c706a45bf4534cc8be9f2be14e31bc6bd
34,673
import warnings def is_myst_available(): """Whether the myst-parser package is available.""" if myst_parser is None: return False major, minor = myst_parser.__version__.split(".")[:2] if int(major) < 1 and int(minor) < 8: warnings.warn("The installed myst-parser version is less than the required 0.8") return False return True
15b54b642e2a4096438f41b12ac2c6b83b651716
34,674
def CreateTrimmedSurface(trimSource, surfaceSource, multiple=False): """ Constructs a Brep using the trimming information of a brep face and a surface. Surface must be roughly the same shape and in the same location as the trimming brep face. Args: trimSource (BrepFace): BrepFace which contains trimmingSource brep. surfaceSource (Surface): Surface that trims of BrepFace will be applied to. Returns: Brep: A brep with the shape of surfaceSource and the trims of trimSource or None on failure. """ url = "rhino/geometry/brep/createtrimmedsurface-brepface_surface" if multiple: url += "?multiple=true" args = [trimSource, surfaceSource] if multiple: args = list(zip(trimSource, surfaceSource)) response = Util.ComputeFetch(url, args) response = Util.DecodeToCommonObject(response) return response
5b317a6c64c3607feb3338844a505e3b62fde970
34,675
def formatdatetime(datatimes): """ 格式化日期时间为指定格式 :param datatimes: 数据库中存储的datetime日期时间,也可以是字符串形式(2021-09-23 11:22:03.1232000) :return: 格式化后的日期时间如:2021-09-23 11:22:03 """ if datatimes: try: if isinstance(datatimes, str): if "." in datatimes: arrays = datatimes.split(".",maxsplit=1) if arrays: return arrays[0] return datatimes.strftime('%Y-%m-%d %H:%M:%S') except Exception as e: return datatimes return datatimes
8346fe27eb27994a647837c8b280e04e178c91d4
34,677
def get_difference(stocks: pd.DataFrame) -> pd.DataFrame: """Calculates the gains or loss for each stock.""" stocks = stocks.astype({"closing_price": "float", "initial_value": "float"}) stocks["gain_loss"] = stocks["closing_price"] - stocks["initial_value"] stocks["gain_loss"] = stocks["gain_loss"].round(2) return stocks
141caa895a6d5761e41f0656307c851c64df2df5
34,678
import math def random_mini_batches(X, Y, batch_size=64, seed=0): """ Creates a list of random minibatches from (X, Y) Arguments: X -- input data, of shape (number of examples, input size) Y -- true "label" vector of shape (number of examples, number of features) batch_size -- size of the mini-batches, integer seed -- this is only for the purpose of grading, so that you're "random minibatches are the same as ours. Returns: mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y) """ m = X.shape[0] # number of training examples mini_batches = [] np.random.seed(seed) # Step 1: Shuffle (X, Y) permutation = list(np.random.permutation(m)) shuffled_X = X[permutation, :] shuffled_Y = Y[permutation, :].reshape((m, Y.shape[1])) # Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case. num_minibatches = math.floor(m/batch_size) for k in range(0, num_minibatches): mini_batch_X = shuffled_X[k*batch_size:k*batch_size + batch_size, :] mini_batch_Y = shuffled_Y[k*batch_size:k*batch_size + batch_size, :] mini_batch = (mini_batch_X, mini_batch_Y) mini_batches.append(mini_batch) # Handling the end case (last mini-batch < batch_size) if m % batch_size != 0: mini_batch_X = shuffled_X[num_minibatches*batch_size:m, :] mini_batch_Y = shuffled_Y[num_minibatches*batch_size:m, :] mini_batch = (mini_batch_X, mini_batch_Y) mini_batches.append(mini_batch) return mini_batches
ee6eec6d90a61f33c44fa01ced15e9a718a4a58e
34,679
def stelab(pobj: ndarray, vobs: ndarray) -> ndarray: """ Correct the apparent position of an object for stellar aberration. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/stelab_c.html :param pobj: Position of an object with respect to the observer. :param vobs: Velocity of the observer with respect to the Solar System barycenter. :return: Apparent position of the object with respect to the observer, corrected for stellar aberration. """ pobj = stypes.to_double_vector(pobj) vobs = stypes.to_double_vector(vobs) appobj = stypes.empty_double_vector(3) libspice.stelab_c(pobj, vobs, appobj) return stypes.c_vector_to_python(appobj)
ebdead6d87c4f916afcca8897758fb189fa4a58a
34,680
import tqdm import torch def train(train_loader, model, args, optimizer, scheduler, epoch, device, writer=None): """Train for one epoch on the training set""" # switch to train mode model.train() print('\nEpoch: %d' % epoch) train_loss = 0 total = 0 correct = 0 for j, (input, target) in tqdm(enumerate(train_loader), total = len(train_loader)): optimizer.zero_grad() input = input.to(device) target = target.to(device) if args.double: input = input.double() output = model(input) loss =F.cross_entropy(output, target, reduction = 'mean') pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability correct += pred.eq(target.view_as(pred)).sum().item() train_loss += loss.item() loss.backward() with torch.no_grad(): if args.directional: V = {} if args.mage: x = input.view(input.shape[0],-1).clone() device =x.device dtype = x.dtype epsilon = 1 eps = 1E-6 dFg = 0 for i, linop in enumerate(model.linops): ##import pdb; pdb.set_trace() if args.mage: W = linop.weight B = linop.bias vn = torch.randn([W.shape[0],1],device =device, dtype = dtype) *epsilon vb = vn.clone().squeeze().expand(B.shape) if args.normalize_v: z = x/(x.norm(dim=1,keepdim = True)+ eps) vw = torch.matmul(vn,z.unsqueeze(1)) ## M X 1 mm B X 1 X N -> B X M X N else: vw = torch.matmul(vn,x.unsqueeze(1)) batch_size = vw.shape[0] dFg = dFg + (linop.weight.grad*vw).sum([1,2]).view([batch_size, 1]) ## B x 1 x = linop(x) if i < len(model.linops) - 1: x = model.act(x) else: vw = torch.randn_like(linop.weight) vb = torch.randn_like(linop.bias) dFg = dFg + (linop.weight.grad*vw).sum() dFg = dFg + (linop.bias.grad*vb).sum() V[i] = (vw, vb) for i, linop in enumerate(model.linops): vw, vb = V[i] if args.mage: linop.weight.grad = torch.matmul(dFg.permute(1,0), vw.view(batch_size,-1)).view(vw.shape[1],vw.shape[2]) ## 1 x B mm Bx(N1xN2) > N1 x N2 else: linop.weight.grad = (linop.weight.grad*vw).sum() * (vw) linop.bias.grad = (linop.bias.grad*vb).sum() * (vb) torch.nn.utils.clip_grad_norm_(model.parameters(), 0.3) total += input.size(0) optimizer.step() if args.cosine: scheduler.step() else: scheduler.step() ## steps_lr(optimizer,args,epoch) train_acc = (100. * correct / len(train_loader.dataset)) train_loss = train_loss/total if writer is not None: writer.add_scalar('train/loss', train_loss, epoch) writer.add_scalar('train/acc', train_acc, epoch) for i,linop in enumerate(model.linops) : if i == 0: stri="" else: stri = f"{i}" writer.add_scalar(f'L2norm/weight{stri}', linop.weight.norm().item(), epoch) if not linop.bias is None: writer.add_scalar(f'L2norm/bias{stri}', linop.bias.norm().item(), epoch) writer.add_scalar('lr/scheduler', optimizer.param_groups[0]['lr'], epoch) return train_loss, train_acc
55f25cf0d7ed93a973443442ad93ba5ed0eea0ba
34,681
def add_noise(input_image, noise, multiple_image_std, size=224): """Transformation of a single image by adding noise. If a random gaussian distribution of noisy is specified (noise='r_normal'), the standard deviation of the noise added is based upon the dynamic range of the image weighed by multiple_image_std argument. This appears to work well empirically, and is the subject of additional research. Args: input_image: A single input image, float32 tensor noise: String that specifies the distribution of noise to add as either a gaussian distribution (r_normal) or a uniform distribution (r_uniform). multiple_image_std: Weight to place on the range of input values. size: size of noise matrix (should match image size) Returns: noisy_image: The input with the addition of a noise distribution. Raises: ValueError: Raised if the string specifying the noise distribution does not correspond to the noise implementations. """ if noise == 'r_normal': image_min = tf.reduce_min(input_image) image_max = tf.reduce_max(input_image) diff = tf.reduce_mean(tf.subtract(image_max, image_min)) range_ = tf.to_float(tf.multiply(tf.constant([multiple_image_std]), diff)) noise = tf.random_normal( shape=[size, size, 3], stddev=range_, dtype=tf.float32) elif noise == 'r_uniform': percentile_ = tfp.stats.percentile(input_image, q=10.) noise = tf.random.uniform( minval=-percentile_, maxval=percentile_, shape=[size, size, 3], dtype=tf.float32) else: raise ValueError('Noise type not found:', noise) noisy_image = tf.add(input_image, noise) return noisy_image
99f290f498b6abea5d592787ee60a137d805ff33
34,682
def evaluate_topic_models(data, varying_parameters, constant_parameters=None, n_max_processes=None, return_models=False, metric=None, **metric_kwargs): """ Compute several Topic Models in parallel using the "gensim" package. Calculate the models using a list of varying parameters `varying_parameters` on a single Document-Term-Matrix `data`. Pass parameters in `constant_parameters` dict to each model calculation. Use at maximum `n_max_processes` processors or use all available processors if None is passed. `data` must be a Document-Term-Matrix (NumPy array/matrix, SciPy sparse matrix). Will return a list of size `len(varying_parameters)` containing tuples `(parameter_set, eval_results)` where `parameter_set` is a dict of the used parameters and `eval_results` is a dict of metric names -> metric results: .. code-block:: text [(parameter_set_1, {'<metric_name>': result_1, ...}), ..., (parameter_set_n, {'<metric_name>': result_n, ...})]) .. seealso:: Results can be simplified using :func:`tmtoolkit.topicmod.evaluate.results_by_parameter`. :param data: a (sparse) 2D array/matrix :param varying_parameters: list of dicts with parameters; each parameter set will be used in a separate evaluation :param constant_parameters: dict with parameters that are the same for all parallel computations :param n_max_processes: maximum number of worker processes to spawn :param return_models: if True, also return the computed models in the evaluation results :param metric: string or list of strings; if given, use only this metric(s) for evaluation; must be subset of `available_metrics` :param metric_kwargs: dict of options for metric used metric(s) :return: list of evaluation results for each varying parameter set as described above """ mp_eval = MultiprocEvaluationRunner(MultiprocEvaluationWorkerGensim, AVAILABLE_METRICS, data, varying_parameters, constant_parameters, metric=metric or DEFAULT_METRICS, metric_options=metric_kwargs, n_max_processes=n_max_processes, return_models=return_models) return mp_eval.run()
01ad43f2ab07dbbd3c64e2a9bc8ee3b7f5fddfad
34,684
from re import T def n_step_bootstrapped_returns(r_t: T, discount_t: T, v_t: T, targets: T, lambda_t: T, seq_len: int, n: int) -> T: """Computes strided n-step bootstrapped return targets over a sequence. The returns are computed according to the below equation iterated `n` times: Gₜ = rₜ₊₁ + γₜ₊₁ [(1 - λₜ₊₁) vₜ₊₁ + λₜ₊₁ Gₜ₊₁]. When lambda_t == 1. (default), this reduces to Gₜ = rₜ₊₁ + γₜ₊₁ * (rₜ₊₂ + γₜ₊₂ * (... * (rₜ₊ₙ + γₜ₊ₙ * vₜ₊ₙ ))). Args: r_t: rewards at times [1, ..., T]. discount_t: discounts at times [1, ..., T]. v_t: state or state-action values to bootstrap from at time [1, ...., T]. n: number of steps over which to accumulate reward before bootstrapping. lambda_t: lambdas at times [1, ..., T]. Shape is [], or [T-1]. stop_target_gradients: bool indicating whether or not to apply stop gradient to targets. Returns: estimated bootstrapped returns at times [0, ...., T-1] """ # Work backwards to compute n-step returns. for i in reversed(range(n)): r_ = r_t[i:i + seq_len] discount_ = discount_t[i:i + seq_len] lambda_ = lambda_t[i:i + seq_len] v_ = v_t[i:i + seq_len] targets = r_ + discount_ * ((1. - lambda_) * v_ + lambda_ * targets) return targets
ec729b840a47f4d37eff65f5e7c36a7467237fc2
34,685
import requests import json def questions (category, token): """Contacts API and retrieves questions + answers based on category""" # Retrieve questions and answers from API try: response = requests.get(f"https://opentdb.com/api.php?amount=1&category={category}&type=multiple&token={token}") response.raise_for_status() except requests.RequestException: return None # Turn JSON format into a python dictionary response = json.loads(response.text) # Check for Response Code if response['response_code'] == 0: # A dictionary keyed by an integer with values being dicts as values question + (incorrect)answers try: question_list = [] for i, item in enumerate(response['results']): question_list.append({}) question_list[i]['question'] = item['question'] question_list[i]['correct'] = item['correct_answer'] question_list[i]['incorrects'] = item['incorrect_answers'] except (KeyError, TypeError, ValueError): return None # Something went wrong with the API else: return None return question_list
7ff86a66e82dd442fc57b68ac02a7b793336d290
34,686
async def reset_clean_filter_timer(obj): """Reset the Clean Filter indicator timer.""" return await obj["madoka"].reset_clean_filter_timer.update(ResetCleanFilterTimerStatus())
a746aa0ce2527dc3a135c4ab71d8841f133b85bb
34,687
def getFigureSpec(iteration: int, perceptual: bool): """ Get 2x2 Figure And Axis Parameters ---------- iterations : int perceptual : bool If true, generate the axis of perceptual loss Return ------ fig, axis : matplotlib.figure.Figure, matplotlib.axes.Axes The plotting instance. """ fig, grids = plt.figure(figsize=(19.2, 10.8)), gridspec.GridSpec(2, 2) axis = [ fig.add_subplot(gs) for gs in grids ] for ax in axis: ax.set_xlabel("Epoch(s) / Iteration: {}".format(iteration)) # Linear scale of Loss axis[0].set_ylabel("Image Loss") axis[0].set_title("Loss") # Log scale of Loss axis[1].set_yscale("log") axis[1].set_ylabel("Image Loss") axis[1].set_title("Loss (Log scale)") # PSNR axis[2].set_title("Average PSNR") # Learning Rate axis[3].set_yscale('log') axis[3].set_title("Learning Rate") # Add TwinScale for Perceptual Loss if perceptual: axis.append( axis[0].twinx() ) axis[4].set_ylabel("Perceptual Loss") axis.append( axis[1].twinx() ) axis[5].set_ylabel("Perceptual Loss") return fig, axis
2003ce5d4ddfa316ba5bd56bfb5150d9c96b96ab
34,688