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
import numpy as np import glob import random import torch import torch.utils.data from analyzer.data.utils.data_raw import * from analyzer.data.utils.data_misc import * from analyzer.data.augmentation import Augmentor class PairDataset(): ''' This Dataloader will prepare sample that are pairs for feeding the c...
analyzer/data/pair_dataset.py
import numpy as np import glob import random import torch import torch.utils.data from analyzer.data.utils.data_raw import * from analyzer.data.utils.data_misc import * from analyzer.data.augmentation import Augmentor class PairDataset(): ''' This Dataloader will prepare sample that are pairs for feeding the c...
0.691289
0.363506
import tvm import multiprocessing as mp import time import datetime import sys import random import os from pprint import pprint from functools import reduce import operator import math import tqdm import pickle import concurrent.futures import numpy as np import pandas as pd from dMazeRunner.common import layer_info...
experiments/dse_tune_memory_256_PE/tune_memory.py
import tvm import multiprocessing as mp import time import datetime import sys import random import os from pprint import pprint from functools import reduce import operator import math import tqdm import pickle import concurrent.futures import numpy as np import pandas as pd from dMazeRunner.common import layer_info...
0.217171
0.196498
# Form implementation generated from reading ui file 'cmw500ManagerWindow.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): ...
cmw500ManagerWindowNew.py
# Form implementation generated from reading ui file 'cmw500ManagerWindow.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): ...
0.347094
0.038538
import multiprocessing import time from datetime import datetime from django.test import TransactionTestCase from django import db from ambition_utils.postgres_lock.lock import PostgresLockContext, PostgresLockException def acquire_postgres_lock(queue, process_name, lock_name, lock_timeout, sleep=0): # pragma: no...
ambition_utils/postgres_lock/tests/lock_tests.py
import multiprocessing import time from datetime import datetime from django.test import TransactionTestCase from django import db from ambition_utils.postgres_lock.lock import PostgresLockContext, PostgresLockException def acquire_postgres_lock(queue, process_name, lock_name, lock_timeout, sleep=0): # pragma: no...
0.475362
0.115436
import unittest import itertools import tempfile import numpy as np import model from assignments.cached import CachedAssignment from assignments.sparse import SparseAssignment class SparseTests(unittest.TestCase): '''Tests fort he sparse assignment module.''' def test_labels(self): '''Verify that th...
tests/assignmenttests.py
import unittest import itertools import tempfile import numpy as np import model from assignments.cached import CachedAssignment from assignments.sparse import SparseAssignment class SparseTests(unittest.TestCase): '''Tests fort he sparse assignment module.''' def test_labels(self): '''Verify that th...
0.557604
0.591664
from keras.layers import Dense, Dropout, BatchNormalization from .shapes import shapes from ..utils.exceptions import TalosTypeError, TalosParamsError class hidden_layers: def __init__(self,params,last_neuron,batch_normalization=False): self.batch_normalization = batch_normalization try: ...
talos/model/layers.py
from keras.layers import Dense, Dropout, BatchNormalization from .shapes import shapes from ..utils.exceptions import TalosTypeError, TalosParamsError class hidden_layers: def __init__(self,params,last_neuron,batch_normalization=False): self.batch_normalization = batch_normalization try: ...
0.811377
0.272563
from django.urls import reverse, resolve from core.tests.base_class import TestCasePlus class TestURLs( TestCasePlus ): def test_list_reverse(self): """categories:index should reverse to /categories/.""" self.assertEqual(reverse('categories:index'), '/categories/') def test_lis...
categories/tests/test_urls.py
from django.urls import reverse, resolve from core.tests.base_class import TestCasePlus class TestURLs( TestCasePlus ): def test_list_reverse(self): """categories:index should reverse to /categories/.""" self.assertEqual(reverse('categories:index'), '/categories/') def test_lis...
0.523664
0.184088
import http.client import http.server import json class OpenFDAClient(): OPENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_DRUG = '&search=patient.drug.medicinalproduct:' OPENFDA_API_COMPANY='&search=companynumb:' def get_event(self, limite): conn = http...
web.py
import http.client import http.server import json class OpenFDAClient(): OPENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_DRUG = '&search=patient.drug.medicinalproduct:' OPENFDA_API_COMPANY='&search=companynumb:' def get_event(self, limite): conn = http...
0.139045
0.057705
# pyright: reportUnknownMemberType=none # This leads to too many false-positives around mocks. import typing from unittest import mock import hikari import pytest import tanjun @pytest.fixture() def command() -> tanjun.abc.ExecutableCommand[typing.Any]: command_ = mock.MagicMock(tanjun.abc.ExecutableCommand) ...
tests/test_checks.py
# pyright: reportUnknownMemberType=none # This leads to too many false-positives around mocks. import typing from unittest import mock import hikari import pytest import tanjun @pytest.fixture() def command() -> tanjun.abc.ExecutableCommand[typing.Any]: command_ = mock.MagicMock(tanjun.abc.ExecutableCommand) ...
0.810816
0.406509
from tkinter import * from tkinter import messagebox from PIL import Image, ImageTk import numpy as np import pandas as pd # Define useful parameters IMAGE_WIDTH = 1400 WIDTH = 1700 IMAGE_HEIGHT = 602 HEIGHT = 700 LENGTH = 14 COLORS = {0: "none", 1: "white", 2: "green", 3: "red"} # 열린 목록 닫힌 목록 길 등은 나중에 추가 class Ca...
CamelPathFinding.py
from tkinter import * from tkinter import messagebox from PIL import Image, ImageTk import numpy as np import pandas as pd # Define useful parameters IMAGE_WIDTH = 1400 WIDTH = 1700 IMAGE_HEIGHT = 602 HEIGHT = 700 LENGTH = 14 COLORS = {0: "none", 1: "white", 2: "green", 3: "red"} # 열린 목록 닫힌 목록 길 등은 나중에 추가 class Ca...
0.643777
0.199717
from __future__ import absolute_import, print_function __author__ = 'katharine' import atexit import logging import math import os import sys import threading import time import requests from pebble_tool.version import __version__ from pebble_tool.sdk import sdk_manager from pebble_tool.util.config import config from...
pebble_tool/util/updates.py
from __future__ import absolute_import, print_function __author__ = 'katharine' import atexit import logging import math import os import sys import threading import time import requests from pebble_tool.version import __version__ from pebble_tool.sdk import sdk_manager from pebble_tool.util.config import config from...
0.322739
0.052522
from FoxDot import * import subprocess import math import parser import tocator import argparse # I'm putting this here because I think it can hypothetically make a difference in a bizarre corner case Clock.set_time(7) Scale.default = "chromatic" #we want chromatic because it has all of our western notes Root.default ...
main.py
from FoxDot import * import subprocess import math import parser import tocator import argparse # I'm putting this here because I think it can hypothetically make a difference in a bizarre corner case Clock.set_time(7) Scale.default = "chromatic" #we want chromatic because it has all of our western notes Root.default ...
0.321567
0.120129
import json import glob from pprint import pprint as pp def logReader(): jsl=[] for i in glob.glob('LOGS/msglog*.json'): with open (i,'r') as f: j=json.load(f) jsl=jsl+j return jsl def msgCatCounter(jsl): try: msg_cat_count_dict=dict(zip({i['orig_message'].split('%')[1].split(...
localparser.py
import json import glob from pprint import pprint as pp def logReader(): jsl=[] for i in glob.glob('LOGS/msglog*.json'): with open (i,'r') as f: j=json.load(f) jsl=jsl+j return jsl def msgCatCounter(jsl): try: msg_cat_count_dict=dict(zip({i['orig_message'].split('%')[1].split(...
0.085459
0.128635
import sys import textwrap import traceback import winsound import wx class ExceptionDialog(wx.Dialog): """This class displays an error dialog with details information about the input exception, including a traceback.""" def __init__(self, error_string): wx.Dialog.__init__(self, None, -1, title=...
source/GUI/error_dialog.py
import sys import textwrap import traceback import winsound import wx class ExceptionDialog(wx.Dialog): """This class displays an error dialog with details information about the input exception, including a traceback.""" def __init__(self, error_string): wx.Dialog.__init__(self, None, -1, title=...
0.348423
0.064683
import json from alipay.aop.api.constant.ParamConstants import * class ServiceConsultQueryResponse(object): def __init__(self): self._consult_event_id = None self._content = None self._gmt_create = None self._gmt_finished = None self._gmt_modified = None self._ima...
alipay/aop/api/domain/ServiceConsultQueryResponse.py
import json from alipay.aop.api.constant.ParamConstants import * class ServiceConsultQueryResponse(object): def __init__(self): self._consult_event_id = None self._content = None self._gmt_create = None self._gmt_finished = None self._gmt_modified = None self._ima...
0.513912
0.10026
import datetime import jwt import logging import os from collections import OrderedDict import django_filters.rest_framework from django.http import HttpResponse, JsonResponse from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.shortcuts import render from r...
anno2/views.py
import datetime import jwt import logging import os from collections import OrderedDict import django_filters.rest_framework from django.http import HttpResponse, JsonResponse from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.shortcuts import render from r...
0.265214
0.048541
import collections import glob import os from collections import OrderedDict from typing import Generator from being.configuration import CONFIG from being.curve import Curve from being.logging import get_logger from being.pubsub import PubSub from being.serialization import loads, dumps from being.spline import BPoly...
being/content.py
import collections import glob import os from collections import OrderedDict from typing import Generator from being.configuration import CONFIG from being.curve import Curve from being.logging import get_logger from being.pubsub import PubSub from being.serialization import loads, dumps from being.spline import BPoly...
0.797083
0.137475
from __future__ import absolute_import, unicode_literals import json import pytest import yaml from servicelib.compat import PY2, env_var, open def test_get(script_runner, config_server, monkeypatch): config_server.initial_config = {"foo": 42, "bar": {"baz": 42.0}} config_server.start() monkeypatch.se...
tests/test_config_cmd_client.py
from __future__ import absolute_import, unicode_literals import json import pytest import yaml from servicelib.compat import PY2, env_var, open def test_get(script_runner, config_server, monkeypatch): config_server.initial_config = {"foo": 42, "bar": {"baz": 42.0}} config_server.start() monkeypatch.se...
0.693161
0.209631
# Add RunManager modules to PYTHONPATH import sys import params sys.path.append(params.RM_DIR) import os import cgi from RunManager import * from HTMLLib import * # Globals rm = None erf_list = [] sgt_var_list = [] rup_var_list = [] # Enable python stack trace output to HTML import cgitb; cgitb.enable() def ini...
runmanager/RunManager/website/cgi-bin/doadd.py
# Add RunManager modules to PYTHONPATH import sys import params sys.path.append(params.RM_DIR) import os import cgi from RunManager import * from HTMLLib import * # Globals rm = None erf_list = [] sgt_var_list = [] rup_var_list = [] # Enable python stack trace output to HTML import cgitb; cgitb.enable() def ini...
0.170612
0.057679
from rest_framework.views import APIView from rest_framework import viewsets from rest_framework.response import Response from rest_framework import status from django.contrib.auth import get_user_model from rest_framework.authentication import TokenAuthentication from rest_framework import filters from rest_framework....
app/core/views.py
from rest_framework.views import APIView from rest_framework import viewsets from rest_framework.response import Response from rest_framework import status from django.contrib.auth import get_user_model from rest_framework.authentication import TokenAuthentication from rest_framework import filters from rest_framework....
0.776199
0.103205
class tree_node(object): def __init__(self, val): self.val = val self.left = None self.right = None class binary_search_tree(object): def __init__(self): self.root = None def insert(self, val): if not self.root: self.root = tree_node(val) ...
binary_search_tree.py
class tree_node(object): def __init__(self, val): self.val = val self.left = None self.right = None class binary_search_tree(object): def __init__(self): self.root = None def insert(self, val): if not self.root: self.root = tree_node(val) ...
0.527803
0.154823
try: from ._models_py3 import AutoScaleVCore from ._models_py3 import AutoScaleVCoreListResult from ._models_py3 import AutoScaleVCoreMutableProperties from ._models_py3 import AutoScaleVCoreProperties from ._models_py3 import AutoScaleVCoreSku from ._models_py3 import AutoScaleVCoreUpdateParam...
sdk/powerbidedicated/azure-mgmt-powerbidedicated/azure/mgmt/powerbidedicated/models/__init__.py
try: from ._models_py3 import AutoScaleVCore from ._models_py3 import AutoScaleVCoreListResult from ._models_py3 import AutoScaleVCoreMutableProperties from ._models_py3 import AutoScaleVCoreProperties from ._models_py3 import AutoScaleVCoreSku from ._models_py3 import AutoScaleVCoreUpdateParam...
0.52829
0.0686
from PyQt5 import QtWidgets as qtw from PyQt5 import QtGui as qtg from PyQt5 import QtCore as qtc import csv from datetime import datetime import pandas as pd from PyQt5 import QtChart as qtch months = ['','January','February','March','April','May','June','July','August','September','October','November', ...
2-Intermediate/expense_tracker/sample/overviewpage.py
from PyQt5 import QtWidgets as qtw from PyQt5 import QtGui as qtg from PyQt5 import QtCore as qtc import csv from datetime import datetime import pandas as pd from PyQt5 import QtChart as qtch months = ['','January','February','March','April','May','June','July','August','September','October','November', ...
0.361165
0.14682
import logging import collections from django.core.management.color import supports_color Level = collections.namedtuple('Level', ['title', 'color',]) Palette = collections.namedtuple('Palette', [ 'bk', 'rd', 'gn', 'yw', 'be', 'ma', 'cn', 'we', 'bkb', 'rdb', 'gnb', 'ywb', 'beb', 'mab', 'cnb', 'web', 'r', ]) ...
sakkada/utils/log.py
import logging import collections from django.core.management.color import supports_color Level = collections.namedtuple('Level', ['title', 'color',]) Palette = collections.namedtuple('Palette', [ 'bk', 'rd', 'gn', 'yw', 'be', 'ma', 'cn', 'we', 'bkb', 'rdb', 'gnb', 'ywb', 'beb', 'mab', 'cnb', 'web', 'r', ]) ...
0.386416
0.231745
from PIL import Image from cdist import cdist from django.conf import settings from django.core.management import call_command from django.test import TestCase from ujson import dumps as repr from tempfile import NamedTemporaryFile from tomoko.lib.equal import equal from tomoko.repaint import int_to_pixel, pixel_to_int...
mokocchi/tomoko/repaint/test.py
from PIL import Image from cdist import cdist from django.conf import settings from django.core.management import call_command from django.test import TestCase from ujson import dumps as repr from tempfile import NamedTemporaryFile from tomoko.lib.equal import equal from tomoko.repaint import int_to_pixel, pixel_to_int...
0.620162
0.467879
from datetime import datetime, timedelta from django.contrib.auth.models import User from django.http import Http404 from django.shortcuts import redirect, get_object_or_404, render from django.utils import timezone from django.utils.datetime_safe import date from django.views.generic.base import View from rest_framew...
attendance/views.py
from datetime import datetime, timedelta from django.contrib.auth.models import User from django.http import Http404 from django.shortcuts import redirect, get_object_or_404, render from django.utils import timezone from django.utils.datetime_safe import date from django.views.generic.base import View from rest_framew...
0.504639
0.190141
import os import pkgutil import sys import bbcode from grow import extensions from grow.documents import document, static_document from grow.extensions import hooks SHORTCODES_DIR = 'shortcodes' class ShortcodesPreRenderHook(hooks.PreRenderHook): """Handle the post-render hook.""" def should_trigger(self, ...
pages/extensions/shortcodes/extension.py
import os import pkgutil import sys import bbcode from grow import extensions from grow.documents import document, static_document from grow.extensions import hooks SHORTCODES_DIR = 'shortcodes' class ShortcodesPreRenderHook(hooks.PreRenderHook): """Handle the post-render hook.""" def should_trigger(self, ...
0.418935
0.116161
# Copyright: (c) 2019, <NAME> (@vasilyprokopov) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], ...
venv/lib/python3.6/site-packages/ansible_collections/cisco/aci/plugins/modules/aci_interface_policy_link_level.py
# Copyright: (c) 2019, <NAME> (@vasilyprokopov) # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], ...
0.839865
0.357904
import os import pytest from click.testing import CliRunner from pipdownload.cli import pipdownload from pipdownload.utils import TempDirectory @pytest.fixture(scope="module") def requirement_file_redundant(): return os.path.abspath(os.path.join(os.getcwd(), 'tests/test_requirements_redundant.txt')) ...
virtual/lib/python3.6/site-packages/tests/commands/test_cli.py
import os import pytest from click.testing import CliRunner from pipdownload.cli import pipdownload from pipdownload.utils import TempDirectory @pytest.fixture(scope="module") def requirement_file_redundant(): return os.path.abspath(os.path.join(os.getcwd(), 'tests/test_requirements_redundant.txt')) ...
0.26971
0.248557
import io import matplotlib.style as mplstyle from .gifconfig import * from .func_input import * from .gifmaker import * from .historylog import * from .preconfig import * mplstyle.use('fast') ''' 在这里注明一下用到的第三方模块: numpy,moviepy,matplotlib,imageio... ''' def get_settings(setting_data: dict): """ setting_data...
python_code/botcode/plugins/fun_pic_plug/main.py
import io import matplotlib.style as mplstyle from .gifconfig import * from .func_input import * from .gifmaker import * from .historylog import * from .preconfig import * mplstyle.use('fast') ''' 在这里注明一下用到的第三方模块: numpy,moviepy,matplotlib,imageio... ''' def get_settings(setting_data: dict): """ setting_data...
0.179028
0.119819
import napari import numpy as np from dask import array as da from transitions import Machine from ._logging import log_error from ._logging import logger from ._transitions import transitions from ._viewer_model import ViewerModel from ._viewer_model import ViewerState # XXX tenative implementation : pluginfy later...
src/napari_travali/_viewer.py
import napari import numpy as np from dask import array as da from transitions import Machine from ._logging import log_error from ._logging import logger from ._transitions import transitions from ._viewer_model import ViewerModel from ._viewer_model import ViewerState # XXX tenative implementation : pluginfy later...
0.596786
0.153137
"""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...
tools/visualize/node_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.333612
0.082512
import os import shutil import logging import mock from django.urls import reverse from django.test import override_settings from rest_framework import status from rest_framework.test import APITestCase from substrapp.ledger_utils import LedgerError from substrapp.utils import get_hash from ..common import get_sa...
substrabac/substrapp/tests/views/tests_views_model.py
import os import shutil import logging import mock from django.urls import reverse from django.test import override_settings from rest_framework import status from rest_framework.test import APITestCase from substrapp.ledger_utils import LedgerError from substrapp.utils import get_hash from ..common import get_sa...
0.410047
0.123736
import os import sys import random import math import numpy as np import cv2 import colorsys # Root directory of the project ROOT_DIR = os.path.abspath("../../") # Import Mask RCNN sys.path.append(ROOT_DIR) # To find local version of the library from mrcnn import utils from samples.davis import davis def hsv2rgb(...
samples/davis/make_video.py
import os import sys import random import math import numpy as np import cv2 import colorsys # Root directory of the project ROOT_DIR = os.path.abspath("../../") # Import Mask RCNN sys.path.append(ROOT_DIR) # To find local version of the library from mrcnn import utils from samples.davis import davis def hsv2rgb(...
0.378919
0.158663
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('houses', '0001_initial'), ] operations = [ migrations.CreateModel( name='Browses', fields=[ ('id', models.AutoField(auto_created=True,...
houses/migrations/0002_auto_20191130_2157.py
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('houses', '0001_initial'), ] operations = [ migrations.CreateModel( name='Browses', fields=[ ('id', models.AutoField(auto_created=True,...
0.493164
0.131703
import setuptools long_description = """# MathLibrary Math Library for Python # Installation ```python pip install MathLibrary ``` # Example ```python from MathLibrary import * print(fact(5)) ``` ### Output : #### ```120``` # Props | Props | Description ...
setup.py
import setuptools long_description = """# MathLibrary Math Library for Python # Installation ```python pip install MathLibrary ``` # Example ```python from MathLibrary import * print(fact(5)) ``` ### Output : #### ```120``` # Props | Props | Description ...
0.865253
0.626596
__doc__ = """ sam3 backend to i2p.socket """ from i2p.socket.sam import simple import socket as pysocket SOCK_STREAM = pysocket.SOCK_STREAM SOCK_DGRAM = pysocket.SOCK_DGRAM SOCK_RAW = pysocket.SOCK_RAW # socket flags for shutdown() SHUT_RD = pysocket.SHUT_RD SHUT_WR = pysocket.SHUT_WR SHUT_RDWR = pysocket.SHUT_RDWR ...
pyi2tun/i2p/socket/sam/__init__.py
__doc__ = """ sam3 backend to i2p.socket """ from i2p.socket.sam import simple import socket as pysocket SOCK_STREAM = pysocket.SOCK_STREAM SOCK_DGRAM = pysocket.SOCK_DGRAM SOCK_RAW = pysocket.SOCK_RAW # socket flags for shutdown() SHUT_RD = pysocket.SHUT_RD SHUT_WR = pysocket.SHUT_WR SHUT_RDWR = pysocket.SHUT_RDWR ...
0.183484
0.072047
import pandas as pd import numpy as np import pickle from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import f1_score def create_disease_hash(): dataset = pd.read_csv('dataset.csv') ...
model/Model.py
import pandas as pd import numpy as np import pickle from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import f1_score def create_disease_hash(): dataset = pd.read_csv('dataset.csv') ...
0.299208
0.222605
class node: def __init__(self, data=None): self.data = data self.link = None class LinkedList: def __init__(self, head=None): self.head = head self.non = 0 def display(self): p = self.head print(f"No of elements in the list are:{self.non}") while p...
py/LinkedList.py
class node: def __init__(self, data=None): self.data = data self.link = None class LinkedList: def __init__(self, head=None): self.head = head self.non = 0 def display(self): p = self.head print(f"No of elements in the list are:{self.non}") while p...
0.560614
0.320316
import speech_recognition as sr class CouldNotRecognizeError(Exception): def __init__(self, message): self.message = message class ServerRequestError(Exception): def __init__(self, message): self.message = message class SRModule: def __init__(self): self.recognizer = sr.Recogni...
src/SpeechRecog/SRModule.py
import speech_recognition as sr class CouldNotRecognizeError(Exception): def __init__(self, message): self.message = message class ServerRequestError(Exception): def __init__(self, message): self.message = message class SRModule: def __init__(self): self.recognizer = sr.Recogni...
0.584983
0.164718
from abc import ABCMeta, abstractmethod """ Here Program superclass """ class Programa(metaclass = ABCMeta): def __init__(self, nome, ano): self._nome = nome.title() self.ano = ano self._likes = 0 @abstractmethod def __str__(self): pass @property def likes(...
Playlist/module/modelo.py
from abc import ABCMeta, abstractmethod """ Here Program superclass """ class Programa(metaclass = ABCMeta): def __init__(self, nome, ano): self._nome = nome.title() self.ano = ano self._likes = 0 @abstractmethod def __str__(self): pass @property def likes(...
0.726426
0.153011
from lasagne import layers from lasagne.updates import nesterov_momentum from nolearn.lasagne import NeuralNet,BatchIterator import os import numpy as np from sklearn.utils import shuffle import cPickle as pickle import matplotlib.pyplot as plt import Image import ImageOps from scipy import misc import scipy.io import ...
shallow/preprocessing.py
from lasagne import layers from lasagne.updates import nesterov_momentum from nolearn.lasagne import NeuralNet,BatchIterator import os import numpy as np from sklearn.utils import shuffle import cPickle as pickle import matplotlib.pyplot as plt import Image import ImageOps from scipy import misc import scipy.io import ...
0.256832
0.283137
# # Text Data # # ## Pre-introduction # # We'll be spending a lot of time today manipulating text. Make sure you remember how to split, join, and search strings. # ## Introduction # # We've spent a lot of time in python dealing with text data, and that's because text data is everywhere. It is the primary form of c...
instructor/day_three.py
# # Text Data # # ## Pre-introduction # # We'll be spending a lot of time today manipulating text. Make sure you remember how to split, join, and search strings. # ## Introduction # # We've spent a lot of time in python dealing with text data, and that's because text data is everywhere. It is the primary form of c...
0.652352
0.685772
"""Generated protocol buffer code.""" from google.protobuf.internal import enum_type_wrapper 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 # @@pro...
src/anko/proto/gateway_pb2.py
"""Generated protocol buffer code.""" from google.protobuf.internal import enum_type_wrapper 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 # @@pro...
0.332961
0.156234
import json import re from collections import Counter import pandas as pd import pysrt from booknlp.booknlp import BookNLP class TextAnalyzer: def __init__(self): model_params = { "model": "small", "pipeline": "entity,quote,event,coref", } self.model = BookNLP("en"...
notebooks/nlp/analyzer.py
import json import re from collections import Counter import pandas as pd import pysrt from booknlp.booknlp import BookNLP class TextAnalyzer: def __init__(self): model_params = { "model": "small", "pipeline": "entity,quote,event,coref", } self.model = BookNLP("en"...
0.400163
0.183905
import time import datetime import struct import msgpack import pytz from . import config if config.get("STORE_DRIVER") == 'redis': server_id = int(config.get("STORE_REDIS_SERVER_ID")) else: server_id = 0 class Plan(object): count_index = 0 def __init__(self, key, second=0, minute = -1, hour = -1, d...
forsun/plan.py
import time import datetime import struct import msgpack import pytz from . import config if config.get("STORE_DRIVER") == 'redis': server_id = int(config.get("STORE_REDIS_SERVER_ID")) else: server_id = 0 class Plan(object): count_index = 0 def __init__(self, key, second=0, minute = -1, hour = -1, d...
0.374448
0.164684
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, BooleanField, HiddenField from wtforms.validators import DataRequired, Email, Length, EqualTo, ValidationError from app.models.user import User password_validation = [Length(min=8, message='Password must be at least 8 charac...
app/views/auth/forms.py
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, BooleanField, HiddenField from wtforms.validators import DataRequired, Email, Length, EqualTo, ValidationError from app.models.user import User password_validation = [Length(min=8, message='Password must be at least 8 charac...
0.530723
0.193528
from pybrain.rl.environments.timeseries.maximizereturntask import MaximizeReturnTask, NeuneierRewardTask from pybrain.rl.environments.timeseries.timeseries import AR1Environment, SnPEnvironment from pybrain.rl.learners.directsearch.enac import ENAC from pybrain.rl.learners.directsearch.rrl import RRL from pybrain.tools...
pybrain/rl/environments/timeseries/ar1RRL.py
from pybrain.rl.environments.timeseries.maximizereturntask import MaximizeReturnTask, NeuneierRewardTask from pybrain.rl.environments.timeseries.timeseries import AR1Environment, SnPEnvironment from pybrain.rl.learners.directsearch.enac import ENAC from pybrain.rl.learners.directsearch.rrl import RRL from pybrain.tools...
0.586168
0.404331
import unittest import os.path import xml.etree.cElementTree as ET from ..aio.annotationpro import sppasANTX from ..aio.annotationpro import sppasANT from ..ann.annlocation import sppasPoint from ..tier import sppasTier from ..media import sppasMedia # -----------------------------------------------------------------...
sppas/sppas/src/anndata/tests/test_aio_annotationpro.py
import unittest import os.path import xml.etree.cElementTree as ET from ..aio.annotationpro import sppasANTX from ..aio.annotationpro import sppasANT from ..ann.annlocation import sppasPoint from ..tier import sppasTier from ..media import sppasMedia # -----------------------------------------------------------------...
0.568895
0.409929
import numpy as np import cv2 import time import math def distance_estimate(alt, deviation): alt = alt * 100 a = 0.002 b = -0.0129 pixel_to_cm = a * alt + b return deviation * pixel_to_cm / 100 cap = cv2.VideoCapture(0) distance = 0.7 while True: ret, frame = cap.read() if ret == True: ...
ObjectTracking.py
import numpy as np import cv2 import time import math def distance_estimate(alt, deviation): alt = alt * 100 a = 0.002 b = -0.0129 pixel_to_cm = a * alt + b return deviation * pixel_to_cm / 100 cap = cv2.VideoCapture(0) distance = 0.7 while True: ret, frame = cap.read() if ret == True: ...
0.521227
0.330606
import sys reload(sys) sys.setdefaultencoding("utf-8") import os import types import logging import json from core import utils from modules.dataextractors.mldataextractor import MLDataExtractor from generic_modules.NameDetector import GenericNameDetector """ Class PersonDetector as described at: Copyright (c) 2019...
modules/dataextractors/nameextractor.py
import sys reload(sys) sys.setdefaultencoding("utf-8") import os import types import logging import json from core import utils from modules.dataextractors.mldataextractor import MLDataExtractor from generic_modules.NameDetector import GenericNameDetector """ Class PersonDetector as described at: Copyright (c) 2019...
0.492188
0.159217
from django.db import models from django.urls import reverse from ckeditor_uploader.fields import RichTextUploadingField class ProgressOutcome(models.Model): """Model for an progress outcome.""" progress_outcome_number = models.PositiveSmallIntegerField(default=1) code = models.CharField(max_length=30) ...
dthm4kaiako/poet/models.py
from django.db import models from django.urls import reverse from ckeditor_uploader.fields import RichTextUploadingField class ProgressOutcome(models.Model): """Model for an progress outcome.""" progress_outcome_number = models.PositiveSmallIntegerField(default=1) code = models.CharField(max_length=30) ...
0.842345
0.209631
import optparse, nmap import json class NmapScannerJSONGenerate: def __init__(self): self.nmsc = nmap.PortScanner() def nmapScan(self, host, port): try: print "Checking port "+ port +" .........." self.nmsc.scan(host, port) # Command ...
chapter8/code/python-nmap/NmapScannerJSONGenerate.py
import optparse, nmap import json class NmapScannerJSONGenerate: def __init__(self): self.nmsc = nmap.PortScanner() def nmapScan(self, host, port): try: print "Checking port "+ port +" .........." self.nmsc.scan(host, port) # Command ...
0.225843
0.088426
try: import matplotlib.pyplot as plt except: print("On philly") from PIL import Image import torch, argparse import torchvision.utils as vutils import numpy as np tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), (44, 160, 44), (152, 223, 138), (214, 39, 40), ...
lib/manipulate.py
try: import matplotlib.pyplot as plt except: print("On philly") from PIL import Image import torch, argparse import torchvision.utils as vutils import numpy as np tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), (44, 160, 44), (152, 223, 138), (214, 39, 40), ...
0.387343
0.342489
import cv2 import numpy as np import easygui from matplotlib import pyplot as plt from matplotlib import image as image # Opening an image using a File Open dialog: #f = easygui.fileopenbox() #Opening an image I = cv2.imread("Text.jpg") #The following code extracts the Y channel, apply the histm equalization and conv...
lighting_correction.py
import cv2 import numpy as np import easygui from matplotlib import pyplot as plt from matplotlib import image as image # Opening an image using a File Open dialog: #f = easygui.fileopenbox() #Opening an image I = cv2.imread("Text.jpg") #The following code extracts the Y channel, apply the histm equalization and conv...
0.701917
0.554229
import contextlib import enum import logging import typing from hat import aio from hat.drivers import cotp mlog = logging.getLogger(__name__) Data = typing.Union[bytes, bytearray, memoryview] """Data""" Address = cotp.Address """Address""" class ConnectionInfo(typing.NamedTuple): loca...
src_py/hat/drivers/cosp.py
import contextlib import enum import logging import typing from hat import aio from hat.drivers import cotp mlog = logging.getLogger(__name__) Data = typing.Union[bytes, bytearray, memoryview] """Data""" Address = cotp.Address """Address""" class ConnectionInfo(typing.NamedTuple): loca...
0.614625
0.141519
from marshmallow import fields, Schema from marshmallow.validate import OneOf from ..enums import * from ..models.BaseSchema import BaseSchema class FeedbackValidator: class getAttributes(BaseSchema): company_id = fields.Str(required=False) application_id = fields.Str(requir...
fdk_client/platform/models/FeedbackValidator.py
from marshmallow import fields, Schema from marshmallow.validate import OneOf from ..enums import * from ..models.BaseSchema import BaseSchema class FeedbackValidator: class getAttributes(BaseSchema): company_id = fields.Str(required=False) application_id = fields.Str(requir...
0.456168
0.09343
import logging import mwparserfromhell from ntee.utils.my_tokenizer import RegexpTokenizer logger = logging.getLogger(__name__) class Paragraph(object): __slots__ = ('text', 'words', 'wiki_links') def __init__(self, text, words, wiki_links): self.text = text self.words = words self....
ntee/utils/wiki_extractor.py
import logging import mwparserfromhell from ntee.utils.my_tokenizer import RegexpTokenizer logger = logging.getLogger(__name__) class Paragraph(object): __slots__ = ('text', 'words', 'wiki_links') def __init__(self, text, words, wiki_links): self.text = text self.words = words self....
0.41941
0.074131
import os import sys import argparse def read_log_file(log_file): fs = open(log_file, 'r') lines = fs.readlines() fs.close() useful_lines = [] validation_lines = [] for i in range(len(lines)): line = lines[i].rstrip() if "Epoch:" in line and ("UserWarning" not in line): ...
train-log-parser/train_log_parser.py
import os import sys import argparse def read_log_file(log_file): fs = open(log_file, 'r') lines = fs.readlines() fs.close() useful_lines = [] validation_lines = [] for i in range(len(lines)): line = lines[i].rstrip() if "Epoch:" in line and ("UserWarning" not in line): ...
0.101089
0.343232
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0036_add_facettype_to_basefacet'), ] operations = [ migrations.AlterUniqueTogether( name='focus', unique_together=None, ), migrations.RemoveField( ...
core/migrations/0037_remove_facet_models.py
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0036_add_facettype_to_basefacet'), ] operations = [ migrations.AlterUniqueTogether( name='focus', unique_together=None, ), migrations.RemoveField( ...
0.615897
0.100304
import urllib.request import boto3 import os sqs = boto3.client('sqs') rekognition = boto3.client('rekognition') def analyze_themes(file, min_confidence=80): with open(file, 'rb') as document: imageBytes = bytearray(document.read()) response = rekognition.detect_moderation_labels(Image={'Bytes': ima...
process-new-images/index.py
import urllib.request import boto3 import os sqs = boto3.client('sqs') rekognition = boto3.client('rekognition') def analyze_themes(file, min_confidence=80): with open(file, 'rb') as document: imageBytes = bytearray(document.read()) response = rekognition.detect_moderation_labels(Image={'Bytes': ima...
0.434941
0.173044
"""Module that can create mocks for testing.""" from __future__ import print_function import boto3 def create_sns_topic(topic_name, region_name='us-east-1'): """Used with moto, create an SNS topic""" # make an SNS topic client = boto3.client('sns', region_name=region_name) response = client.create_to...
ebs_snapper/mocks.py
"""Module that can create mocks for testing.""" from __future__ import print_function import boto3 def create_sns_topic(topic_name, region_name='us-east-1'): """Used with moto, create an SNS topic""" # make an SNS topic client = boto3.client('sns', region_name=region_name) response = client.create_to...
0.732305
0.281856
import os, json, datetime from s3ts.utils import datetimeFromIso class S3Access(object): """Provide connection parameters for an s3m store""" def __init__( self, awsKey, awsSecret, s3Bucket ): self.awsKey = awsKey self.awsSecret = awsSecret self.s3Bucket = s3Bucket class S3A...
src/s3ts/config.py
import os, json, datetime from s3ts.utils import datetimeFromIso class S3Access(object): """Provide connection parameters for an s3m store""" def __init__( self, awsKey, awsSecret, s3Bucket ): self.awsKey = awsKey self.awsSecret = awsSecret self.s3Bucket = s3Bucket class S3A...
0.519765
0.091301
from django.http import JsonResponse, HttpResponseBadRequest, HttpResponse from src.tipboard.app.applicationconfig import getRedisPrefix from src.tipboard.app.properties import BASIC_CONFIG, REDIS_DB, DEBUG, ALLOWED_TILES from src.tipboard.app.cache import MyCache, save_tile from src.tipboard.app.utils import checkAcce...
src/tipboard/app/views/api.py
from django.http import JsonResponse, HttpResponseBadRequest, HttpResponse from src.tipboard.app.applicationconfig import getRedisPrefix from src.tipboard.app.properties import BASIC_CONFIG, REDIS_DB, DEBUG, ALLOWED_TILES from src.tipboard.app.cache import MyCache, save_tile from src.tipboard.app.utils import checkAcce...
0.4917
0.064447
import socket import struct import crcmod # ## Public constant # This is a somewhat arbitrary value MAX_RESPONSE_BYTES = 16384 # Set up CRC32c algorithm _CASTAGNOLI = 0x11EDC6F41 # From kivaloo/INTERFACES _ILONGATSAC = 0x82f63b78 # Bit-reversed CASTAGNOLI polynomial _CRC_FUNC = crcmod.mkCrcFun(_CASTAGNOLI, i...
tests/python/kivaloo/wire.py
import socket import struct import crcmod # ## Public constant # This is a somewhat arbitrary value MAX_RESPONSE_BYTES = 16384 # Set up CRC32c algorithm _CASTAGNOLI = 0x11EDC6F41 # From kivaloo/INTERFACES _ILONGATSAC = 0x82f63b78 # Bit-reversed CASTAGNOLI polynomial _CRC_FUNC = crcmod.mkCrcFun(_CASTAGNOLI, i...
0.693161
0.347067
import sys import os import platform import yaml import requests import bz2 import json import subprocess from pathlib import Path from typing import Tuple # Constants HERE = Path(__file__).resolve().parent REPO_ROOT = HERE.parent ROOT = REPO_ROOT.parent MATRIX_FPATH = ROOT / "maxiconda-envs/specs/matrix.yaml" PRIMARY...
scripts/solve.py
import sys import os import platform import yaml import requests import bz2 import json import subprocess from pathlib import Path from typing import Tuple # Constants HERE = Path(__file__).resolve().parent REPO_ROOT = HERE.parent ROOT = REPO_ROOT.parent MATRIX_FPATH = ROOT / "maxiconda-envs/specs/matrix.yaml" PRIMARY...
0.437583
0.147095
# My imports from lhvqt.lvqt_real import LVQT as LVQT_R from lhvqt import LHVQT from compare_utils import * # Regular imports from time import time import numpy as np import librosa import torch def main(): """ Compare the real variant with different max pooling settings to librosa HVQT. """ # S...
examples/pooling_real.py
# My imports from lhvqt.lvqt_real import LVQT as LVQT_R from lhvqt import LHVQT from compare_utils import * # Regular imports from time import time import numpy as np import librosa import torch def main(): """ Compare the real variant with different max pooling settings to librosa HVQT. """ # S...
0.871489
0.30474
from time import sleep from argparse import ArgumentParser from temscript import Microscope, NullMicroscope, RemoteMicroscope parser = ArgumentParser() parser.add_argument("--null", action='store_true', default=False, help="Use NullMicroscope") parser.add_argument("--remote", type=str, default='', help="Use RemoteMi...
scripts/test_microscope.py
from time import sleep from argparse import ArgumentParser from temscript import Microscope, NullMicroscope, RemoteMicroscope parser = ArgumentParser() parser.add_argument("--null", action='store_true', default=False, help="Use NullMicroscope") parser.add_argument("--remote", type=str, default='', help="Use RemoteMi...
0.341802
0.111024
from pyrsistent import pmap class ConfusionTable(object): def __init__(self, class_name, true_positive, true_negative, false_positive, false_negative, format_fn): self.__class_name = class_name self.__true_positive = true_positive self.__true_negative = true_negative ...
modules/confusion_table/src/_confusion_table.py
from pyrsistent import pmap class ConfusionTable(object): def __init__(self, class_name, true_positive, true_negative, false_positive, false_negative, format_fn): self.__class_name = class_name self.__true_positive = true_positive self.__true_negative = true_negative ...
0.898087
0.203529
# pylint: disable=too-many-arguments from collections import OrderedDict import json from enum import Enum from azure.cli.core._util import CLIError class ArmTemplateBuilder(object): def __init__(self): template = OrderedDict() template['$schema'] = \ 'https://schema.management.az...
src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/_template_builder.py
# pylint: disable=too-many-arguments from collections import OrderedDict import json from enum import Enum from azure.cli.core._util import CLIError class ArmTemplateBuilder(object): def __init__(self): template = OrderedDict() template['$schema'] = \ 'https://schema.management.az...
0.689306
0.094093
import numpy as np import pandas as pd from scipy import ndimage from . import readTrodesExtractedDataFile3 as read_trodes def get_trodes_files(data_dir, trodes_name): """Generate names of all the trodes files from a calibration recording. Assumes data is saved in the default trodes filesystem and channels ar...
software/preprocessing/trodes_data/calibration_data_parser.py
import numpy as np import pandas as pd from scipy import ndimage from . import readTrodesExtractedDataFile3 as read_trodes def get_trodes_files(data_dir, trodes_name): """Generate names of all the trodes files from a calibration recording. Assumes data is saved in the default trodes filesystem and channels ar...
0.821044
0.433562
from binascii import crc32 from nydus.contrib.ketama import Ketama from nydus.db.routers import BaseRouter, RoundRobinRouter, routing_params from nydus import compat __all__ = ('ConsistentHashingRouter', 'PartitionRouter') def get_key(args, kwargs): if 'key' in kwargs: return kwargs['key'] elif args...
nydus/db/routers/keyvalue.py
from binascii import crc32 from nydus.contrib.ketama import Ketama from nydus.db.routers import BaseRouter, RoundRobinRouter, routing_params from nydus import compat __all__ = ('ConsistentHashingRouter', 'PartitionRouter') def get_key(args, kwargs): if 'key' in kwargs: return kwargs['key'] elif args...
0.680879
0.195095
import tkinter as tk import events as event import jwt import constants from tkinter import messagebox def create_menu(root, canvas): Login_with_password = tk.Button(text='Login with password', width=20, command=lambda : \ event.login_event_...
screens.py
import tkinter as tk import events as event import jwt import constants from tkinter import messagebox def create_menu(root, canvas): Login_with_password = tk.Button(text='Login with password', width=20, command=lambda : \ event.login_event_...
0.352982
0.167321
from transformers import pipeline def input_extraction(task): """Function that gets from the user the desired input that will be sent to the model and extracts relevant information.""" print("="*100) context = input("\nPlease provide the case facts (subject name, individual or entity, residence, permanent...
articles/residence.py
from transformers import pipeline def input_extraction(task): """Function that gets from the user the desired input that will be sent to the model and extracts relevant information.""" print("="*100) context = input("\nPlease provide the case facts (subject name, individual or entity, residence, permanent...
0.446857
0.470615
import tkinter as tk import numpy as np import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import parser import re # Importing mathematical functions and constants individually for UX from numpy import sin, cos, tan, arcsin, arccos, arctan, log as ln, log10 as log, e, pi #...
RS-GCalc.py
import tkinter as tk import numpy as np import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import parser import re # Importing mathematical functions and constants individually for UX from numpy import sin, cos, tan, arcsin, arccos, arctan, log as ln, log10 as log, e, pi #...
0.608594
0.371194
QB_CT = 0.55 WB_CT = 0.19 EB_CT = 0.4 RB_CT = 0.44 TB_CT = 0.39 CT_LT = {'q':QB_CT, 'w':WB_CT, 'e':EB_CT, 'r':RB_CT, 't':TB_CT} #Movement Map constants MM_ISOP = 0.7 #Percantage of nearby closed cells for a cell to be considered isolated MM_NSP = 16 #Number of points to sample getting nearby points #Health and ma...
Const.py
QB_CT = 0.55 WB_CT = 0.19 EB_CT = 0.4 RB_CT = 0.44 TB_CT = 0.39 CT_LT = {'q':QB_CT, 'w':WB_CT, 'e':EB_CT, 'r':RB_CT, 't':TB_CT} #Movement Map constants MM_ISOP = 0.7 #Percantage of nearby closed cells for a cell to be considered isolated MM_NSP = 16 #Number of points to sample getting nearby points #Health and ma...
0.387459
0.523359
import urllib.request as request from datetime import datetime as dt import datetime from subprocess import call import os from glob import glob import numpy as np import xarray as xr def fetch(strtDT,endDT,saveDir): """ Download and unzip MRMS files from the Iowa State data archive between a given start ...
retrieveMRMS.py
import urllib.request as request from datetime import datetime as dt import datetime from subprocess import call import os from glob import glob import numpy as np import xarray as xr def fetch(strtDT,endDT,saveDir): """ Download and unzip MRMS files from the Iowa State data archive between a given start ...
0.550124
0.36886
class ResultCodes: Client = { 0 : 'Success, the operation succeeded, however, the client entry is untrusted', 1 : 'SuccessButUntrusted', 2 : 'ArgumentInvalidValue', 3 : 'ArgumentUnsupportedDerivingClass', 4 : 'ArgumentIsEmpty', 5 : 'ArgumentIsNull', 6 : 'BadAu...
pytpp/properties/resultcodes.py
class ResultCodes: Client = { 0 : 'Success, the operation succeeded, however, the client entry is untrusted', 1 : 'SuccessButUntrusted', 2 : 'ArgumentInvalidValue', 3 : 'ArgumentUnsupportedDerivingClass', 4 : 'ArgumentIsEmpty', 5 : 'ArgumentIsNull', 6 : 'BadAu...
0.665845
0.266184
from openerp import models, api, _, fields, SUPERUSER_ID from openerp.exceptions import Warning as UserError def get_last_value(self, ids, model=None, field=None, fieldtype=None): """Return the last value of a record in the model to show a post with the change @param ids: int with id record @param mo...
message_post_model/model/message_post.py
from openerp import models, api, _, fields, SUPERUSER_ID from openerp.exceptions import Warning as UserError def get_last_value(self, ids, model=None, field=None, fieldtype=None): """Return the last value of a record in the model to show a post with the change @param ids: int with id record @param mo...
0.704872
0.390185
import argparse from datetime import datetime import logging import os import shutil import subprocess import sys import coloredlogs import git import numpy as np _logger = logging.getLogger() def print_info(opt, log_dir=None): """ Logs source code configuration """ _logger.info('Command: {}'.format(' ...
src/common/misc.py
import argparse from datetime import datetime import logging import os import shutil import subprocess import sys import coloredlogs import git import numpy as np _logger = logging.getLogger() def print_info(opt, log_dir=None): """ Logs source code configuration """ _logger.info('Command: {}'.format(' ...
0.368747
0.116186
import os import h5py import pandas as pd import numpy as np import torchvision.transforms as transforms import torch from torch.utils.data import Dataset from .word_utils import Corpus from PIL import Image import torch.nn.functional as F from collections import Iterable from torch.autograd import Variable class R...
datasets/a2d_dataset.py
import os import h5py import pandas as pd import numpy as np import torchvision.transforms as transforms import torch from torch.utils.data import Dataset from .word_utils import Corpus from PIL import Image import torch.nn.functional as F from collections import Iterable from torch.autograd import Variable class R...
0.75101
0.335378
from __future__ import annotations import json import typing as t from ..tools.enums import ResponseType from ..objects import UlistLabels try: import orjson # type: ignore ORJ = True except ModuleNotFoundError: ORJ = False if t.TYPE_CHECKING: from ..interface import Interface __all__ = ("TERM...
azaka/commands/command.py
from __future__ import annotations import json import typing as t from ..tools.enums import ResponseType from ..objects import UlistLabels try: import orjson # type: ignore ORJ = True except ModuleNotFoundError: ORJ = False if t.TYPE_CHECKING: from ..interface import Interface __all__ = ("TERM...
0.816845
0.179207
import re from typing import Any, Dict, Iterable, List, Optional, Union from ansiscape import bright_green, heavy, italic from ansiscape.checks import should_emit_codes from asking.actions.action import Action, ActionResult from asking.exceptions import AskingError, NothingToDoError from asking.prompts import get_pro...
asking/actions/ask.py
import re from typing import Any, Dict, Iterable, List, Optional, Union from ansiscape import bright_green, heavy, italic from ansiscape.checks import should_emit_codes from asking.actions.action import Action, ActionResult from asking.exceptions import AskingError, NothingToDoError from asking.prompts import get_pro...
0.850096
0.20949
import json import os import platform import attr import click import subprocess32 as subprocess from kross.utils import echo, get_std @attr.s class Builder(object): def init(self): echo("Initializing kross. You may be prompted for sudo password") self.check_builder() sel...
kross/builder.py
import json import os import platform import attr import click import subprocess32 as subprocess from kross.utils import echo, get_std @attr.s class Builder(object): def init(self): echo("Initializing kross. You may be prompted for sudo password") self.check_builder() sel...
0.189559
0.044932
import paho.mqtt.client as mqtt from powermate import Powermate, PowermateDelegate import time import json # Change the following line to include the Bluetooth address of your Powermate Bluetooth # To find the address, run: sudo hcitool lescan POwERMATE_ADDRESS = '00:12:92:08:2B:59' class PrintEvents(PowermateDelega...
powermate2mqtt.py
import paho.mqtt.client as mqtt from powermate import Powermate, PowermateDelegate import time import json # Change the following line to include the Bluetooth address of your Powermate Bluetooth # To find the address, run: sudo hcitool lescan POwERMATE_ADDRESS = '00:12:92:08:2B:59' class PrintEvents(PowermateDelega...
0.343562
0.085289
import xlrd import os import traceback def open_excel(file): try: data = xlrd.open_workbook(file) return data except Exception as e: print(str(e)) def excel_table_byname(file, colnameindex=0, by_name="Sheet1"): # 获取Excel表格名单 data = open_excel(file) table = data.sheet_by_nam...
Src/pyHelper.py
import xlrd import os import traceback def open_excel(file): try: data = xlrd.open_workbook(file) return data except Exception as e: print(str(e)) def excel_table_byname(file, colnameindex=0, by_name="Sheet1"): # 获取Excel表格名单 data = open_excel(file) table = data.sheet_by_nam...
0.064307
0.139426
# This script builds the SWIG source tarball, creates the Windows executable and the Windows zip package # and uploads them both to SF ready for release. Also uploaded are the release notes. import sys import string import os def failed(message): if message == "": print "mkrelease.py failed to complete" else:...
swig-2.0.4/Tools/mkrelease.py
# This script builds the SWIG source tarball, creates the Windows executable and the Windows zip package # and uploads them both to SF ready for release. Also uploaded are the release notes. import sys import string import os def failed(message): if message == "": print "mkrelease.py failed to complete" else:...
0.240507
0.068756
import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func import datetime as dt import numpy as np from flask import Flask, jsonify # Connecting the sqlite file to climateapp.py engine = create_engine("sqlite:///Resources/hawaii.sqli...
climateapp.py
import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func import datetime as dt import numpy as np from flask import Flask, jsonify # Connecting the sqlite file to climateapp.py engine = create_engine("sqlite:///Resources/hawaii.sqli...
0.393385
0.167083
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = ['PolicyAttachmentArgs', 'PolicyAttachment'] @pulumi.input_type class PolicyAttachmentArgs: def __init__(__self__, *, policy_name: pulumi.I...
sdk/python/pulumi_alicloud/resourcemanager/policy_attachment.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = ['PolicyAttachmentArgs', 'PolicyAttachment'] @pulumi.input_type class PolicyAttachmentArgs: def __init__(__self__, *, policy_name: pulumi.I...
0.853516
0.129926
import pytest import os from connect.client import ConnectClient, ClientError from connect.devops_testing import asserts from connect.processors_toolkit.requests.tier_configurations import TierConfigurationBuilder from connect.processors_toolkit.requests import RequestBuilder from connect.processors_toolkit.api.mixi...
tests/api/test_mixin_with_tier_configuration_helper.py
import pytest import os from connect.client import ConnectClient, ClientError from connect.devops_testing import asserts from connect.processors_toolkit.requests.tier_configurations import TierConfigurationBuilder from connect.processors_toolkit.requests import RequestBuilder from connect.processors_toolkit.api.mixi...
0.537041
0.104935
import os from datetime import datetime import time from optparse import OptionParser import cli_client # get command line arguments parser = OptionParser() parser.add_option("-d", "--databases", dest="databases", help="List of databases to backup") parser.add_option("-u", "--username", dest="username", help="MySQL us...
backup_and_upload.py
import os from datetime import datetime import time from optparse import OptionParser import cli_client # get command line arguments parser = OptionParser() parser.add_option("-d", "--databases", dest="databases", help="List of databases to backup") parser.add_option("-u", "--username", dest="username", help="MySQL us...
0.211824
0.11004
import os import io import re import sys import subprocess from threading import Thread # compatibility with python 2/3 try: from queue import Queue, Empty # python 3 unicode = str except ImportError: from Queue import Queue, Empty # python 2 class ProcessExecution(object): """ Executes a proces...
src/lib/kombi/ProcessExecution.py
import os import io import re import sys import subprocess from threading import Thread # compatibility with python 2/3 try: from queue import Queue, Empty # python 3 unicode = str except ImportError: from Queue import Queue, Empty # python 2 class ProcessExecution(object): """ Executes a proces...
0.494873
0.152537
import argparse import boto3 import pandas as pd import nltk import sagemaker import json from sagemaker.deserializers import JSONDeserializer from sagemaker.serializers import JSONSerializer from pathlib import Path def nest_sentences(document): nested = [] sent = [] length = 0 for sentence in nlt...
end_to_end/nlp_mlops_company_sentiment/scripts/summarize.py
import argparse import boto3 import pandas as pd import nltk import sagemaker import json from sagemaker.deserializers import JSONDeserializer from sagemaker.serializers import JSONSerializer from pathlib import Path def nest_sentences(document): nested = [] sent = [] length = 0 for sentence in nlt...
0.301054
0.118029
import os import functools as fun import itertools as it import collections as coll import re import numpy as np from scipy import ndimage as nd from skimage import io from scipy.stats.mstats import mquantiles as quantiles from skimage import morphology as skmorph, filter as imfilter import skimage.filter.rank as rank ...
husc/preprocess.py
import os import functools as fun import itertools as it import collections as coll import re import numpy as np from scipy import ndimage as nd from skimage import io from scipy.stats.mstats import mquantiles as quantiles from skimage import morphology as skmorph, filter as imfilter import skimage.filter.rank as rank ...
0.888033
0.444927
import numbers import itertools import numpy as np import typing as T from operator import attrgetter as attr from sqsgenerator.core.core import Structure as Structure_, Atom class Structure(Structure_): """ Structure class used to store structural information. This class is used by the core extension and is ...
sqsgenerator/core/structure.py
import numbers import itertools import numpy as np import typing as T from operator import attrgetter as attr from sqsgenerator.core.core import Structure as Structure_, Atom class Structure(Structure_): """ Structure class used to store structural information. This class is used by the core extension and is ...
0.87312
0.531209
import sys import struct import shlex import subprocess import re from bluepy.btle import * from bluetooth.ble import * import serial import requests host = { "ip": "172.16.17.32", "port": 50000, "endpoint": "values" } def get_vals(host): r = requests.get("http://{}:{}/users".format(host["ip"], host[...
scale/scale.py
import sys import struct import shlex import subprocess import re from bluepy.btle import * from bluetooth.ble import * import serial import requests host = { "ip": "172.16.17.32", "port": 50000, "endpoint": "values" } def get_vals(host): r = requests.get("http://{}:{}/users".format(host["ip"], host[...
0.102265
0.168309
from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django_summernote_ajax import settings as django_summernote_ajax_settings from . import settings as sandbox_app_settin...
sandbox_app/forms.py
from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django_summernote_ajax import settings as django_summernote_ajax_settings from . import settings as sandbox_app_settin...
0.522933
0.088978
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.impo...
pysnmp/ZXR10-SMI.py
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.impo...
0.356895
0.108566
from yaferp.orderings import directOrdering from yaferp.analysis import analyser import cPickle import os import datetime DATA_DIR = '/home/andrew/workspace/BKData/' INTEGRALS_DIR = DATA_DIR + 'integrals/' OPLIST_DIR = DATA_DIR + 'hamiltonian/oplist/' OPLIST_JW_DIR = DATA_DIR + 'hamiltonian/oplist/JW/' OPLIST_BK_DIR = ...
misc/legacy/fermions/yaferp/analysis/analyserOrdering.py
from yaferp.orderings import directOrdering from yaferp.analysis import analyser import cPickle import os import datetime DATA_DIR = '/home/andrew/workspace/BKData/' INTEGRALS_DIR = DATA_DIR + 'integrals/' OPLIST_DIR = DATA_DIR + 'hamiltonian/oplist/' OPLIST_JW_DIR = DATA_DIR + 'hamiltonian/oplist/JW/' OPLIST_BK_DIR = ...
0.221856
0.16228
import numpy as np import cv2 try: xrange except NameError: xrange = range class PatchGenerator: def __init__(self,stepsize, imsize, winsize=None): self.stepsize = stepsize self.imsize = imsize if len(self.imsize)==2: self.imsize=(imsize[0],imsize[1],1) if wins...
number13/number13/src/patchify.py
import numpy as np import cv2 try: xrange except NameError: xrange = range class PatchGenerator: def __init__(self,stepsize, imsize, winsize=None): self.stepsize = stepsize self.imsize = imsize if len(self.imsize)==2: self.imsize=(imsize[0],imsize[1],1) if wins...
0.165796
0.606091