code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
from django.core.management.base import BaseCommand from django.conf import settings from uw_pws import PWS from uw_canvas.accounts import Accounts from uw_canvas.reports import Reports from restclients_core.exceptions import DataFailureException, InvalidRegID from os.path import dirname import csv import sys class ...
sis_provisioner/management/commands/find_active_instructors.py
from django.core.management.base import BaseCommand from django.conf import settings from uw_pws import PWS from uw_canvas.accounts import Accounts from uw_canvas.reports import Reports from restclients_core.exceptions import DataFailureException, InvalidRegID from os.path import dirname import csv import sys class ...
0.22093
0.096791
from abc import abstractmethod from logging import getLogger LOGGER = getLogger(__name__) class NamedEntity(object): """ This class represents an entity with a unique identifier, and a human-readable text description. Attributes ---------- identifier : str A unique identifier. descr...
ntcir_mias_search/abstract.py
from abc import abstractmethod from logging import getLogger LOGGER = getLogger(__name__) class NamedEntity(object): """ This class represents an entity with a unique identifier, and a human-readable text description. Attributes ---------- identifier : str A unique identifier. descr...
0.945714
0.439386
from pkg_resources import get_distribution __version__ = get_distribution('pg_chameleon').version import argparse from pg_chameleon import replica_engine from pg_chameleon import config_dir configdir = config_dir() configdir.set_config() commands = [ 'create_schema', 'init_replica', 'start_replica', 'upgrade_schem...
scripts/chameleon.py
from pkg_resources import get_distribution __version__ = get_distribution('pg_chameleon').version import argparse from pg_chameleon import replica_engine from pg_chameleon import config_dir configdir = config_dir() configdir.set_config() commands = [ 'create_schema', 'init_replica', 'start_replica', 'upgrade_schem...
0.371137
0.058132
import json import pickle import os from typing import Dict, Iterable, TypeVar, Type, List, Union, Any if __package__: from link_analysis.models import Header, DocumentHeader, CleanLink else: from models import Header, DocumentHeader, CleanLink # type: ignore # Don't forget to add to this place new classes w...
link_analysis/converters.py
import json import pickle import os from typing import Dict, Iterable, TypeVar, Type, List, Union, Any if __package__: from link_analysis.models import Header, DocumentHeader, CleanLink else: from models import Header, DocumentHeader, CleanLink # type: ignore # Don't forget to add to this place new classes w...
0.471223
0.220594
from .helpers import Create, List from .utils.rave_utils import merge_dict, initialize_config class PreAuthorization(Create): """ Preauthorization for refunds and card transactions """ @classmethod def capture(cls, payload, api): """ process preauthorization of capture transaction...
ravepaypysdk/resources.py
from .helpers import Create, List from .utils.rave_utils import merge_dict, initialize_config class PreAuthorization(Create): """ Preauthorization for refunds and card transactions """ @classmethod def capture(cls, payload, api): """ process preauthorization of capture transaction...
0.739611
0.13589
import random import string from time import sleep import sys def delay_print(s): for c in s: sys.stdout.write('%s' % c) sys.stdout.flush() sleep(0.25) delay_print("--== A7MD0V PRESENTS ==--\n") delay_print("GASPE: Genetic Algorithm String Production Engine...\n") print("Hello user...") ...
GA_HelloWorld.py
import random import string from time import sleep import sys def delay_print(s): for c in s: sys.stdout.write('%s' % c) sys.stdout.flush() sleep(0.25) delay_print("--== A7MD0V PRESENTS ==--\n") delay_print("GASPE: Genetic Algorithm String Production Engine...\n") print("Hello user...") ...
0.227555
0.186687
from __future__ import annotations from pioreactor.automations import events from pioreactor.automations.dosing.base import DosingAutomationJob from pioreactor.exc import CalibrationError from pioreactor.utils import local_persistant_storage class Turbidostat(DosingAutomationJob): """ Turbidostat mode - try ...
pioreactor/automations/dosing/turbidostat.py
from __future__ import annotations from pioreactor.automations import events from pioreactor.automations.dosing.base import DosingAutomationJob from pioreactor.exc import CalibrationError from pioreactor.utils import local_persistant_storage class Turbidostat(DosingAutomationJob): """ Turbidostat mode - try ...
0.878887
0.33158
import scrapy from scrapy_demo.items import AosunItem class AosunSpider(scrapy.Spider): name = 'aosun_spider' # 定义爬虫的名称,用于区别spider,该名称必须是唯一的,不可为不同的spider设置相同的名字 allowed_domains = ['aosun.cloud'] # 定义允许爬取的域,若不是该列表内的域名则放弃抓取 custom_settings = { 'ITEM_PIPELINES': {'scrapy_demo.pipelines.AosunPipelin...
scrapy_demo/spiders/aosun_spider.py
import scrapy from scrapy_demo.items import AosunItem class AosunSpider(scrapy.Spider): name = 'aosun_spider' # 定义爬虫的名称,用于区别spider,该名称必须是唯一的,不可为不同的spider设置相同的名字 allowed_domains = ['aosun.cloud'] # 定义允许爬取的域,若不是该列表内的域名则放弃抓取 custom_settings = { 'ITEM_PIPELINES': {'scrapy_demo.pipelines.AosunPipelin...
0.165425
0.113604
import logging import time from tqdm import tqdm from settings import number_of_retries logger = logging.getLogger(__name__) class Sync: """Assumptions: - Unito has run currently, so that - Each issue has a counterpart in each management system - Each issue's description says the name of the...
src/sync.py
import logging import time from tqdm import tqdm from settings import number_of_retries logger = logging.getLogger(__name__) class Sync: """Assumptions: - Unito has run currently, so that - Each issue has a counterpart in each management system - Each issue's description says the name of the...
0.515132
0.154472
import sys import os BASE_PATH = os.environ.get('BASE_PATH') sys.path.insert(1, BASE_PATH + '/telegram-bots/src') from libraries.util import create_href_str url_website = 'boobank.org' url_uniswap_boo = 'https://app.uniswap.org/#/swap?inputCurrency=BOO' url_uniswap_ecto = 'https://app.uniswap.org/#/swap?inputCurrenc...
src/bots/boo_bank/bot_boo_values.py
import sys import os BASE_PATH = os.environ.get('BASE_PATH') sys.path.insert(1, BASE_PATH + '/telegram-bots/src') from libraries.util import create_href_str url_website = 'boobank.org' url_uniswap_boo = 'https://app.uniswap.org/#/swap?inputCurrency=BOO' url_uniswap_ecto = 'https://app.uniswap.org/#/swap?inputCurrenc...
0.269614
0.213644
from google.colab import files files.upload() !mkdir -p ~/.kaggle !cp kaggle.json ~/.kaggle/ !chmod 600 /root/.kaggle/kaggle.json !kaggle datasets download -d shobhit18th/indian-currency-notes Dataset = !unzip indian-currency-notes.zip !pip install "torch==1.4" "torchvision==0.5.0" # Commented out IPython magic to...
Notebooks/classify_notes.py
from google.colab import files files.upload() !mkdir -p ~/.kaggle !cp kaggle.json ~/.kaggle/ !chmod 600 /root/.kaggle/kaggle.json !kaggle datasets download -d shobhit18th/indian-currency-notes Dataset = !unzip indian-currency-notes.zip !pip install "torch==1.4" "torchvision==0.5.0" # Commented out IPython magic to...
0.529263
0.151843
from django import forms def _get_field_group(field_name, enable_fields): if enable_fields[field_name]: return "User" return "Admin" def get_choices_from_string(string_with_anti_slash_n): split_lines = string_with_anti_slash_n.splitlines() returned_list = list() for line in split_lines: ...
service_catalog/forms/utils.py
from django import forms def _get_field_group(field_name, enable_fields): if enable_fields[field_name]: return "User" return "Admin" def get_choices_from_string(string_with_anti_slash_n): split_lines = string_with_anti_slash_n.splitlines() returned_list = list() for line in split_lines: ...
0.349311
0.123392
import logging import subprocess import requests from requests import Response class Topic: """A class that represent a Kafka topic.""" def __init__( self, blaster_bearer_token: str, blaster_topics_api_url: str, blaster_cluster_uuid: str, confluent_env_id: str, ...
kafka-delete-topic/capability_service/kafka.py
import logging import subprocess import requests from requests import Response class Topic: """A class that represent a Kafka topic.""" def __init__( self, blaster_bearer_token: str, blaster_topics_api_url: str, blaster_cluster_uuid: str, confluent_env_id: str, ...
0.736211
0.176885
# Python Standard Library general imports import logging import requests # Python Standard Library specific imports from datetime import datetime # pyCKW class imports from pyckw.pyCKWConfig import pyCKWConfig from pyckw.pyCKWExceptions import pyCKWValidationError # pyCKW contants imports from pyckw.pyCKWConstants i...
pyckw/pyCKW.py
# Python Standard Library general imports import logging import requests # Python Standard Library specific imports from datetime import datetime # pyCKW class imports from pyckw.pyCKWConfig import pyCKWConfig from pyckw.pyCKWExceptions import pyCKWValidationError # pyCKW contants imports from pyckw.pyCKWConstants i...
0.717309
0.16248
import torch import torch.nn as nn device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class Aggregator(torch.nn.Module): def __init__(self, config): super(Aggregator, self).__init__() self.config = config in_channels = 1 + len(config.news_rep['dilations']) lay...
src/model/FIM/aggregator.py
import torch import torch.nn as nn device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class Aggregator(torch.nn.Module): def __init__(self, config): super(Aggregator, self).__init__() self.config = config in_channels = 1 + len(config.news_rep['dilations']) lay...
0.802556
0.347496
import sys import cx_Oracle # the package used for accessing Oracle in Python import getpass # the package for getting password from user without displaying it def createTable(): # get username user = input("Username [%s]: " % getpass.getuser()) if not user: user=getpass.getuser() # ...
connect.py
import sys import cx_Oracle # the package used for accessing Oracle in Python import getpass # the package for getting password from user without displaying it def createTable(): # get username user = input("Username [%s]: " % getpass.getuser()) if not user: user=getpass.getuser() # ...
0.136206
0.111
__copyright__ = "Copyright (c) 2009 <NAME>" __version__ = "$Id$" from Queue import Queue from tws import EWrapper class QueueWrapper(Queue, EWrapper): def __init__(self): super(QueueWrapper, self).__init__() if __debug__: # Assert structure of items put into Queue _queue_type = Queue ...
tws/helper/_queuewrapper.py
__copyright__ = "Copyright (c) 2009 <NAME>" __version__ = "$Id$" from Queue import Queue from tws import EWrapper class QueueWrapper(Queue, EWrapper): def __init__(self): super(QueueWrapper, self).__init__() if __debug__: # Assert structure of items put into Queue _queue_type = Queue ...
0.444083
0.130507
from PyQt5 import QtWidgets,QtCore from ConstructRIT.UI.ThreadedMainWindow import ThreadedMainWindow class SandboxConfirmWindow(ThreadedMainWindow): """ Confirm window for enabling or disabling the sandbox. """ onConfirmed = QtCore.pyqtSignal() openWindows = [] def __init__(self, windowName:...
ConstructSettingsSandbox/src/SandboxConfirmWindow.py
from PyQt5 import QtWidgets,QtCore from ConstructRIT.UI.ThreadedMainWindow import ThreadedMainWindow class SandboxConfirmWindow(ThreadedMainWindow): """ Confirm window for enabling or disabling the sandbox. """ onConfirmed = QtCore.pyqtSignal() openWindows = [] def __init__(self, windowName:...
0.67405
0.104889
import itertools import numpy as np EMPTY = 0 BLACK = 1 WHITE = -1 COLUMNS = "ABCDEFGHJKLMNOPQRST" PASS = () class Engine(): def __init__(self, size=19, komi=6.5): self.size = size self.komi = komi self.reset() def reset(self): self.board = np.zeros((self.size, self.size), dt...
src/engine.py
import itertools import numpy as np EMPTY = 0 BLACK = 1 WHITE = -1 COLUMNS = "ABCDEFGHJKLMNOPQRST" PASS = () class Engine(): def __init__(self, size=19, komi=6.5): self.size = size self.komi = komi self.reset() def reset(self): self.board = np.zeros((self.size, self.size), dt...
0.249996
0.294985
from .base import Mutator import json import lmctl.reference as refs def deprecated_behaviour_descriptor_reference(): return '$lmctl.descriptor_name' def is_deprecated_behaviour_descriptor_reference(value): return value == deprecated_behaviour_descriptor_reference() class BehaviourMutator(Mutator): de...
lmctl/project/mutate/behaviour.py
from .base import Mutator import json import lmctl.reference as refs def deprecated_behaviour_descriptor_reference(): return '$lmctl.descriptor_name' def is_deprecated_behaviour_descriptor_reference(value): return value == deprecated_behaviour_descriptor_reference() class BehaviourMutator(Mutator): de...
0.427158
0.072604
import typing from abc import abstractmethod from ..uno.x_interface import XInterface as XInterface_8f010a43 if typing.TYPE_CHECKING: from ..beans.x_property_set import XPropertySet as XPropertySet_bc180bfa from ..lang.locale import Locale as Locale_70d308fa class XNumberFormats(XInterface_8f010a43): """ ...
ooobuild/lo/util/x_number_formats.py
import typing from abc import abstractmethod from ..uno.x_interface import XInterface as XInterface_8f010a43 if typing.TYPE_CHECKING: from ..beans.x_property_set import XPropertySet as XPropertySet_bc180bfa from ..lang.locale import Locale as Locale_70d308fa class XNumberFormats(XInterface_8f010a43): """ ...
0.667798
0.244352
from matplotlib.pyplot import figure, grid, legend, plot, show, subplot, suptitle, title from numpy import arange, array, concatenate, cos, identity, linspace, ones, sin, tanh, tile, zeros from numpy.random import uniform from scipy.io import loadmat, savemat from sys import argv from ..controllers import CombinedCon...
lyapy/examples/segway.py
from matplotlib.pyplot import figure, grid, legend, plot, show, subplot, suptitle, title from numpy import arange, array, concatenate, cos, identity, linspace, ones, sin, tanh, tile, zeros from numpy.random import uniform from scipy.io import loadmat, savemat from sys import argv from ..controllers import CombinedCon...
0.764276
0.682336
import os import numpy as np import matplotlib.pyplot as plt from PIL import Image def show_images(images, epoch=None, mode='show'): if mode not in ['show', 'pause']: raise ValueError('Unknown mode to show images: ' + mode) if images.shape[-1] == 1: x = images[:, :, :, 0] cmap = 'gray'...
src/utils/image_utils.py
import os import numpy as np import matplotlib.pyplot as plt from PIL import Image def show_images(images, epoch=None, mode='show'): if mode not in ['show', 'pause']: raise ValueError('Unknown mode to show images: ' + mode) if images.shape[-1] == 1: x = images[:, :, :, 0] cmap = 'gray'...
0.340924
0.521715
import os import pickle from functools import lru_cache, wraps, partial from utils.log import get_logger logger = get_logger(__name__) class Path(object): @classmethod def _get_full_path(cls, relative_path="", base_path_type="top"): """ 不开放这段代码了,将top,src,test的dirpath登记到Config里,使用时从conf拿更合...
src/utils/io.py
import os import pickle from functools import lru_cache, wraps, partial from utils.log import get_logger logger = get_logger(__name__) class Path(object): @classmethod def _get_full_path(cls, relative_path="", base_path_type="top"): """ 不开放这段代码了,将top,src,test的dirpath登记到Config里,使用时从conf拿更合...
0.353986
0.102934
import torch import numpy as np import torch.nn as nn import torch.optim as optim from dataset import ModelNet10 import matplotlib.pyplot as plt import torch.nn.functional as F from mpl_toolkits import mplot3d from torch.utils.data import DataLoader from pointnet import PointNetClassifier from pointnet_seg import Point...
models/data_based_perturbation.py
import torch import numpy as np import torch.nn as nn import torch.optim as optim from dataset import ModelNet10 import matplotlib.pyplot as plt import torch.nn.functional as F from mpl_toolkits import mplot3d from torch.utils.data import DataLoader from pointnet import PointNetClassifier from pointnet_seg import Point...
0.579519
0.591871
import pandas as pd import numpy as np import os from PyQt5.QtCore import QAbstractTableModel, Qt, QVariant import cubetools.config as cfg class Model(): '''Creates data for the UI and export''' def __init__(self): super().__init__() self.valid_cncfilelist = self.check_cnc_filepaths() de...
cubetools/model.py
import pandas as pd import numpy as np import os from PyQt5.QtCore import QAbstractTableModel, Qt, QVariant import cubetools.config as cfg class Model(): '''Creates data for the UI and export''' def __init__(self): super().__init__() self.valid_cncfilelist = self.check_cnc_filepaths() de...
0.551815
0.179495
from empire.python.typings import * from empire.enums.base_enum import BaseEnum class QueueAttributes(BaseEnum): """ SQS Queue attributes Attributes: APPROXIMATE_NUMBER_OF_MESSAGES Returns the approximate number of messages available for retrieval from the queue. APPROXIM...
Python/empire/aws/sqs/queue_attributes.py
from empire.python.typings import * from empire.enums.base_enum import BaseEnum class QueueAttributes(BaseEnum): """ SQS Queue attributes Attributes: APPROXIMATE_NUMBER_OF_MESSAGES Returns the approximate number of messages available for retrieval from the queue. APPROXIM...
0.820073
0.256519
import json from django.urls import reverse from rest_framework import status import pytest from locations import models from locations.views import LocationListView @pytest.fixture def disable_throttling(): throttle_classes = LocationListView.throttle_classes LocationListView.throttle_classes = () try:...
src/tests/locations/test_create_location.py
import json from django.urls import reverse from rest_framework import status import pytest from locations import models from locations.views import LocationListView @pytest.fixture def disable_throttling(): throttle_classes = LocationListView.throttle_classes LocationListView.throttle_classes = () try:...
0.496338
0.226976
import os import sys import numpy as np import tensorflow as tf import io import pysnooper import time import seq2seqModel from sklearn.model_selection import train_test_split from getConfig import get_config CONFIG = get_config() vocab_input_size = CONFIG['enc_vocab_size'] vocab_target_size = CONFIG['dec_vocab_size'...
execute.py
import os import sys import numpy as np import tensorflow as tf import io import pysnooper import time import seq2seqModel from sklearn.model_selection import train_test_split from getConfig import get_config CONFIG = get_config() vocab_input_size = CONFIG['enc_vocab_size'] vocab_target_size = CONFIG['dec_vocab_size'...
0.412767
0.255492
__author__='thiagocastroferreira' """ Author: <NAME> Date: 28/02/2019 Description: This script aims to generate the referring expressions. ARGS: [1] Path to the file with the Lexicalization step output [2] Path to the file with the Discourse Ordering step output [3] Path to the file wh...
hierarchical-decoding/utils/generate.py
__author__='thiagocastroferreira' """ Author: <NAME> Date: 28/02/2019 Description: This script aims to generate the referring expressions. ARGS: [1] Path to the file with the Lexicalization step output [2] Path to the file with the Discourse Ordering step output [3] Path to the file wh...
0.371707
0.496582
import pprint import re import six class BugStatisticResponseV4: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key...
huaweicloud-sdk-projectman/huaweicloudsdkprojectman/v4/model/bug_statistic_response_v4.py
import pprint import re import six class BugStatisticResponseV4: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key...
0.504639
0.256925
"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_databas...
osirix/pb2/types_pb2.py
"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_databas...
0.353317
0.083516
import sys if len(sys.argv)>1: ppNo = str(sys.argv[1]) subject_id=ppNo if subject_id in ['sub-3008', 'sub-3038']: print("Participant %s is excluded from DTI analyses" % subject_id) exit() else: print ("No input argument") exit() import os #Add FSL os.environ["FSLDIR"] = "/apps/fsl/6...
preproc3_distortion.py
import sys if len(sys.argv)>1: ppNo = str(sys.argv[1]) subject_id=ppNo if subject_id in ['sub-3008', 'sub-3038']: print("Participant %s is excluded from DTI analyses" % subject_id) exit() else: print ("No input argument") exit() import os #Add FSL os.environ["FSLDIR"] = "/apps/fsl/6...
0.41253
0.130979
import hashlib import tempfile import unittest import vivisect from vivisect.const import * def add_events(vw): # Call some APIs to populate the event list. # Coherency is not the objective. Just get some events in there. filehash = hashlib.md5(b'testfile').hexdigest() vw.addFile('testfile', 0x1000, ...
vivisect/tests/teststorage.py
import hashlib import tempfile import unittest import vivisect from vivisect.const import * def add_events(vw): # Call some APIs to populate the event list. # Coherency is not the objective. Just get some events in there. filehash = hashlib.md5(b'testfile').hexdigest() vw.addFile('testfile', 0x1000, ...
0.318485
0.298003
from typing import Optional from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse, JSONResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates import pandas as pd import plotly.express as pex import plotly.offline as pof from sqlalchemy.orm impo...
app/main.py
from typing import Optional from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse, JSONResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates import pandas as pd import plotly.express as pex import plotly.offline as pof from sqlalchemy.orm impo...
0.90033
0.302383
from py2neo import Transaction from base import BaseObject from base import MandatoryParamError from datagraph.neo.dmo import NeoGraphContext from datagraph.neo.dmo import NeoUtils class GenerateSimilarityMetric(BaseObject): """ """ def __init__(self, some_tx: Transaction, ...
python/datagraph/neo/svc/generate_similarity_metric.py
from py2neo import Transaction from base import BaseObject from base import MandatoryParamError from datagraph.neo.dmo import NeoGraphContext from datagraph.neo.dmo import NeoUtils class GenerateSimilarityMetric(BaseObject): """ """ def __init__(self, some_tx: Transaction, ...
0.733547
0.154153
import pymysql from PyQt5.QtWidgets import QWidget, QMessageBox,QTableWidgetItem from PyQt5.QtCore import QDate, Qt from FIND_LOAN import Ui_Form class find_loan(QWidget): def __init__(self): super(find_loan, self).__init__() self.ui = Ui_Form() self.ui.setupUi(self) self.ui.pushBu...
Bank/FindLoan.py
import pymysql from PyQt5.QtWidgets import QWidget, QMessageBox,QTableWidgetItem from PyQt5.QtCore import QDate, Qt from FIND_LOAN import Ui_Form class find_loan(QWidget): def __init__(self): super(find_loan, self).__init__() self.ui = Ui_Form() self.ui.setupUi(self) self.ui.pushBu...
0.147647
0.092033
SEND_UPLOADED_FILE_TO_SENDBOX_ANALYSIS_HTTP_RESPONSE = { "errors": [], "meta": { "powered_by": "falconx-api", "query_time": 0.163158146, "quota": { "in_progress": 3, "total": 100, "used": 36 }, "trace_id": "trace_id" }, "resourc...
Packs/CrowdStrikeFalconX/Integrations/CrowdStrikeFalconX/TestsInput/http_responses.py
SEND_UPLOADED_FILE_TO_SENDBOX_ANALYSIS_HTTP_RESPONSE = { "errors": [], "meta": { "powered_by": "falconx-api", "query_time": 0.163158146, "quota": { "in_progress": 3, "total": 100, "used": 36 }, "trace_id": "trace_id" }, "resourc...
0.374448
0.316211
import psycopg2 def conn_curs(): """ makes a connection to the database dont worry these are dummy keys """ dbname = "abcdefgh" password = "<PASSWORD>" host = "db.elephantsql.com" connection = psycopg2.connect(dbname=dbname, user=dbname, password=password...
database/queries.py
import psycopg2 def conn_curs(): """ makes a connection to the database dont worry these are dummy keys """ dbname = "abcdefgh" password = "<PASSWORD>" host = "db.elephantsql.com" connection = psycopg2.connect(dbname=dbname, user=dbname, password=password...
0.422981
0.129733
from rest_framework.test import APITestCase from .models import Notice, UnreadNoticeCount from .utils import create_notice from account.tests import create_activated_test_user from django.urls import reverse from rest_framework import status class NoticeTests(APITestCase): def test_create_notice(self): us...
notice/tests.py
from rest_framework.test import APITestCase from .models import Notice, UnreadNoticeCount from .utils import create_notice from account.tests import create_activated_test_user from django.urls import reverse from rest_framework import status class NoticeTests(APITestCase): def test_create_notice(self): us...
0.359589
0.204481
import datetime import numpy as np import pandas as pd import matplotlib.pyplot as plt def get_drawdown(p): """ 计算净值回撤 """ T = len(p) hmax = [p[0]] for t in range(1, T): hmax.append(np.nanmax([p[t], hmax[t - 1]])) dd = [p[t] / hmax[t] - 1 for t in range(T)] return dd def cal...
timingByPERank/TimingByPERank.py
import datetime import numpy as np import pandas as pd import matplotlib.pyplot as plt def get_drawdown(p): """ 计算净值回撤 """ T = len(p) hmax = [p[0]] for t in range(1, T): hmax.append(np.nanmax([p[t], hmax[t - 1]])) dd = [p[t] / hmax[t] - 1 for t in range(T)] return dd def cal...
0.208904
0.384883
import bs4 as bs import datetime as dt import os, pickle, requests, time import pandas as pd import pandas_datareader.data as web import matplotlib.pyplot as plt from matplotlib import style from collections import Counter import numpy as np from sklearn import svm, cross_validation, neighbors from sklearn.ensemble imp...
S&P500-Analysis/S&P500-Analysis and StockPrice Prediction.py
import bs4 as bs import datetime as dt import os, pickle, requests, time import pandas as pd import pandas_datareader.data as web import matplotlib.pyplot as plt from matplotlib import style from collections import Counter import numpy as np from sklearn import svm, cross_validation, neighbors from sklearn.ensemble imp...
0.340485
0.276665
import os import re import numpy as np from collections import OrderedDict import caffe from caffe.proto import caffe_pb2 as pb2 from . import net_caffe from . import predictor class CaffeNetPredictor(caffe.Net): """ Predicts output given the current inputs inputs -> prediction """ def __init_...
visual_dynamics/predictors/predictor_caffe.py
import os import re import numpy as np from collections import OrderedDict import caffe from caffe.proto import caffe_pb2 as pb2 from . import net_caffe from . import predictor class CaffeNetPredictor(caffe.Net): """ Predicts output given the current inputs inputs -> prediction """ def __init_...
0.667148
0.390941
import unittest from unittest.mock import MagicMock, patch from urllib.error import HTTPError from bot.instagram import (Instagram, Instagram404Error, InstagramLinkError, urlopen) class InstagramAccountTestCase(unittest.TestCase): @patch('bot.instagram.urlopen') def test_get_photos...
tests/instagram/tests_instagram_account.py
import unittest from unittest.mock import MagicMock, patch from urllib.error import HTTPError from bot.instagram import (Instagram, Instagram404Error, InstagramLinkError, urlopen) class InstagramAccountTestCase(unittest.TestCase): @patch('bot.instagram.urlopen') def test_get_photos...
0.585457
0.328287
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('calculator', '0026_price_strict_range'), ] operations = [ migrations.AlterField( model_name='feetype', name='aggregation', field=models.CharField(choice...
fee_calculator/apps/calculator/migrations/0027_auto_20181122_1057.py
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('calculator', '0026_price_strict_range'), ] operations = [ migrations.AlterField( model_name='feetype', name='aggregation', field=models.CharField(choice...
0.826222
0.286606
import os import glob import argparse import numpy as np import pickle as pkl import os.path as osp import seaborn as sns import matplotlib.pyplot as plt from dataset_utils import * def parse_args(): file_purpose = ''' plot reruns stats for lottery tickets ''' parser = argparse.ArgumentParser(desc...
experiments/plot_train_lottery_reruns.py
import os import glob import argparse import numpy as np import pickle as pkl import os.path as osp import seaborn as sns import matplotlib.pyplot as plt from dataset_utils import * def parse_args(): file_purpose = ''' plot reruns stats for lottery tickets ''' parser = argparse.ArgumentParser(desc...
0.510741
0.274783
from unittest.mock import MagicMock from lmctl.environment.lmenv import LmSession, LmEnvironment import lmctl.drivers.lm as lm_drivers import lmctl.utils.descriptors as descriptor_utils import uuid import threading import time import tempfile import shutil import zipfile import yaml import os class NotFoundError(Excep...
tests/common/simulations/lm_simulator.py
from unittest.mock import MagicMock from lmctl.environment.lmenv import LmSession, LmEnvironment import lmctl.drivers.lm as lm_drivers import lmctl.utils.descriptors as descriptor_utils import uuid import threading import time import tempfile import shutil import zipfile import yaml import os class NotFoundError(Excep...
0.561215
0.149128
import os from sys import argv script, data_dir = argv # input requires file path to directory with files to analyze """Make list containing files in directory""" list_of_directories = os.listdir(data_dir) list_of_files = [] for directory in list_of_directories: new_list = os.listdir(f"{data_dir}/{di...
input/list_namespaces.py
import os from sys import argv script, data_dir = argv # input requires file path to directory with files to analyze """Make list containing files in directory""" list_of_directories = os.listdir(data_dir) list_of_files = [] for directory in list_of_directories: new_list = os.listdir(f"{data_dir}/{di...
0.19544
0.131982
import pytest from pypsrp._utils import ( get_hostname, to_bytes, to_string, to_unicode, version_equal_or_newer, ) def test_unicode_to_bytes_default(): expected = b"\x61\x62\x63" actual = to_bytes("abc") assert actual == expected def test_unicode_to_bytes_diff_encoding(): expect...
tests/test_utils.py
import pytest from pypsrp._utils import ( get_hostname, to_bytes, to_string, to_unicode, version_equal_or_newer, ) def test_unicode_to_bytes_default(): expected = b"\x61\x62\x63" actual = to_bytes("abc") assert actual == expected def test_unicode_to_bytes_diff_encoding(): expect...
0.606032
0.698214
from numba import njit, prange import numpy as np from openamundsen import ( constants as c, heatconduction, ) def soil_properties(model): """ Wrapper function for _soil_properties(). """ s = model.state _soil_properties( model.grid.roi_idxs, s.soil.thickness, s.so...
openamundsen/modules/soil/soil.py
from numba import njit, prange import numpy as np from openamundsen import ( constants as c, heatconduction, ) def soil_properties(model): """ Wrapper function for _soil_properties(). """ s = model.state _soil_properties( model.grid.roi_idxs, s.soil.thickness, s.so...
0.745954
0.641254
import cloudinary.models from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ mig...
proHub/migrations/0001_initial.py
import cloudinary.models from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ mig...
0.501221
0.119254
from datetime import date, datetime from typing import Optional import pytest import statey as st from statey.syms import encoders @pytest.mark.parametrize( "type, check", [ pytest.param(int, lambda x: isinstance(x, encoders.IntegerEncoder), id="int"), pytest.param(str, lambda x: isinstance(x...
tests/test_encoders.py
from datetime import date, datetime from typing import Optional import pytest import statey as st from statey.syms import encoders @pytest.mark.parametrize( "type, check", [ pytest.param(int, lambda x: isinstance(x, encoders.IntegerEncoder), id="int"), pytest.param(str, lambda x: isinstance(x...
0.820685
0.571647
import subprocess import time import os from zipfile import ZipFile import sh import fabric.api from fabric import operations from path import path from cosmo_tester.framework.testenv import TestCase from cosmo_tester.framework.util import YamlPatcher, get_actual_keypath CHEF_SERVER_COOKBOOK_ZIP_URL = ( 'https:/...
system_tests/manager/chef_plugin_test.py
import subprocess import time import os from zipfile import ZipFile import sh import fabric.api from fabric import operations from path import path from cosmo_tester.framework.testenv import TestCase from cosmo_tester.framework.util import YamlPatcher, get_actual_keypath CHEF_SERVER_COOKBOOK_ZIP_URL = ( 'https:/...
0.354545
0.107204
from collections import OrderedDict from typing import Sequence, TypeVar, Tuple, Dict, List, Iterator, Union, Optional import os import numpy as np import pandas as pd from .utils import MissingDict, UNK_TOKEN, BASE_VOCAB, invert_dict, create_sentence_indexer from .skip_thoughts.encoder_manager import EncoderManage...
project2/sct/data/stories.py
from collections import OrderedDict from typing import Sequence, TypeVar, Tuple, Dict, List, Iterator, Union, Optional import os import numpy as np import pandas as pd from .utils import MissingDict, UNK_TOKEN, BASE_VOCAB, invert_dict, create_sentence_indexer from .skip_thoughts.encoder_manager import EncoderManage...
0.763484
0.323808
from typing import Type, Tuple from . import Canvas from .common import * from .Layer import Comparer from .BaseClasses import CanvasNone from .tools.geometry import TwoDimensional class Tracker(Comparer): def __init__(self, canvas: Type[Comparer]): super().__init__(canvas) def how_did_it_transform(...
canvas/Transformer.py
from typing import Type, Tuple from . import Canvas from .common import * from .Layer import Comparer from .BaseClasses import CanvasNone from .tools.geometry import TwoDimensional class Tracker(Comparer): def __init__(self, canvas: Type[Comparer]): super().__init__(canvas) def how_did_it_transform(...
0.75985
0.538134
import rospy from std_msgs.msg import Int32 from geometry_msgs.msg import PoseStamped, Pose from styx_msgs.msg import TrafficLightArray, TrafficLight from styx_msgs.msg import Lane from sensor_msgs.msg import Image from cv_bridge import CvBridge from light_classification.tl_classifier import TLClassifier import tf imp...
ros/src/tl_detector/tl_detector_use_simulator.py
import rospy from std_msgs.msg import Int32 from geometry_msgs.msg import PoseStamped, Pose from styx_msgs.msg import TrafficLightArray, TrafficLight from styx_msgs.msg import Lane from sensor_msgs.msg import Image from cv_bridge import CvBridge from light_classification.tl_classifier import TLClassifier import tf imp...
0.492188
0.186632
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.formats import number_format # List of values for use in choices from .applib.lists import gender_list, treatment_list, type_address_list, uf_list, type_phone_list class TimeStampedModel(models.Model): created_a...
myproject/core/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.formats import number_format # List of values for use in choices from .applib.lists import gender_list, treatment_list, type_address_list, uf_list, type_phone_list class TimeStampedModel(models.Model): created_a...
0.542136
0.118131
import numba from math import sqrt from numpy import matmul from numpy.linalg import lstsq @numba.jit def vec_norm(a): """compute the vector norm of a vector""" sum2 = 0 for i in range(len(a)): sum2 += a[i] * a[i] return sqrt(sum2) @numba.jit def all_zero(a): """evaluate if entire vector...
crossmap/vectors.py
import numba from math import sqrt from numpy import matmul from numpy.linalg import lstsq @numba.jit def vec_norm(a): """compute the vector norm of a vector""" sum2 = 0 for i in range(len(a)): sum2 += a[i] * a[i] return sqrt(sum2) @numba.jit def all_zero(a): """evaluate if entire vector...
0.635449
0.799442
from datetime import datetime from datetime import timedelta import endpoints # pylint: disable=F0401 from protorpc import messages from protorpc import message_types from protorpc import remote import controller package = 'Stats' class MasterCollection(messages.Message): masters = messages.StringField(1, repe...
appengine/chrome_infra_stats/stats_api.py
from datetime import datetime from datetime import timedelta import endpoints # pylint: disable=F0401 from protorpc import messages from protorpc import message_types from protorpc import remote import controller package = 'Stats' class MasterCollection(messages.Message): masters = messages.StringField(1, repe...
0.696165
0.151122
import numpy as np from scipy.ndimage.measurements import label from features import extract_single_img_features import cv2 class CarDetector(): def __init__(self, clf, pca, scaler, color_space='YCrCb', orient=9, pix_per_cell=8, cell_per_block=2, hog_channel=0, spatial_size=(16, 16), hist_bins=16, ...
p5-vehicle-detection/detection.py
import numpy as np from scipy.ndimage.measurements import label from features import extract_single_img_features import cv2 class CarDetector(): def __init__(self, clf, pca, scaler, color_space='YCrCb', orient=9, pix_per_cell=8, cell_per_block=2, hog_channel=0, spatial_size=(16, 16), hist_bins=16, ...
0.778649
0.439567
__all__ = ["ChoiceField"] from cosmicRays.pexConfig import Field, _typeStr from cosmicRays.pexCallStack import getStackFrame class ChoiceField(Field): """A configuration field (`~lsst.pex.config.Field` subclass) that allows a user to select from a predefined set of values. Use ``ChoiceField`` when a co...
python/cosmicRays/choiceField.py
__all__ = ["ChoiceField"] from cosmicRays.pexConfig import Field, _typeStr from cosmicRays.pexCallStack import getStackFrame class ChoiceField(Field): """A configuration field (`~lsst.pex.config.Field` subclass) that allows a user to select from a predefined set of values. Use ``ChoiceField`` when a co...
0.910336
0.381277
import warnings from dataclasses import dataclass from typing import Any import matplotlib.pyplot as plt import matplotlib import numpy as np import visgeom as vg from pylie import SE2, SO2 from shapely import geometry as sg, ops as so def plot_se2_covariance_on_manifold(ax, dist, n=50, chi2_val=11.345, right_perturb...
ex4_distributions.py
import warnings from dataclasses import dataclass from typing import Any import matplotlib.pyplot as plt import matplotlib import numpy as np import visgeom as vg from pylie import SE2, SO2 from shapely import geometry as sg, ops as so def plot_se2_covariance_on_manifold(ax, dist, n=50, chi2_val=11.345, right_perturb...
0.784526
0.630969
import os import sys import argparse import numpy as np import deeptools.countReadsPerBin as countR from deeptools import parserCommon from deeptools.utilities import smartLabels from deeptools._version import __version__ old_settings = np.seterr(all='ignore') def parse_arguments(args=None): parser = \ ...
deeptools/multiBamSummary.py
import os import sys import argparse import numpy as np import deeptools.countReadsPerBin as countR from deeptools import parserCommon from deeptools.utilities import smartLabels from deeptools._version import __version__ old_settings = np.seterr(all='ignore') def parse_arguments(args=None): parser = \ ...
0.606732
0.345574
import click import os import yaml import time from nitpicker import helpers from nitpicker.report_generator.generator import ReportGenerator TEST_CASE_TEMPLATE = ''' created: {created} author: {author} description: {description} tags: setup: - Do something to start actions: - Action 1 - Action 2 reactions: - Reacti...
nitpicker/nitpicker.py
import click import os import yaml import time from nitpicker import helpers from nitpicker.report_generator.generator import ReportGenerator TEST_CASE_TEMPLATE = ''' created: {created} author: {author} description: {description} tags: setup: - Do something to start actions: - Action 1 - Action 2 reactions: - Reacti...
0.387227
0.136868
from PyQt5 import QtWidgets, QtCore from petra_camera.gui.Marker_ui import Ui_Marker # ---------------------------------------------------------------------- class Marker(QtWidgets.QWidget): repaint_marker = QtCore.pyqtSignal() delete_me = QtCore.pyqtSignal(int) # ----------------------------------------...
petra_camera/widgets/marker.py
from PyQt5 import QtWidgets, QtCore from petra_camera.gui.Marker_ui import Ui_Marker # ---------------------------------------------------------------------- class Marker(QtWidgets.QWidget): repaint_marker = QtCore.pyqtSignal() delete_me = QtCore.pyqtSignal(int) # ----------------------------------------...
0.617397
0.087136
import numpy as np import pandapipes as pp import pandas as pd from pandapipes.plotting import simple_plot from pandapipes.properties.fluids import get_fluid try: import pplog as logging except ImportError: import logging logger = logging.getLogger(__name__) def pipeflow_openmodelica_comparison(net, log_re...
pandapipes/test/openmodelica_comparison/pipeflow_openmodelica_comparison.py
import numpy as np import pandapipes as pp import pandas as pd from pandapipes.plotting import simple_plot from pandapipes.properties.fluids import get_fluid try: import pplog as logging except ImportError: import logging logger = logging.getLogger(__name__) def pipeflow_openmodelica_comparison(net, log_re...
0.248899
0.284097
import logging import socket from datetime import datetime, timedelta from collections import namedtuple import os import csv import homeassistant as ha import homeassistant.util as util from homeassistant.components import (group, extract_entity_ids, STATE_ON, STATE_OFF, ...
homeassistant/components/light/__init__.py
import logging import socket from datetime import datetime, timedelta from collections import namedtuple import os import csv import homeassistant as ha import homeassistant.util as util from homeassistant.components import (group, extract_entity_ids, STATE_ON, STATE_OFF, ...
0.570212
0.125547
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('resumes', '0001_initial'), ] operations = [ migrations.AlterField( model_name='award', name='resume', field=models.Fore...
resumes/migrations/0002_auto_20210425_2156.py
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('resumes', '0001_initial'), ] operations = [ migrations.AlterField( model_name='award', name='resume', field=models.Fore...
0.57678
0.100216
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = ['DataSourceWindowsPerformanceCounterArgs', 'DataSourceWindowsPerformanceCounter'] @pulumi.input_type class DataSourceWindowsPerformanceCounterArgs: def __i...
sdk/python/pulumi_azure/loganalytics/data_source_windows_performance_counter.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = ['DataSourceWindowsPerformanceCounterArgs', 'DataSourceWindowsPerformanceCounter'] @pulumi.input_type class DataSourceWindowsPerformanceCounterArgs: def __i...
0.885866
0.138695
import json from django.core.urlresolvers import reverse from nose.tools import eq_, ok_ import mkt from mkt.api.tests import BaseAPI from mkt.api.tests.test_oauth import RestOAuth from mkt.site.fixtures import fixture from mkt.site.tests import ESTestCase, app_factory from mkt.tvplace.serializers import (TVAppSeria...
mkt/tvplace/tests/test_views.py
import json from django.core.urlresolvers import reverse from nose.tools import eq_, ok_ import mkt from mkt.api.tests import BaseAPI from mkt.api.tests.test_oauth import RestOAuth from mkt.site.fixtures import fixture from mkt.site.tests import ESTestCase, app_factory from mkt.tvplace.serializers import (TVAppSeria...
0.328314
0.194655
from scapy.layers.inet import IP from scapy.layers.inet import ICMP from scapy.layers.inet import TCP from scapy.utils import rdpcap, wrpcap import pdb, sys, os import re, random from scapy.all import * ipDict = {}; def generateIpv6(baseIpv4=None): global ipDict; if (baseIpv4): if (not baseIpv4 in ipD...
pcap4to6.py
from scapy.layers.inet import IP from scapy.layers.inet import ICMP from scapy.layers.inet import TCP from scapy.utils import rdpcap, wrpcap import pdb, sys, os import re, random from scapy.all import * ipDict = {}; def generateIpv6(baseIpv4=None): global ipDict; if (baseIpv4): if (not baseIpv4 in ipD...
0.345216
0.106133
import os import sys import socket import argparse import requests import subprocess def main(req, lb): results = doRequests(req, lb) printResult(results) def setUpEnvironment(nodes): os.environ["WEB_NODES_NUMBER"] = str(nodes) try: print("Setting up environment...") subprocess.che...
lbtest.py
import os import sys import socket import argparse import requests import subprocess def main(req, lb): results = doRequests(req, lb) printResult(results) def setUpEnvironment(nodes): os.environ["WEB_NODES_NUMBER"] = str(nodes) try: print("Setting up environment...") subprocess.che...
0.23066
0.072308
import numpy as np import pandas as pd from extract_pulse import get_pulse from rm_qu_fitting import mcmc_fit, plot_mcmc_samp from rm_synthesis import synthesis_rm, get_rm, plot_rm_synthesis from translate_data import translate_file, plot_spec def read_file(file_name='RM-190303-1.txt'): ##### Read File; Forma...
ModulePy/code_usage.py
import numpy as np import pandas as pd from extract_pulse import get_pulse from rm_qu_fitting import mcmc_fit, plot_mcmc_samp from rm_synthesis import synthesis_rm, get_rm, plot_rm_synthesis from translate_data import translate_file, plot_spec def read_file(file_name='RM-190303-1.txt'): ##### Read File; Forma...
0.485356
0.34414
import sys import datetime import csv import ee class ReportWriter(object): def __init__(self, filename=None): self.total_size = 0 self.writers = [csv.writer(sys.stdout)] self.writer_fo = None if filename: if sys.version_info[0] < 3: self.writer_fo = o...
gee_asset_manager/batch_info.py
import sys import datetime import csv import ee class ReportWriter(object): def __init__(self, filename=None): self.total_size = 0 self.writers = [csv.writer(sys.stdout)] self.writer_fo = None if filename: if sys.version_info[0] < 3: self.writer_fo = o...
0.387574
0.15374
from concept.math.point import Point2d from concept.math.vector import Vector2d class HDefinition(object): """One H definition as part of an H fractal.""" def __init__(self, center_position=Point2d(), direction=Vector2d(0.0, 1.0)): """Initialize with center coordinates and direction (and size).""" ...
concept/math/hfractal.py
from concept.math.point import Point2d from concept.math.vector import Vector2d class HDefinition(object): """One H definition as part of an H fractal.""" def __init__(self, center_position=Point2d(), direction=Vector2d(0.0, 1.0)): """Initialize with center coordinates and direction (and size).""" ...
0.941547
0.648884
import sys TRACK_PREVIOUS = True class WeightedDigraph: '''Weighted digraph class for dijkstra's algorithm implementation''' class _edge(): def __init__(self, to_node, weight): self.to_node = to_node self.weight = weight class _node(): def __init__(self, value): ...
structures/dijkstra.py
import sys TRACK_PREVIOUS = True class WeightedDigraph: '''Weighted digraph class for dijkstra's algorithm implementation''' class _edge(): def __init__(self, to_node, weight): self.to_node = to_node self.weight = weight class _node(): def __init__(self, value): ...
0.441673
0.371878
import time import os import tempfile from . import conftest import scrape_batch def test_blackboard(batch_client, s3_client, iam_client): # we'll need a mock iam role to pass to the mock batch client iams = iam_client.create_role( RoleName="test_batch_client", AssumeRolePolicyDocument="stri...
tests/test_lambda_blackboard.py
import time import os import tempfile from . import conftest import scrape_batch def test_blackboard(batch_client, s3_client, iam_client): # we'll need a mock iam role to pass to the mock batch client iams = iam_client.create_role( RoleName="test_batch_client", AssumeRolePolicyDocument="stri...
0.278355
0.113187
from __future__ import print_function from lib.cfgs import c as dcfgs import lib.cfgs as cfgs import os os.environ['JOBLIB_TEMP_FOLDER']=dcfgs.shm import argparse os.environ['GLOG_minloglevel'] = '3' import os.path as osp import pickle import sys from multiprocessing import Process, Queue import matplotlib.pyplot as p...
tools.py
from __future__ import print_function from lib.cfgs import c as dcfgs import lib.cfgs as cfgs import os os.environ['JOBLIB_TEMP_FOLDER']=dcfgs.shm import argparse os.environ['GLOG_minloglevel'] = '3' import os.path as osp import pickle import sys from multiprocessing import Process, Queue import matplotlib.pyplot as p...
0.451085
0.069226
import webob import webob.exc from api import robot_abstract import logging class RobotMiddleware(object): """WSGI middleware that routes /_wave/ requests to a robot wsgi app.""" def __init__(self, robot_app, main_app): self._robot_app = robot_app self._main_app = main_app def __call__(self, environ,...
app.py
import webob import webob.exc from api import robot_abstract import logging class RobotMiddleware(object): """WSGI middleware that routes /_wave/ requests to a robot wsgi app.""" def __init__(self, robot_app, main_app): self._robot_app = robot_app self._main_app = main_app def __call__(self, environ,...
0.621081
0.103839
from __future__ import unicode_literals from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np import time from annoy import AnnoyIndex from src.data_generator.data_loader import BaseBatch from src.data_generator.vocabulary import Tokenizer from src.utils impo...
src/op/vectorize.py
from __future__ import unicode_literals from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np import time from annoy import AnnoyIndex from src.data_generator.data_loader import BaseBatch from src.data_generator.vocabulary import Tokenizer from src.utils impo...
0.601828
0.170681
from baseWidget import * from enum import Enum, auto import sys import math class Display(Enum): SOLE = auto() INSOLE = auto() MOLD = auto() class insoleMoldExportWidget(baseWidget): def __init__(self, nextTab = -1): super(insoleMoldExportWidget, self).__init__(nextTab) def initCustomUI...
src/insoleMoldExportWidget.py
from baseWidget import * from enum import Enum, auto import sys import math class Display(Enum): SOLE = auto() INSOLE = auto() MOLD = auto() class insoleMoldExportWidget(baseWidget): def __init__(self, nextTab = -1): super(insoleMoldExportWidget, self).__init__(nextTab) def initCustomUI...
0.314787
0.153486
from django.test.utils import override_settings from django.test import tag from django.contrib.gis.geos import Point from django.core import mail from django_elasticsearch_dsl.test import ESTestCase from bluebottle.test.factory_models.accounts import BlueBottleUserFactory from bluebottle.test.utils import Bluebottl...
bluebottle/activities/tests/test_tasks.py
from django.test.utils import override_settings from django.test import tag from django.contrib.gis.geos import Point from django.core import mail from django_elasticsearch_dsl.test import ESTestCase from bluebottle.test.factory_models.accounts import BlueBottleUserFactory from bluebottle.test.utils import Bluebottl...
0.518546
0.267008
import markdown from markdown.extensions.toc import TocExtension from django import template from django.template.defaultfilters import stringfilter from django.utils.safestring import mark_safe from django.utils.text import slugify from django.db.models.aggregates import Count from ..models import Category, Tag # ...
blog/templatetags/blog_tags.py
import markdown from markdown.extensions.toc import TocExtension from django import template from django.template.defaultfilters import stringfilter from django.utils.safestring import mark_safe from django.utils.text import slugify from django.db.models.aggregates import Count from ..models import Category, Tag # ...
0.383988
0.107484
import yaml TARGET_FILES = set( ["conda.yaml", "MLmodel", "keras_module.txt", "save_format.txt", "model.h5"] ) def migrate_s3(s3_resource): s3_files = _find_s3_files(s3_resource, TARGET_FILES) s3_files["save_format.txt"] = _filter_h5_save_format_files( s3_resource, s3_files["save_format.txt"], s3...
tests/integration/legacy_migration/migrate_s3.py
import yaml TARGET_FILES = set( ["conda.yaml", "MLmodel", "keras_module.txt", "save_format.txt", "model.h5"] ) def migrate_s3(s3_resource): s3_files = _find_s3_files(s3_resource, TARGET_FILES) s3_files["save_format.txt"] = _filter_h5_save_format_files( s3_resource, s3_files["save_format.txt"], s3...
0.326164
0.173009
from typing import Dict, Tuple def read_input(): with open("./input.txt", "r", encoding="utf-8") as f: return parse_input(f.read()) def parse_input(input_str: str): ret = {} for i, line in enumerate(input_str.splitlines(keepends=False)): for j, char in enumerate(line): ret[(i...
2021/day-11/solution.py
from typing import Dict, Tuple def read_input(): with open("./input.txt", "r", encoding="utf-8") as f: return parse_input(f.read()) def parse_input(input_str: str): ret = {} for i, line in enumerate(input_str.splitlines(keepends=False)): for j, char in enumerate(line): ret[(i...
0.3492
0.283258
import sys import argparse import re from blessings import Terminal from lxml import etree from difflib import unified_diff version = 2.3 parser = argparse.ArgumentParser() parser.add_argument("file1", help="XML file 1") parser.add_argument("file2", help="XML file 2") parser.add_argument("-a", "--all-context", actio...
docker/build/xdiff.py
import sys import argparse import re from blessings import Terminal from lxml import etree from difflib import unified_diff version = 2.3 parser = argparse.ArgumentParser() parser.add_argument("file1", help="XML file 1") parser.add_argument("file2", help="XML file 2") parser.add_argument("-a", "--all-context", actio...
0.166032
0.121113
import argparse import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models from collections import OrderedDict from workspace_utils import active_session import json from PIL import Image import numpy as np from torch.autograd import ...
predict.py
import argparse import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models from collections import OrderedDict from workspace_utils import active_session import json from PIL import Image import numpy as np from torch.autograd import ...
0.905473
0.364834
import os import sys import pwd import grp import logging import argparse import docker import docker.errors import dockerpty from . import dockerutils _DEFAULT_LOG_FORMAT = "%(name)s : %(threadName)s : %(levelname)s : %(message)s" logging.basicConfig( stream=sys.stderr, format=_DEFAULT_LOG_FORMAT, level...
src/dockerinside/__init__.py
import os import sys import pwd import grp import logging import argparse import docker import docker.errors import dockerpty from . import dockerutils _DEFAULT_LOG_FORMAT = "%(name)s : %(threadName)s : %(levelname)s : %(message)s" logging.basicConfig( stream=sys.stderr, format=_DEFAULT_LOG_FORMAT, level...
0.141608
0.037257
from __future__ import annotations import typing import asyncio import collections.abc from multibar.utils import ignored from multibar.core import errors from multibar.core.variants import CharsSnowflake __all__: typing.Sequence[str] = ("ProgressTools",) class ProgressTools: """``|class|`` Additional me...
multibar/tools.py
from __future__ import annotations import typing import asyncio import collections.abc from multibar.utils import ignored from multibar.core import errors from multibar.core.variants import CharsSnowflake __all__: typing.Sequence[str] = ("ProgressTools",) class ProgressTools: """``|class|`` Additional me...
0.883914
0.740667
import os import time from functools import reduce import docker import redis from celery import Celery from flask_mail import Message from loguru import logger from py2neo import Graph from application.utils.mysql_handler import change_project_status, update_task_process from application.utils.neo4j_handler import (...
backend/application/server/tasks.py
import os import time from functools import reduce import docker import redis from celery import Celery from flask_mail import Message from loguru import logger from py2neo import Graph from application.utils.mysql_handler import change_project_status, update_task_process from application.utils.neo4j_handler import (...
0.3295
0.125386
from scipy.io import loadmat from datetime import datetime import os def calc_age(taken, dob): birth = datetime.fromordinal(max(int(dob) - 366, 1)) # assume the photo was taken in the middle of the year if birth.month < 7: return taken - birth.year else: return taken - birth.year - 1 ...
src/utils.py
from scipy.io import loadmat from datetime import datetime import os def calc_age(taken, dob): birth = datetime.fromordinal(max(int(dob) - 366, 1)) # assume the photo was taken in the middle of the year if birth.month < 7: return taken - birth.year else: return taken - birth.year - 1 ...
0.295636
0.280327
#importing modules import pygame import math import sys, os pygame.init() #screen variables screenX = 1000 screenY = 800 screen = pygame.display.set_mode((screenX, screenY)) #variables mainGame = True fps = 30 clock = pygame.time.Clock() images = {} #game images images['icon'] = pygame.image.l...
Atoms And Structure/NitrogenAtom/Nitrogen.py
#importing modules import pygame import math import sys, os pygame.init() #screen variables screenX = 1000 screenY = 800 screen = pygame.display.set_mode((screenX, screenY)) #variables mainGame = True fps = 30 clock = pygame.time.Clock() images = {} #game images images['icon'] = pygame.image.l...
0.276105
0.365598
from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator import django.contrib.postgres.fields as pgfields def assignment_directory_path(instance, filename): """Used in FileField option upload_to, to upload the file to MED...
classgrade/gradapp/models.py
from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator import django.contrib.postgres.fields as pgfields def assignment_directory_path(instance, filename): """Used in FileField option upload_to, to upload the file to MED...
0.674265
0.317744
from IAuth import IAuth from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.fernet import Fernet import sys,os import time class AuthFer256(IAuth): def __init__(self,key): # Put this somewhere safe! self.key = key ...
Security/AuthFer256.py
from IAuth import IAuth from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.fernet import Fernet import sys,os import time class AuthFer256(IAuth): def __init__(self,key): # Put this somewhere safe! self.key = key ...
0.226955
0.129843
from . import visualization class Result: """ A container for the results of a simulation run. """ def __init__(self, results_tuple): self.__centerline = results_tuple[0] self.__load_step_iterations = results_tuple[1] self.__load_steps = results_tuple[2] self.__residual...
rodigan/common/result.py
from . import visualization class Result: """ A container for the results of a simulation run. """ def __init__(self, results_tuple): self.__centerline = results_tuple[0] self.__load_step_iterations = results_tuple[1] self.__load_steps = results_tuple[2] self.__residual...
0.879419
0.535341
import pprint import re # noqa: F401 import six class OrderReplacementResponse(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name ...
ultracart/models/order_replacement_response.py
import pprint import re # noqa: F401 import six class OrderReplacementResponse(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name ...
0.625095
0.126785
from headers.BeaEnginePython import * from nose.tools import * class TestSuite: def test(self): # 66 0F 7C /r # HADDPD xmm1, xmm2/m128 Buffer = bytes.fromhex('660f7c9000000000') myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Opco...
src/third_party/beaengine/tests/0f7c.py
from headers.BeaEnginePython import * from nose.tools import * class TestSuite: def test(self): # 66 0F 7C /r # HADDPD xmm1, xmm2/m128 Buffer = bytes.fromhex('660f7c9000000000') myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Opco...
0.702122
0.380356
from pathlib import Path import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import ScriptedLoadableModule, ScriptedLoadableModuleWidget from slicer.util import VTKObservationMixin from EPISURGBase import EPISURGBaseLogic # pylint: disable=import-error EPISURG_URL = 'https://s3-eu-west-1.amazonaws.com/ps...
EPISURGBrowser/EPISURGBrowser.py
from pathlib import Path import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import ScriptedLoadableModule, ScriptedLoadableModuleWidget from slicer.util import VTKObservationMixin from EPISURGBase import EPISURGBaseLogic # pylint: disable=import-error EPISURG_URL = 'https://s3-eu-west-1.amazonaws.com/ps...
0.714329
0.318724
from typing import Dict, Any, List from cobot_core import SelectingStrategy from cobot_core.offensive_speech_classifier import OffensiveSpeechClassifier import example.sensitive_response_generator.utils as sensitive_response_utils from example.dialogues.StateTransitionPrompts import StateTransitionPrompts from exampl...
ap-taskbot-snippets/automata_selecting_strategy.py
from typing import Dict, Any, List from cobot_core import SelectingStrategy from cobot_core.offensive_speech_classifier import OffensiveSpeechClassifier import example.sensitive_response_generator.utils as sensitive_response_utils from example.dialogues.StateTransitionPrompts import StateTransitionPrompts from exampl...
0.707708
0.262987
import argparse import sys import inspect from ingest_validation_tools.error_report import ErrorReport from ingest_validation_tools.cli_utils import ShowUsageException, exit_codes from ingest_validation_tools.schema_loader import PreflightError from ingest_validation_tools.validation_utils import ( get_tsv_errors...
src/validate_tsv.py
import argparse import sys import inspect from ingest_validation_tools.error_report import ErrorReport from ingest_validation_tools.cli_utils import ShowUsageException, exit_codes from ingest_validation_tools.schema_loader import PreflightError from ingest_validation_tools.validation_utils import ( get_tsv_errors...
0.258232
0.153454