content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_econstraints(unknowns, segment):
""" Runs the mission if the equality constraint values are needed
Assumptions:
N/A
Inputs:
state.unknowns [Data]
Outputs:
constraints [array]
Properties Used:
N/A
... | 5,285,800 |
def mkdir(path: str, mode: int = 0o777, *,
dir_fd: Optional[int] = None) -> None:
"""Makes a directory with mode
Call the corresponding :func:`IO.mkdir` upon the default handler.
The ``path`` can be a POSIX path or a URI.
"""
global _DEFAULT_CONTEXT
default_context = _DEFAULT_CONTEX... | 5,285,801 |
def adjust_learning_rate(optimizer, epoch, args, multiple):
"""Sets the learning rate to the initial LR decayed by 0.95 every 20 epochs"""
# lr = args.lr * (0.95 ** (epoch // 4))
lr = args.lr * (0.95 ** (epoch // 20))
for i, param_group in enumerate(optimizer.param_groups):
param_group['lr'] = l... | 5,285,802 |
def receipts_as_vc(tx_receipt: TxReceipt, tol_receipt: dict) -> dict:
"""Convert a raw tx receipt to an unsigned Verifiable Credential"""
# Generate a random UUID, not related to anything in the credential
uid = unique_id.uuid4().hex
# Current time and expiration
now = int(time.time())
one_yea... | 5,285,803 |
def get_filenames(is_training,datadir):
"""Returns a list of filenames."""
assert os.path.exists(datadir), (
'Can not find data at given directory!!')
if(is_training):
labels = []
data_dir = []
with open('/home/qnie/PycharmProjects/ntumotion/training_protocol/fEDM_R_CS_trainimgs.txt') as f... | 5,285,804 |
def cluster_upgrade(ctx, cluster_name, template_name, template_revision,
vdc, org_name, k8_runtime=None):
"""Upgrade cluster software to specified template's software versions.
\b
Example
vcd cse cluster upgrade my-cluster ubuntu-16.04_k8-1.18_weave-2.6.4 1
Upgrade cluster 'mycluste... | 5,285,805 |
def join_url(*sections):
"""
Helper to build urls, with slightly different behavior from
urllib.parse.urljoin, see example below.
>>> join_url('https://foo.bar', '/rest/of/url')
'https://foo.bar/rest/of/url'
>>> join_url('https://foo.bar/product', '/rest/of/url')
'https://foo.bar/product/re... | 5,285,806 |
def save_features():
""" This function is called once after the json files is created
"""
audio_samples = []
dataset_types = ['train', 'valid', 'test']
for dataset_type in dataset_types:
if dataset_type == 'train':
with open(CREATED_JSON_PATH + dataset_type + '_corpus.json') as ... | 5,285,807 |
def get_vertices(arcpyPolyline, reverse = False):
"""Returns points of a polyline feature class as orded list of points
:param arcpyPolyline:
:return: list of points
"""
try:
points = []
for part in arcpyPolyline:
for pnt in part:
if pnt:
... | 5,285,808 |
def getTaggedCommit(repository, sha1):
"""Returns the SHA-1 of the tagged commit.
If the supplied SHA-1 sum is a commit object, then it is returned,
otherwise it must be a tag object, which is parsed to retrieve the
tagged object SHA-1 sum."""
while True:
git_object = repository.f... | 5,285,809 |
def register(request):
"""User creation view."""
if settings.USE_ID_SITE:
return redirect('sample:stormpath_id_site_register')
form = StormpathUserCreationForm(request.POST or None)
if form.is_valid():
try:
form.save()
user = authenticate(
userna... | 5,285,810 |
def _get_span_replace_glob_and_regex(
range_config: range_config_pb2.RangeConfig, is_match_span: bool,
is_match_date: bool,
span_width_str: Optional[Text]) -> Union[Text, List[Text]]:
"""Replace span or date spec if static range RangeConfig is provided."""
if range_config.HasField('static_range'):
i... | 5,285,811 |
def selu(x: T.Tensor, **kwargs):
"""
SELU activation.
"""
return T.selu(x) | 5,285,812 |
def main():
"""
Program entry point
:return: None
"""
args = parse_args()
p = ProfileManager(args)
p.run() | 5,285,813 |
def start():
"""Start the application servers"""
sudo("/etc/init.d/apache2 start") | 5,285,814 |
def edge_detect(image):
"""
this function will get an image as an input convert it to grayscale apply Gaussian Blurring and Canny Edge detection
then it will return the output image
"""
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gau_blurred = cv2.GaussianBlur(gray_image,(5,5),0)
return cv2.Canny(gau_b... | 5,285,815 |
def solve_classical_ising(J, N, pos):
"""
function to solve classical optimization problem defined by graph
"""
# define and build classical Ising
model, linear, quad, offset = build_classical_ising(J, N)
# Solve classical Ising model
solution = solve_ising(linear, quad)
# print calss... | 5,285,816 |
def load_fueltech_map(fixture_name):
"""
Reads the CSV to load the fueltech map
Fields are:
fuel_source,fuel_source_desc,tech,tech_desc,fueltech_map,load_type
"""
MAP_KEYS = [
"fuel_source",
"fuel_source_desc",
"tech",
"tech_desc",
"load_ty... | 5,285,817 |
def fix_class_scope(rules):
"""
Because otherwise class_type consume last id after ::
and it is not possible to recover
"""
r = rule_by_name(rules, "class_scope")
_inline_rule([r, ], rule_by_name(rules, "class_type")) | 5,285,818 |
def info_df_row(request: SubRequest) -> pd.Series:
"""Create a pd.Series that mimicks a row from the info DataFrame."""
name, num, start, end, word = request.param
data = {"seg_num": num, "seg_start_idx": start, "seg_end_idx": end, "word_id": word}
return pd.Series(data=data, name=name) | 5,285,819 |
def precision_formatter(layer: Layer):
"""Format Dot nodes by layer precision"""
formatting = {'style': 'filled',
'tooltip': layer.tooltip(),
'fillcolor': precision_colormap[layer.precision]}
return formatting | 5,285,820 |
def extend_columns_eventbased(orig_df):
"""
Handles adding extra columns based on a condition the value of another column.
:param orig_df: the original dataframe
:return: a new, modified dataframe
"""
global COL_NAMES_NEW_FROM_EXTENSION
global COL_NAMES_TO_DROP_FROM_EXTENSION
#... | 5,285,821 |
def check_git_branch():
"""
Check if the local branch is the same than the connected Odoo DB and
checkout to match it if needed.
"""
server = get_odoo_server_url()
if server:
urllib3.disable_warnings()
http = urllib3.PoolManager(cert_reqs='CERT_NONE')
try:
res... | 5,285,822 |
def test_update_with_bittrex(limit_buy_order, limit_sell_order, fee, caplog):
"""
On this test we will buy and sell a crypto currency.
Buy
- Buy: 90.99181073 Crypto at 0.00001099 BTC
(90.99181073*0.00001099 = 0.0009999 BTC)
- Buying fee: 0.25%
- Total cost of buy trade: 0.001002500 BTC
... | 5,285,823 |
def test_non_presented_child(protocol_version, return_value):
"""Test non presented sensor child."""
gateway = get_gateway(protocol_version=protocol_version)
sensor = get_sensor(1, gateway)
gateway.logic('1;0;1;0;23;43\n')
assert 0 not in sensor.children
ret = gateway.run_job()
assert ret ==... | 5,285,824 |
def stable_reward_gen(reward):
"""
Always yields reward
:param reward:
:return:
"""
while True:
yield reward | 5,285,825 |
def incidents_per_year_generator(data):
"""
Generate incidents per year graph
Parameters:
-----------
data: dataframe
Returns:
incidents_per_year: dcc.Graph
"""
data['n_injured+killed'] = data['n_injured'] + data['n_killed']
casualties_by_year = data[['year', 'n_killed', 'n_in... | 5,285,826 |
def saveToFile(inputFile, outputFileName):
"""Writes to a csv file.
"""
outputFile = outputFileName
inputfile = inputFile
output= codecs.open(os.path.join(outputDir, outputFile) + '.csv' ,'w')
Fieldnames = inputfile[0].keys()
wr = csv... | 5,285,827 |
def join_sqlite(
dataset,
file=None,
table_name=None,
compile=False,
debug=False,
quiet=False,
use_cache=True,
):
"""Install scripts in sqlite."""
if not table_name:
table_name = "{db}_table"
if not file:
file = os.path.join(DATA_DIR, "sqlite.db")
args = {
... | 5,285,828 |
def apps_users(app, **kwargs):
"""List all users for an application"""
app = _okta_get("apps", app,
selector=_selector_field_find("label", app))
app_id = app["id"]
rv = okta_manager.call_okta(f"/apps/{app_id}/users", REST.get)
rv.sort(key=lambda x: x["credentials"]["userName"])
... | 5,285,829 |
def make_cont_plot(zfunc, rates, levels=None, title=""):
"""Helper function to make a contour plot."""
dens = np.logspace(-6, -2, 100)
ienergy = np.linspace(100, 700, 100)
gridd, gridt = np.meshgrid(dens, ienergy)
temp = rates.get_temp(np.median(gridd)*np.ones_like(gridt), gridt)
cs = plt.cont... | 5,285,830 |
def decode_for_output(output, target_stream=None, translation_map=None):
"""Given a string, decode it for output to a terminal.
:param str output: A string to print to a terminal
:param target_stream: A stream to write to, we will encode to target this stream if
possible.
:param dict translatio... | 5,285,831 |
def create_null(n):
""" Creates empty data containers.
Empty data containers can be used for headless callbacks.
They can also be used to store information on the client side"""
return html.Div(children=[dcc.Store(id=f'null{i}', data=[]) for i in range(n)]) | 5,285,832 |
def colorline(
x, y, z=None, cmap=plt.get_cmap('copper'),
linewidth=3, alpha=1.0):
"""
http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
http://matplotlib.org/examples/pylab_examples/multicolored_line.html
Plot a colored line with coordinates x and ... | 5,285,833 |
def populate_data_store(data_store, assignment_id=None, episode_ids=None,
steps_per_episode_chunk=None):
"""Populate a datastore with an assignment.
Args:
data_store: data_store.DataStore instance to populate.
assignment_id: Assignment ID to create or ASSIGNMENT_ID if this is None.
... | 5,285,834 |
def create_pip_configuration(options):
# type: (Namespace) -> PipConfiguration
"""Creates a Pip configuration from options registered by `register`.
:param options: The Pip resolver configuration options.
"""
if options.cache_ttl:
pex_warnings.warn("The --cache-ttl option is deprecated and... | 5,285,835 |
def get_motifs(cbn: CausalBayesianNetwork, path: Sequence[str]) -> List[str]:
"""classify the motif of all nodes along a path as a forward (chain), backward (chain), fork,
collider or endpoint"""
for node in path:
if node not in cbn.nodes():
raise KeyError(f"The node {node} is not in the... | 5,285,836 |
def update_manifest_node(node: manifest.ManifestNode) -> bool:
"""Updates NODE in stateful manifest so it is preserved even as we traverse models unless dbt is refreshed"""
ctx.dbt.update_node(node)
# ctx.dbt.build_flat_graph()
return True | 5,285,837 |
def validate_data(data, allow_restricted_fields, kind):
"""
Check that all the fields in `data` correspond to fields in
`ALLOWED_ENTITIES[kind]`. `data` is a dictionary/dictionary subclass, `kind`
is the datastore entity kind. `allow_restricted_fields` is a bool.
"""
if kind not in ALLOWED_ENTIT... | 5,285,838 |
def test_stats_running_average():
""" restest: test internal: stats_running_average() """
stats1 = {'diff_bytes': (0, 92955), 'diff_bytes_prev': (0, 92955), 'diff_count': (0, 7), 'diff_count_prev': (0, 7), 'repair_power': 0, 'error': 0.0}
stats2 = {'diff_bytes': (4, 92955), 'diff_bytes_prev': (4, 92955), 'd... | 5,285,839 |
def sync_website_content(website_name: str):
""" Commit any unsynced files to the backend for a website """
try:
website = Website.objects.get(name=website_name)
except Website.DoesNotExist:
log.debug(
"Attempted to update backend for Website that doesn't exist: name=%s",
... | 5,285,840 |
def get_attr_lang(src, attr, default_locale):
"""
Our index stores localized strings in elasticsearch as, e.g.,
"name_spanish": [u'Nombre']. This takes the current language in the
threadlocal and gets the localized value, defaulting to
settings.LANGUAGE_CODE.
"""
req_lang = amo.SEARCH_LANGUA... | 5,285,841 |
def share_in_range(x,omegas_low,omegas_high):
""" calculate share in range """
# a. allocate memory and inialize
Nomegas = omegas_low.size
Ntrue = np.zeros(Nomegas)
Nactive = 0
# b. compute
for i in range(x.size):
if ~np.isnan(x[i]):
Nactive += 1
for h in r... | 5,285,842 |
def parse_inFile(fileName):
"""
Parses a .cmsisdata file to extract the information necessary for project connection file creation
Returns a tuple of (project_name device_name core linker_script defineList includePathList cSrcList asmSrcList headersList libsList)
"""
inFileData = namedtuple('inFile... | 5,285,843 |
def trio_hits(l_contig, mid_contig_end, blast_hits, olap_dict, cont_dict):
"""
From a unique contig (l_contig), steps across a repeat (mid_contig) to find the next unique contig,
based on best case of adjacent hits in a reference genome (product of the two blast scores).
Called by grow_scaffold()
""... | 5,285,844 |
def remove():
"""Remove a vegetable from the current user's vegetables"""
# Check if the user already has that vegetable
user_veg = []
for vegetable in db.execute('SELECT plant_id FROM users_plants WHERE user_id=?', session['user_id']):
user_veg.append(vegetable['plant_id'])
new_veg = int(... | 5,285,845 |
def get_formatted_date(date: datetime.datetime) -> str:
""" Formatted date """
return date.isoformat()[:10] | 5,285,846 |
def get_submission_max_ram(session, submission_id):
"""Get the max amount RAM used by a submission during processing.
Parameters
----------
session : :class:`sqlalchemy.orm.Session`
The session to directly perform the operation on the database.
submission_id : int
The id of the subm... | 5,285,847 |
def is_dir(path: str, basedir):
"""Takes a dot separated directory path"""
maybe_path = _parse_path(path, basedir)
return os.path.isdir(maybe_path) | 5,285,848 |
def uuid_to_cbuuid(uuid):
"""Convert native Python UUID type to Objective-C CBUUID type."""
return CBUUID.UUIDWithString_(str(uuid)) | 5,285,849 |
def solve(a, b): # pragma: no cover
"""Solve the linear system `a x = b`.
Args:
a (tensor): LHS `a`.
b (tensor): RHS `b`.
Returns:
tensor: Solution `x`.
""" | 5,285,850 |
def is_valid_hostname(hostname):
"""
Check that hostname passed in is valid.
Pretty much a copy paste of this
https://stackoverflow.com/questions/2532053/validate-a-hostname-string
"""
if len(hostname) > 255:
return False
if hostname[-1] == ".":
hostname = hostname[:-1] # st... | 5,285,851 |
def go_binary(name, **kwargs):
"""Wraps the standard go_binary.
Args:
name: the rule name.
**kwargs: standard go_binary arguments.
"""
_go_binary(
name = name,
**kwargs
) | 5,285,852 |
def test_project_paths_basics():
"""
Test basics
"""
paths = ProjectPaths(ROOT)
assert str(paths.root.name) == ROOT
assert paths.root == paths(ProjectPaths.UID_ROOT) | 5,285,853 |
def edit_player_position(players: list[dict]) -> None:
"""Edit the selected players position."""
number: int = get_lineup_number(players, "Lineup number: ")
player: Player = players[number-1]
print("You selected " + player.full_name + " POS=" + player.position)
position: str = get_player_positi... | 5,285,854 |
def concat_data(years):
"""
Convert to long format, add 'Year' and concatenate into one DataFrame
"""
data = []
for year in years:
for file in glob.glob(os.path.join("CSV", str(year), "*.csv")):
csv_data = pd.read_csv(file)
csv_data = pd.melt(csv_data, id_vars=["name"... | 5,285,855 |
def save_data(name, data):
"""save data to file json"""
arq = open(name + ".txt", "a")
arq.write(str(data))
arq.write("\n")
arq.close() | 5,285,856 |
def delta_soga_from_masso(m_orig, m_new, s_orig):
"""Infer a change in global average salinity from mass"""
delta_s = s_orig * ((m_orig / m_new) - 1)
return delta_s | 5,285,857 |
def find_packages_source_files(
packages_path: Union[str, Path]
) -> Dict[str, List[Path]]:
"""
List packages source files.
Args:
packages_path: Path to the packages root directory
Returns:
Mapping (package name, source files list)
"""
package_files = OrderedDict()
for ... | 5,285,858 |
def plot_children(fig, box, level=0, printit=True):
"""Simple plotting to show where boxes are."""
import matplotlib
import matplotlib.pyplot as plt
if isinstance(fig, matplotlib.figure.Figure):
ax = fig.add_axes([0., 0., 1., 1.])
ax.set_facecolor([1., 1., 1., 0.7])
ax.set_alpha... | 5,285,859 |
def test_column_values_to_be_between():
"""
Check ColumnValuesToBeBetween
"""
column_profile = ColumnProfile(
min=1,
max=3,
)
res_ok = validate(
ColumnValuesToBeBetween(
minValue=0,
maxValue=3,
),
col_profile=column_profile,
... | 5,285,860 |
def calc_sha(obj):
"""Calculates the base64-encoded SHA hash of a file."""
try:
pathfile = Path(obj)
except UnicodeDecodeError:
pathfile = None
sha = hashlib.sha256()
try:
if pathfile and pathfile.exists():
return base64.b64encode(pathfile.read_hash('SHA256'))
... | 5,285,861 |
def L_model_backward(AL, Y, caches):
"""
Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group
Arguments:
AL -- probability vector, output of the forward propagation (L_model_forward())
Y -- true "label" vector (containing 0 if non-cat, 1 if cat)
caches --... | 5,285,862 |
def book_generator(config):
""" Generates an infinite sequence of books.
Once it's been through the entire database it will start again from the beginning.
"""
while True:
with open(config.books_file) as db:
for line in db:
yield make_book(config, line) | 5,285,863 |
def load_gt_graph(graph_path):
"""Load a graph in graphml or gt format."""
from graph_tool.all import load_graph
logger.info(f"loading the generated graph file from {graph_path}")
g = load_graph(graph_path)
return g | 5,285,864 |
def generate_key(name: str) -> str:
"""
Given a display name, generate a global unique value suitable
for use as a step key in Buildkite.
"""
norm = name.lower()
for regex in (RE_NONID, RE_MULTI_US):
norm = regex.sub('_', norm)
if norm not in KEY_COUNT:
KEY_COUNT[norm] = 1
... | 5,285,865 |
def get_session():
""" Set tf backend to allow memory to grow, instead of claiming everything """
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
return tf.Session(config=config) | 5,285,866 |
def read_pcd_to_exchange_lut():
"""
Produces all unique postcode-to-exchange combinations from available data, including:
'January 2013 PCP to Postcode File Part One.csv'
'January 2013 PCP to Postcode File Part Two.csv'
'pcp.to.pcd.dec.11.one.csv'
'pcp.to.pcd.dec.11.two.csv'
'from_tomasso_v... | 5,285,867 |
def get_axis_lims_con(epoch):
"""
Generates an invisible mne.viz.plot_topomap plot and gets the ylim from its
matplotlib.axes._subplots.AxesSubplot. Helper function for plot_connectivity.
Parameters:
epoch: mne.epochs.Epochs
MNE epochs object containing the timestamps.
... | 5,285,868 |
def osdn(url: str) -> str:
""" OSDN direct links generator """
osdn_link = 'https://osdn.net'
try:
link = re.findall(r'\bhttps?://.*osdn\.net\S+', url)[0]
except IndexError:
reply = "`No OSDN links found`\n"
return reply
page = BeautifulSoup(
requests.get(link, allow_... | 5,285,869 |
def abox2bbox(aboxes):
"""covnert affine boxes to bounding point box
reference: https://www.iquilezles.org/www/articles/ellipses/ellipses.htm
Args:
aboxes ([np.ndarray]): affine boxes shape with [*, 3, 3]
"""
c = aboxes[..., :2, 2]
e = np.linalg.norm(aboxes[..., :2, :2], ord=2, axis=-... | 5,285,870 |
def show_face():
""" Send name of detected face to server
- param name: Name of the face
- ptype name: String
"""
global detect_count
cam = cv2.VideoCapture(DEVICE_NUMBER)
cam.set(3, WIDTH)
cam.set(4, HEIGHT)
minW, minH = 0.1 * cam.get(3), 0.1 * cam.get(4)
recognizer = cv2.face.L... | 5,285,871 |
def nrrd_2_numpy(input_nrrd, return_all=False):
""" Loads nrrd data and optionally return a nrrd header
in pynrrd's format. If array is 4D, swaps axes so
that time dimension is last to match nifti standard.
"""
nrrd_data, nrrd_options = nrrd.read(input_nrrd)
if nrrd_data.ndim == 4... | 5,285,872 |
def get_evergreen_api() -> EvergreenApi:
"""Return evergreen API."""
# Pickup the first config file found in common locations.
for file in EVERGREEN_CONFIG_LOCATIONS:
if os.path.isfile(file):
evg_api = RetryingEvergreenApi.get_api(config_file=file)
return evg_api
LOGGER.... | 5,285,873 |
def make_schedule(schedule: config_pb2.Schedule) -> Callable[int, float]:
"""Creates a schedule."""
if schedule.HasField('inverse_time_decay'):
base_schedule = optimizers.inverse_time_decay(
step_size=schedule.inverse_time_decay.base,
decay_steps=schedule.inverse_time_decay.deca... | 5,285,874 |
def delete_shelf_tab(shelf_name, confirm=True):
"""The python version of the original mel script of Maya
:param shelf_name: The name of the shelf to delete
"""
try:
shelf_top_level_path = pm.melGlobals['gShelfTopLevel']
except KeyError:
# not in GUI mode
return
shelf_top... | 5,285,875 |
def procstringT0(candidate):
"""
ProcessingString validation function for T0 specs
"""
if isinstance(candidate, dict):
for candi in viewvalues(candidate):
check(r'^$|[a-zA-Z0-9_]{1,100}$', candi)
return True
else:
return check(r'^$|[a-zA-Z0-9_]{1,100}$', candidate... | 5,285,876 |
def index():
"""Return an index page."""
return render_template('index.html') | 5,285,877 |
def download_file(location, wv_user=None, wv_password=None, wv_host_name=None):
"""
Download a file from the specified URL location.
It recognizes MAGIC's Nextcloud (WebDAV) instance AND Google Drive URL's
Of course, it should work with Zenodo.
Google Drive URL's are assumed to be Spreadsheets (bot... | 5,285,878 |
def clustering_analysis(visualization=0, grade=False, trace=None):
"""
Clustering analysis wrapper which clusters the trace into repeating instructions and presents the results in the Clustering Viewer.
:param visualization: output via Clustering Viewer or output window
:param grade: grading
:param ... | 5,285,879 |
def rreplace(s, old, new, occurrence = 1):
"""
Replaces the last occurence(s) of an expression in a string.
"""
return new.join(s.rsplit(old, occurrence)) | 5,285,880 |
def purescript_test(
name,
src,
module,
args = None,
data = None,
deps = None,
ignore_warnings = False,
ffi = None,
rts_options = None,
**kwargs):
"""
Builds a test from PureScript source code.
Args:
name: A unique name... | 5,285,881 |
def get_cal_params(power_data_dict,particle_data,config_header,config_transducer):
"""
Get calibration params from the unpacked file
Parameters come from config_header and config_transducer (both from header),
as well as particle_data (from .RAW file)
"""
cal_pa... | 5,285,882 |
def text_split_feature(col, df, sep=' ', new_col_name='number_of_names'):
"""
Splits values in a string Series (as part of a DataFrame) and sums the number
of resulting items. Automatically appends summed column to original DataFrame.
PARAMETERS
----------
col : column to split
df : DataFrame wh... | 5,285,883 |
def get_decompounder():
"""
Restarts the JVM with the decompounder. It is necessary once in a while.
"""
javabridge.start_vm(class_path=["tf/jwordsplitter/target/jwordsplitter-4.2-SNAPSHOT.jar"])
java_instance = javabridge.make_instance("de/danielnaber/jwordsplitter/GermanWordSplitter", "(Z)V", Fals... | 5,285,884 |
def get_instance():
"""Return a DB API instance."""
return IMPL | 5,285,885 |
def test_beeline_command_non_isolation(mocker):
"""
Tests whether the expected beeline command is generated from CDHHook's parameters without isolation.
"""
mocker.patch.object(
BaseHook,
"get_connection",
return_value=Connection(conn_id='fake', conn_type='hive_cli',
... | 5,285,886 |
def loadfile(filename):
"""
Helper function to load content given the filename
@param filename: target file's name
@type filename: C{string}
"""
try:
f = open(filename , "r")
except IOError , e:
print >> sys.stderr, "Fail to load file %s: %s" % (filename, e)
return []... | 5,285,887 |
def save_images_to_excel(file_name, sheet_name, image_names):
"""
# 保存图形文件到excel
:param file_name: excel文件名
:param sheet_name: workSheet
:param image_names: 图像文件名列表
:return:
"""
if file_name is None or len(sheet_name) == 0 or len(image_names) == 0:
return False
if 'openpyxl'... | 5,285,888 |
def num_groups(aregex):
""" Counts groups in regexp """
return re.compile(aregex).groups | 5,285,889 |
def check_internet(url=None):
"""Check if internet is available"""
url = "https://github.com" if url is None else url
try:
urlopen(url)
except URLError as err:
return False
return True | 5,285,890 |
def test_duration():
"""Test serialization of duration.
Procedure:
- Create a new serializer.
- Create a duration object in proto
- Set value for seconds.
- Make the expected output string in ISO8601 duration format.
- Call the serialize_proto function of serializer along... | 5,285,891 |
def progress_bar_str(char_limit, max_value, current_value):
"""
Returns a pretty progress bar string, complete with colorization.
:param int char_limit: How wide the progress bar (in characters) should
be. This includes the bar and its brackets. Must be at least 6.
:param int max_value: The max... | 5,285,892 |
def post_profession_evidence(profession_id, body):
"""post_profession_evidence
Post profession evidence # noqa: E501
:rtype: Response
"""
if connexion.request.is_json:
if type(body) is not Evidence:
body = Evidence.from_dict(connexion.request.get_json())
evidence = DB... | 5,285,893 |
def histogram_metric(p_data, p_metric):
"""
Histograma y estadistidicas descriptivas
Parameters
---------
p_data: DataFrame : datos de pymes con columna de metrica
p_metric: str : nombre de la metrica
Returns
---------
fig : plotly figure : mapa de la zmg de jalisco
... | 5,285,894 |
def type_updater_columns(graph: Graph, updaters: Updaters) -> Dict:
"""Determines the types of graph columns used by Tally updaters."""
column_dependencies = tally_columns(updaters)
column_types = {
col: type_graph_column(graph, col)
for col in column_dependencies.values()
}
if set(c... | 5,285,895 |
def normpath(path):
"""Return a normalized path in canonical form."""
return os.path.normpath(path).replace(os.sep, '/') | 5,285,896 |
def manhattan_distance(problem_: rules.EightPuzzle) -> int:
""":returns: Sum of Manhattan distances for each misplaced tile."""
rv = 0
for k, v in problem_.state.items():
if v is None:
v = (problem_.height - 1, problem_.width - 1)
rv += _manhattan_distance(k, v)
return rv | 5,285,897 |
def full_conversion(inputPath):
"""Convert a single csv into identity and binding"""
read_input_csv(inputPath)
write_azure_identity(msilist)
write_azure_identity_binding(msilist)
msilist.clear | 5,285,898 |
def geo_x(arg: ir.GeoSpatialValue) -> ir.FloatingValue:
"""Return the X coordinate of `arg`, or NULL if not available.
Input must be a point.
Parameters
----------
arg
Geometry expression
Returns
-------
FloatingValue
X coordinate of `arg`
"""
op = ops.GeoX(arg... | 5,285,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.