content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from UR10 import *
u = UR10Controller('10.1.1.6')
x = URPoseManager()
x.load('t1.urpose')
print(x.getPosJoint('home'))
resp = input('hit y if you want to continue')
if resp == 'y':
x.moveUR(u,'home',30) | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Wireshark - Network traffic analyzer
# By Gerald Combs <gerald@wireshark.org>
# Copyright 1998 Gerald Combs
#
# SPDX-License-Identifier: GPL-2.0-or-later
'''Update the "manuf" file.
Make-manuf creates a file containing ethernet OUIs and their company
IDs. It merges the... | python |
from unittest import mock
import json
import time
from aiohttp import web
from aiohttp.web_middlewares import _Handler
from aiohttp.test_utils import TestClient
from typing import Any, Dict
from aiohttp_session import get_session, SimpleCookieStorage
from aiohttp_session import setup as setup_middleware
from typede... | python |
import json
import os
import dotenv
class ConfigError(Exception):
def __init__(self, field):
super().__init__(f'Missing environment variable {field}')
def get_env_var(name: str, default: str = None, prefix='', allow_empty=False):
if prefix:
env = prefix + '_' + name
else:
env = ... | python |
"""Library for Byte-pair-encoding (BPE) tokenization.
Authors
* Abdelwahab Heba 2020
* Loren Lugosch 2020
"""
import os.path
import torch
import logging
import csv
import json
import sentencepiece as spm
from speechbrain.dataio.dataio import merge_char
from speechbrain.utils import edit_distance
import speechbrain ... | python |
from ExceptionHandler import ExceptionHandler
class InputController:
def __init__(self, inputReader, exceptionHandler):
self.InputReader = inputReader
self.ExceptionHandler = exceptionHandler
def pollUserInput(self):
return self.ExceptionHandler.executeFunc()
| python |
import math
def factors(n):
results = set()
for i in range(1, int(math.sqrt(n)) + 1):
if n % i == 0:
results.add(i)
results.add(int(n/i))
return results
x = 0
i = 0
while True:
x += i
if len(factors(x)) > 500:
print(x)
i += 1
| python |
"""
MesoNet
Authors: Brandon Forys and Dongsheng Xiao, Murphy Lab
https://github.com/bf777/MesoNet
Licensed under the Creative Commons Attribution 4.0 International License (see LICENSE for details)
The method "vxm_data_generator" is adapted from VoxelMorph:
Balakrishnan, G., Zhao, A., Sabuncu, M. R., Guttag, J., & Dal... | python |
from py.test import raises
from pypy.conftest import gettestobjspace
class AppTestUnicodeData:
def setup_class(cls):
space = gettestobjspace(usemodules=('unicodedata',))
cls.space = space
def test_hangul_syllables(self):
import unicodedata
# Test all leading, vowel and trailing... | python |
# Copyright 2021 Huawei Technologies Co., Ltd.All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... | python |
class A:
def foo<caret><error descr="Method must have a first parameter, usually called 'self'">()</error>: # Add 'self'
pass
| python |
import copy
import math
import random
import typing as t
import hypemaths as hm
from ..exceptions import (
InvalidMatrixError,
MatrixDimensionError,
MatrixNotSquare,
)
from ..mixins import CopyMixin
class Matrix(CopyMixin):
def __init__(
self,
matrix: t.Union[int, float, list]... | python |
#
# Qutebrowser Config
#
from cconfig import CConfig
# Custom state full config options
cc = CConfig(config)
cc.redirect = True
# ==================== General Settings ==================================
c.hints.chars = 'dfghjklcvbnm'
c.hints.uppercase = True
c.confirm_quit = ['n... | python |
"""Misc funcs for backtester"""
import pandas as pd
from io import StringIO
from . import fb_amzn
def load_example():
"""Load example input data"""
df = pd.read_csv(StringIO(fb_amzn.data))
df['date'] = pd.to_datetime(df['date']).dt.tz_localize('US/Central')
return df
| python |
import pprint
import sys
import numpy as np
def pbatch(source, dic):
ss = np.transpose(source)
for line in ss[:10]:
for word in line:
a = dic[word]
b = a
if a == "SOS":
b = "{"
elif a == "EOS":
b = "}"
elif a =... | python |
from cryptofield.fieldmatrix import *
import unittest
class TestFMatrix(unittest.TestCase):
def testMatrixGetRow1(self):
F = FField(4)
m = FMatrix(F, 3, 3)
m.ident()
r = m.getRow(1)
ans = [FElement(F, 0), FElement(F, 1), FElement(F, 0)]
self.assertEqual(r, ans)
def testMatrix... | python |
# Generated by Django 2.2.5 on 2019-10-28 17:29
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('service', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='rating',
... | python |
def binary_search(input_array, value):
first = 0
last = len(input_array) - 1
found = False
while first <= last and not found:
middle_point = (first + last)//2
if input_array[middle_point] == value:
found = True
else:
if value < input_array[middle_point]:
... | python |
from rest_framework import permissions
class IsBuyerOrSellerUser(permissions.BasePermission):
def has_permission(self, request, view):
if request.user.is_authenticated and request.user.is_buyer_or_seller:
return True
return False
| python |
from copy import deepcopy
from dbt.contracts.graph.manifest import WritableManifest
from dbt.contracts.results import CatalogArtifact
def edit_catalog(
catalog: CatalogArtifact, manifest: WritableManifest
) -> CatalogArtifact:
output = deepcopy(catalog)
node_names = tuple(node for node in output.nodes)
... | python |
# -*- coding: utf-8 -*-
"""
encryption test_services module.
"""
import pytest
import pyrin.security.encryption.services as encryption_services
import pyrin.configuration.services as config_services
from pyrin.security.encryption.handlers.aes128 import AES128Encrypter
from pyrin.security.encryption.handlers.rsa256 i... | python |
"""
HoNCore. Python library providing connectivity and functionality
with HoN's chat server.
Packet ID definitions.
Updated 23-7-11.
Client version 2.40.2
"""
""" Server -> Client """
HON_SC_AUTH_ACCEPTED = 0x1C00
HON_SC_PING = 0x2A00
HON_SC_CHANNEL_MSG = 0x03
HON_SC_JOINE... | python |
"""A quantum tic tac toe running in command line"""
from qiskit import Aer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import CompositeGate
from qiskit import execute
import numpy as np
from composite_gates import cry,cnx,any_x,bus_or,x_bus
class Move():
def __init__(self,ind... | python |
import os
import foundations
from foundations_contrib.global_state import current_foundations_context, message_router
from foundations_events.producers.jobs import RunJob
foundations.set_project_name('default')
job_id = os.environ['ACCEPTANCE_TEST_JOB_ID']
pipeline_context = current_foundations_context().pipeline_c... | python |
class MySql(object):
pass
| python |
#!/usr/bin/env python3
#
# Author: Jeremy Compostella <jeremy.compostella@gmail.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notic... | python |
import cv2
import numpy as np
from PIL import Image, ImageDraw
from scipy.spatial import ConvexHull
from skimage import filters
import tensorflow as tf
from monopsr.core import evaluation
from monopsr.datasets.kitti import instance_utils, calib_utils
from monopsr.visualization import vis_utils
def np_proj_error(poin... | python |
#
# Copyright 2021 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
"""Test the ExpiredDataRemover object."""
import logging
import re
from datetime import datetime
from unittest.mock import patch
from uuid import uuid4
import pytz
from dateutil import relativedelta
from api.provider.models import Provider
from m... | python |
import threading
import time
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.figure import Figure
from matplotlib.widgets import Slider, Button
import logging
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-9s) %(message)s',)
class MyFigure(Figure):
def ... | python |
# MIT License
#
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | python |
#!/usr/local/bin/python3.3
def echo(message):
print(message)
return
echo('Direct Call')
x = echo
x('Indirect Call')
def indirect(func, arg):
func(arg)
indirect(echo, "Argument Call")
schedule = [(echo, 'Spam'), (echo, 'Ham')]
for (func, arg) in schedule:
func(arg)
def make(label):
def echo(me... | python |
# Copyright (c) 2015
#
# All rights reserved.
#
# This file is distributed under the Clear BSD license.
# The full text can be found in LICENSE in the root directory.
from boardfarm.devices import prompt
from boardfarm.tests import rootfs_boot
class NetperfRFC2544(rootfs_boot.RootFSBootTest):
"""Single test to s... | python |
import SimpleITK as sitk
import numpy as np
def reshape_by_padding_upper_coords(image, new_shape, pad_value=None):
shape = tuple(list(image.shape))
new_shape = tuple(np.max(np.concatenate((shape, new_shape)).reshape((2,len(shape))), axis=0))
if pad_value is None:
if len(shape)==2:
pad_... | python |
#
# PySNMP MIB module SUN-SNMP-NETRA-CT-RSC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SUN-SNMP-NETRA-CT-RSC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:12:10 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... | python |
from django.core.management.base import BaseCommand
from django.conf import settings
from ..utilities.modelwriter import *
class Command(BaseCommand):
help = 'Add a new model to an app.'
def add_arguments(self, parser):
parser.add_argument(
'app_name',
action='store',
... | python |
from test.vim_test_case import VimTestCase as _VimTest
from test.constant import *
# Recursive (Nested) Snippets {{{#
class RecTabStops_SimpleCase_ExpectCorrectResult(_VimTest):
snippets = ('m', '[ ${1:first} ${2:sec} ]')
keys = 'm' + EX + 'm' + EX + 'hello' + \
JF + 'world' + JF + 'ups' + JF + 'en... | python |
from disnake import CommandInteraction, Embed, Thread
from disnake.ext.commands import Cog, Param, slash_command
from src import Bot
from src.impl.database import Channel, ChannelMap, Message
from src.impl.utils import is_administrator
class Core(Cog):
def __init__(self, bot: Bot) -> None:
self.bot = bot... | python |
from .models import Folder, MEDIA_MODELS
def handle_uploaded_file(file, folder=None, is_public=True):
'''handle uploaded file to folder
match first media type and create media object and returns it
file: File object
folder: str or Folder isinstance
is_public: boolean
'''
_folder = None
... | python |
# Copyright 2021 The SeqIO Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | python |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... | python |
import time
import RPi.GPIO as GPIO
import SerialWombatPigpioI2c
import SerialWombatServo
import SerialWombatAnalogInput
import SerialWombatQuadEnc
GPIO.setwarnings(False)
sw = SerialWombatPigpioI2c.SerialWombatChipPigpioI2c(17,27,0x6D)
sw.begin(False)
print(sw.version)
print(sw.model)
print(sw.fwVersion)
servo =... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# newclass.py
from pfp_sdk.PFPUtil import *
class Example(wx.Frame):
def __init__(self, parent, title):
super(Example, self).__init__(parent, title=title, pos=(100,100), size=(800, 230))
self.InitUI()
self.Centre()
self.Show() ... | python |
"""A practical configuration system.
"""
from .extension_point import ExtensionPoint # noqa: F401
from .loading import load_from_module, load_from_pkg_resources # noqa: F401
from .option import build_default_config, Option # noqa: F401
from .profile import Profile # noqa: F401
from .utilities import merge # noqa:... | python |
"""Transform metrics stored in SQuaSH into InfluxDB format.
See sqr-009.lsst.io for a description on how metrics are stored in SQuaSH and
the resulting InfluxDB data model.
"""
__all__ = ["Transformer"]
import logging
import math
import pathlib
import urllib.parse
import requests
import yaml
from requests.exception... | python |
from globibot.lib.web.handlers import SessionHandler
from globibot.lib.web.decorators import authenticated, respond_json
from http import HTTPStatus
server_data = lambda server: dict(
id = server.id,
name = server.name,
icon_url = server.icon_url,
)
class GuildHandler(SessionHandler):
@aut... | python |
import json
import random
import glob
import torch
import numpy as np
import clip.clip as clip
import pickle
from collections import Counter, defaultdict
from tqdm import tqdm
from torch.utils.data import DataLoader
import sys
from vqa.vqa_dataset import VQADataset
SOFT_PROMPT = True
ITER_TO_BREAK = 999
def eval_ini... | python |
"""
Created on Jan 27, 2016
@author: tmahrt
Tests that praat files can be read in and then written out, and that the two
resulting files are the same.
This does not test that the file reader is correct. If the file
reader is bad (e.g. truncates floating points to 1 decimal place), the
resulting data structures will... | python |
from pyfluminus.authorization import vafs_jwt
from pyfluminus.api import name, modules, get_announcements
from pyfluminus.structs import Module
from flask import Flask, request, jsonify, redirect, url_for, render_template
import sys
from app import app, db, util
from app.models import User, User_Mods, Announcements, M... | python |
"""
Copyright (c) 2018-2021 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... | python |
# -*- coding: utf-8 -*-
"""
runserver.py
~~~~~~~~~~~~~
This code launches the backend webserver of moves using flask with eventlet
(for concurrency) and socket.io.
"""
from moves import app,socketio,r
app.run(debug=True)
socketio.run(app,host='0.0.0.0',port=PORT, debug=DEBUG)
| python |
import torch
from models.MaskRCNN import get_model_instance_segmentation
from dataset import PennFudanDataset, get_transform
from references.engine import train_one_epoch, evaluate
from references import utils
# train on the GPU or the CPU, if a GPU is not available
device = torch.device('cuda') if torch.cuda.is_avai... | python |
"""empty message
Revision ID: 8c7f8fa92c20
Revises: c925e4d07621
Create Date: 2018-08-17 13:09:27.720622
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '8c7f8fa92c20'
down_revision = 'c925e4d07621'
branch_labels = None... | python |
import toml
t = toml.load("Cargo.toml")
crate_version = t['package']['version']
t = toml.load("pyproject.toml")
wheel_version = t['tool']['poetry']['version']
assert crate_version == wheel_version
print(crate_version)
| python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import Dict, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Parameter
from fairseq import utils
from fairseq.modul... | python |
import nltk, json, pickle
from HelperFunctions import find_author
class MessageSentiment:
"""Generate mood sentiments for messages"""
MINIMUM_CERTAINTY_PROBABILITY = 0.85
TRAINING_SET_SIZE = 5000
try:
STOP_WORDS = set(nltk.corpus.stopwords.words('english'))
except:
nltk.download('stopwords')
STO... | python |
import os, cv2, shutil
import numpy as np
import argparse
def read_coords(coord_file):
coord_data, inds_pos = [], []
assert os.path.exists(coord_file), "File does not exist! %s"%coord_file
with open(coord_file, 'r') as f:
for ind, line in enumerate(f.readlines()):
x_coord = int(line.str... | python |
# Type of the message
FIELD_MSGTYPE = "t"
MSG_OP = 1 # This is an operation
MSG_REPLY = 2 # This is a regular reply
MSG_EXCEPTION = 3 # This is an exception
MSG_CONTROL = 4 # This is a control message
MSG_INTERNAL_ERROR = 5 # Some internal error happened
# Fields for operations/control
FIELD_OPTYPE = "o"
FIELD_TA... | python |
import logging
from typing import List, Union, Iterable
from matplotlib.pyplot import Figure
import matplotlib.ticker as mtick
import pandas as pd
from py_muvr.permutation_test import PermutationTest
from matplotlib import pyplot as plt
from py_muvr.data_structures import FeatureSelectionResults
log = logging.getLogg... | python |
# WEATHER RETRIEVING MICROSERVICE
# By: Cody Jennette
# CS 361 - Software Engineering I
# jennettc@oregonstate.edu
import requests
import urllib.request
# Program fetches local machine's external IP address, later used for current location:
external_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8... | python |
# -*- coding: utf-8 -*-
# pylint: disable=no-member,invalid-name,duplicate-code
"""
REST API Documentation for the NRS TFRS Credit Trading Application
The Transportation Fuels Reporting System is being designed to streamline
compliance reporting for transportation fuel suppliers in accordance with
the ... | python |
import time
import requests
import threading
from filibuster.logger import debug
TIMEOUT_ITERATIONS = 100
SLEEP = 1
def num_services_running(services):
num_running = len(services)
for service in services:
if not service_running(service):
debug("! service " + service + " not yet running!"... | python |
class ParkingSystem(object):
def __init__(self, big, medium, small):
"""
:type big: int
:type medium: int
:type small: int
"""
self.lot = {
1: [big,0],
2: [medium,0],
3: [small,0]
}
def addCar(self, carType):
"... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2014 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the L... | python |
# test_hello_add.py
from API import app
from flask import json
def test_predict():
response = app.test_client().post(
'/predict',
data=json.dumps({"gender":["Male"],
"SeniorCitizen":["0"],
"Partner":["0"],
"Dependents":["0"],
... | python |
import argparse
import marshal
import os
import py_compile
from importlib import import_module
from pathlib import Path
from zipfile import ZipFile, PyZipFile
from Crypto.Cipher import AES
from loaders import register, PycZimpLoader, PyZimpLoader
def get_key(path):
if path is None:
return None
with... | python |
from brick_wall_build import task
@task()
def clean():
pass
# Should be marked as task.
def html():
pass
# References a non task.
@task(clean,html)
def android():
pass
| python |
def INSERTION_SORT(list):
for n in range(1, len(list)):
for i in range(0, len(list) - 2):
if list[i] > list[i + 1]:
tmp = list[i]
list[i] = list[i + 1]
list[i + 1] = tmp
k = 0
for i in range(0, len(list) - 2):
if list[-1] > list[i]:... | python |
"""placeholder
Revision ID: 57539722e5cf
Revises: c1b5abada09c
Create Date: 2019-12-03 00:55:16.012247
"""
# revision identifiers, used by Alembic.
revision = '57539722e5cf'
down_revision = 'c1b5abada09c'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - ... | python |
first_number=1+1
print(first_number)
second_number=105+10
print(second_number)
| python |
from flask import Flask, request, jsonify, url_for, Blueprint
from api.models import db, User
from api.utils import generate_sitemap, APIException
from flask_jwt_extended import create_access_token
from flask_jwt_extended import get_jwt_identity
from flask_jwt_extended import jwt_required
import os
api = Blueprint('api... | python |
import os
import package1.process as process
import package1.loadsettings as loadsettings
filenames = os.listdir("./task") #Create list of mediafiles to run through
if filenames == []:
print( "\nERROR: Task folder is empty. Put in video file(s) that you want to condense." )
quit()
if 'deletethis.txt' in file... | python |
import urllib
from BeautifulSoup import *
class ComputerLab():
def __init__(self, room, num, time):
self.room = room
self.num = num
self.time = time
def __repr__(self):
str = "Room: %s\nNum: %s\nTime: %s\n" % (self.room, self.num, self.time)
return str
url = "https://tomcat.itap.purdue.edu:8445/ICSWeb/Av... | python |
#!/usr/bin/env python
# encoding: utf-8
"""
mssql2csv.py
Created by Bill Wiens on 2010-05-04.
"""
import sys, os, getopt, getpass
import optparse
import logging
import csv
import pymssql
def main():
parser = optparse.OptionParser()
parser.description="""Python script to dump a MSSQL Server Database to folder of ... | python |
#! usr/bin/python3.6
"""
Module initially auto generated using V5Automation files from CATIA V5 R28 on 2020-06-11 12:40:47.360445
.. warning::
The notes denoted "CAA V5 Visual Basic Help" are to be used as reference only.
They are there as a guide as to how the visual basic / catscript function... | python |
import numpy as np
import read_thres as thrs
def test_thr(check_thr):
data, x = thrs.ths_def(check_thr, threshd=1.E-5)
dat_nw = check_thr.drop(columns=["norm", "<x>", "<y>"])
x_nw = dat_nw.columns.values
assert len(x) == len(x_nw)
assert np.array_equal(x, x_nw)
assert data.equals(dat_nw)
| python |
import os
import yaml
import getpass
from ConfigParser import SafeConfigParser
from twisted.internet import defer, reactor
from twisted.internet.endpoints import TCP4ClientEndpoint
from os.path import abspath, expanduser
from ooni.utils.net import ConnectAndCloseProtocol, connectProtocol
from ooni import geoip
from ... | python |
#!/usr/bin/env python3
import pandas as pd
from tqdm import tqdm
from collections import defaultdict
import os, re, time, warnings, sys
import warnings
import pickle
from mutagen.mp3 import MP3
import numpy as np
def create_df(tsv, audio_dir):
tqdm.pandas()
df = pd.read_csv(tsv, sep='\t')
df['dur'] = df['... | python |
from unittest import TestCase
from cards.businesslogic.description_generator.DescriptionAppender import DescriptionAppender
class DescriptionAppenderTestCase(TestCase):
def test_sample_description1(self):
appender = DescriptionAppender()
text1 = "line1"
text2 = "line2"
appender.a... | python |
# Copyright 2020 Thomas Rogers
# SPDX-License-Identifier: Apache-2.0
import typing
import yaml
from direct.gui import DirectGui, DirectGuiGlobals
from direct.task import Task
from panda3d import core
from ... import constants, edit_mode
from ...tiles import manager
from ...utils import gui
from .. import descriptors... | python |
import tkinter as tk
import pygubu
import csv
import serial
import rospy
import numpy as np
import PID
import ctypes
from can_msgs import msg
import fcntl
import termios
import sys
import select
import subprocess
import os
from threading import Timer
import signal
from termios import tcflush, TCIOFLUSH
from rospy.core... | python |
# Generated by Django 2.0.3 on 2018-04-07 13:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects', '0035_auto_20180402_1507'),
]
operations = [
migrations.AddField(
model_name='project_attendees',
name='m... | python |
from .fpath import *
from .tree import * | python |
from .constants import AWSRegion
def parse_aws_region(region_arg: str) -> AWSRegion:
for region in AWSRegion:
if region_arg == region.value[0]:
return region
raise ValueError(f'Invalid AWS region {region_arg}') | python |
import os
import json
import dfd
extended_python_path = dfd.get_path_if_exists('extended_python_path')
environment_path = dfd.get_path_if_exists('environment')
if extended_python_path:
import site
site.addsitedir(extended_python_path)
if environment_path:
with open(environment_path) as env_file:
... | python |
from typing import Optional, Tuple
from munch import Munch
import logging
from api.jwt import Jwt, JwtPayload
ADMIN_AUTHORITY = "ADMIN"
BASIC_AUTHORITY = "BASIC"
class Auth:
def __init__(self, event):
self._event = Munch.fromDict(event)
self.jwt = Jwt()
@property
def auth_header(self) -... | python |
import choraconfig, re, sys, os.path
def master_theorem_bounds_callout(params) :
if "logpath" not in params :
print "ERROR: duet_bounds_callout was called without a path"
sys.exit(0)
#output = ""
with open(params["logpath"],"rb") as logfile : output = logfile.read().strip()
return outp... | python |
import numpy as np
class Territory:
def __init__(self,name,adjacent_territories,occupying_player=None,troops=None):
self.name = name
self.adjacent_territories = adjacent_territories
self.occupying_player = occupying_player
self.troops = troops
def __str__(self):
return ... | python |
# This file will contain the entry point where you load the data and init the variables
| python |
from mars_profiling.report.presentation.core.collapse import Collapse
from mars_profiling.report.presentation.core.container import Container
from mars_profiling.report.presentation.core.duplicate import Duplicate
from mars_profiling.report.presentation.core.frequency_table import FrequencyTable
from mars_profiling.rep... | python |
from django.urls import path, include
from users.api.loginviews import LoginAPI
urlpatterns = [
path('', LoginAPI.as_view())
] | python |
def corrupt_part_data_on_disk(node, table, part_name):
part_path = node.query(
"SELECT path FROM system.parts WHERE table = '{}' and name = '{}'".format(
table, part_name
)
).strip()
corrupt_part_data_by_path(node, part_path)
def corrupt_part_data_by_path(node, part_path):
... | python |
#!/usr/bin/python3
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | python |
import numpy as np
import pandas as pd
import bbi
import pysam
##only mappabilty_by_idx called from top level
def load_chromsizes(f_bw):
chroms = bbi.chromsizes(f_bw)
chroms.pop('chrM')
chroms.pop('chrX')
chroms.pop('chrY')
return chroms
def mappability_by_window(f_mapp, window, overlap=0):
ch... | python |
import unittest
import io
from contextlib import redirect_stdout
from rdflib import Namespace, Graph
from sparqlslurper import SlurpyGraph
from sparqlslurper._graphdb_slurpygraph import GraphDBSlurpyGraph
endpoint = 'https://graph.fhircat.org/repositories/fhirontology'
class SparqlParametersTestCase(unittest.TestC... | python |
import pathlib
import subprocess
import signal
import time
import os
import sys
import argparse
def main():
parser = argparse.ArgumentParser(prog="run-snet-services")
parser.add_argument("--daemon-config-path", help="Path to daemon configuration file", required=False)
args = parser.parse_args(sys.argv[1:]... | python |
from django.urls import path
from.import views
urlpatterns = [
path('index',views.index,name='Iniciowarehouse')
] | python |
# coding=utf-8
from collections import namedtuple
CamouflageInfo = namedtuple('CamouflageInfo', ['id', 'schemeId'])
| python |
lua_1 = """
local k = 1/math.sqrt(0.05)
local val = tonumber(ARGV[1])
local old_vals = redis.call('get',KEYS[1])
local new_vals = {}
if (old_vals) then
old_vals = cjson.decode(old_vals)
new_vals["count_1"] = old_vals['count_1'] + 1
local delta = val - old_vals["me... | python |
import time
from django.core.management.base import BaseCommand
from django.db import transaction
import database_locks
class Command(BaseCommand):
help = 'Lock it!'
def add_arguments(self, parser):
parser.add_argument('lock_name', help='lock name to be used')
parser.add_argument(
... | python |
import logging.config
import uvicorn
from fastapi import FastAPI, Request, status
from fastapi.encoders import jsonable_encoder
from dotenv import load_dotenv
from fastapi.responses import JSONResponse, PlainTextResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.exceptions i... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.