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
# imports import PySide.QtCore as __PySide_QtCore import Shiboken as __Shiboken class QSystemTrayIcon(__PySide_QtCore.QObject): # no doc def activated(self, *args, **kwargs): # real signature unknown """ Signal """ pass def contextMenu(self, *args, **kwargs): # real signature unknown ...
resources/dot_PyCharm/system/python_stubs/-762174762/PySide/QtGui/QSystemTrayIcon.py
# imports import PySide.QtCore as __PySide_QtCore import Shiboken as __Shiboken class QSystemTrayIcon(__PySide_QtCore.QObject): # no doc def activated(self, *args, **kwargs): # real signature unknown """ Signal """ pass def contextMenu(self, *args, **kwargs): # real signature unknown ...
0.584745
0.067301
from .endpoint import Endpoint, api from .exceptions import JobCancelledException, JobFailedException from .. import JobItem, BackgroundJobItem, PaginationItem from ..request_options import RequestOptionsBase from ...exponential_backoff import ExponentialBackoffTimer import logging logger = logging.getLogger("tableau...
tableauserverclient/server/endpoint/jobs_endpoint.py
from .endpoint import Endpoint, api from .exceptions import JobCancelledException, JobFailedException from .. import JobItem, BackgroundJobItem, PaginationItem from ..request_options import RequestOptionsBase from ...exponential_backoff import ExponentialBackoffTimer import logging logger = logging.getLogger("tableau...
0.585575
0.098642
from __future__ import print_function from array import array from operator import xor __author__ = 'inmcm' class SkinnyCipher: # Sbox Constants sbox4 = array('B', [12, 6, 9, 0, 1, 10, 2, 11, 3, 8, 5, 13, 4, 14, 7, 15]) sbox4_inv = array('B', [3, 4, 6, 8, 12, 10, 1, 14, 9, 2, 5, 7, 0, 11, 13, 15]) ...
Python/skinny.py
from __future__ import print_function from array import array from operator import xor __author__ = 'inmcm' class SkinnyCipher: # Sbox Constants sbox4 = array('B', [12, 6, 9, 0, 1, 10, 2, 11, 3, 8, 5, 13, 4, 14, 7, 15]) sbox4_inv = array('B', [3, 4, 6, 8, 12, 10, 1, 14, 9, 2, 5, 7, 0, 11, 13, 15]) ...
0.186947
0.44089
import numpy as np import mne from itertools import product from mne.datasets import eegbci from mne.io import concatenate_raws, read_raw_edf from joblib import Parallel, delayed, Memory from picard import picard from smica import dipolarity, JDIAG_mne, SOBI_mne, ICA location = './cachedir' memory = Memory(location,...
experiment_eeg_data.py
import numpy as np import mne from itertools import product from mne.datasets import eegbci from mne.io import concatenate_raws, read_raw_edf from joblib import Parallel, delayed, Memory from picard import picard from smica import dipolarity, JDIAG_mne, SOBI_mne, ICA location = './cachedir' memory = Memory(location,...
0.427397
0.337667
import threading import unittest import time import rostest import rospy from araig_msgs.msg import BoolStamped class TestEdgeTrigger(unittest.TestCase): def setUp(self): _pub_topic_1 = '/out_bool' _sub_topic_high = '/in_high' _sub_topic_low = '/in_low' rospy.init_node('test_edge...
araig_calculators/tests/node_tests/test_edge_detector_node.py
import threading import unittest import time import rostest import rospy from araig_msgs.msg import BoolStamped class TestEdgeTrigger(unittest.TestCase): def setUp(self): _pub_topic_1 = '/out_bool' _sub_topic_high = '/in_high' _sub_topic_low = '/in_low' rospy.init_node('test_edge...
0.403567
0.230194
import argparse from distutils.util import strtobool from torch.utils.tensorboard import SummaryWriter from tensorboard_logger import TensorboardLogger from trainer import Trainer def main(opt): # tensorboardに出力するためのwriterを作成 TensorboardLogger.writer = SummaryWriter(log_dir=opt.tensorboard_path) # Traine...
chapter7/stylegan2_pytorch/training.py
import argparse from distutils.util import strtobool from torch.utils.tensorboard import SummaryWriter from tensorboard_logger import TensorboardLogger from trainer import Trainer def main(opt): # tensorboardに出力するためのwriterを作成 TensorboardLogger.writer = SummaryWriter(log_dir=opt.tensorboard_path) # Traine...
0.549641
0.222679
import unittest import matplotlib.pyplot as plt from unittest.mock import patch from click.testing import CliRunner from nseta.cli.plotscli import plot_ta import nseta.common.urls as urls from baseUnitTest import baseUnitTest class TestStrategycli(baseUnitTest): def setUp(self, redirect_logs=True): super().set...
tests/test_plotscli.py
import unittest import matplotlib.pyplot as plt from unittest.mock import patch from click.testing import CliRunner from nseta.cli.plotscli import plot_ta import nseta.common.urls as urls from baseUnitTest import baseUnitTest class TestStrategycli(baseUnitTest): def setUp(self, redirect_logs=True): super().set...
0.55929
0.619644
import pandas as pd class ResultCalculator: def __init__(self,last_unit, cgpa, course_title, course_codes, units, grades): self.course_info = {} self.a,self.b,self.c,self.d,self.f = 5,4,3,1,0 self.course_title = course_title self.courses = course_codes self.units = units...
resultCal.py
import pandas as pd class ResultCalculator: def __init__(self,last_unit, cgpa, course_title, course_codes, units, grades): self.course_info = {} self.a,self.b,self.c,self.d,self.f = 5,4,3,1,0 self.course_title = course_title self.courses = course_codes self.units = units...
0.208179
0.270664
from __future__ import print_function import sys def loadPcbLines(filename): with open(filename,'r') as f: lineList = f.readlines() return lineList def savePcbLines(lineList,filename): with open(filename,'w') as f: for line in lineList: f.write(line) def loadRefToPosFile(file...
arena_12-18_v0/scripts/set_module_pos.py
from __future__ import print_function import sys def loadPcbLines(filename): with open(filename,'r') as f: lineList = f.readlines() return lineList def savePcbLines(lineList,filename): with open(filename,'w') as f: for line in lineList: f.write(line) def loadRefToPosFile(file...
0.400984
0.326017
import numpy as np import tkinter as tk from tkinter import * from scipy import signal import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure import matplotlib.pyplot as plt import os # Graphical interface class SigGen(tk.Tk): ...
main.py
import numpy as np import tkinter as tk from tkinter import * from scipy import signal import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure import matplotlib.pyplot as plt import os # Graphical interface class SigGen(tk.Tk): ...
0.488283
0.308047
import os.path as osp import mmcv import numpy as np from ..builder import HOI_PIPELINES try: from panopticapi.utils import rgb2id except ImportError: rgb2id = None @HOI_PIPELINES.register_module() class LoadImageFromFile: """Load an image from file. Required keys are "img_prefix" and "img_info" (...
mmhoidet/datasets/pipelines/loading.py
import os.path as osp import mmcv import numpy as np from ..builder import HOI_PIPELINES try: from panopticapi.utils import rgb2id except ImportError: rgb2id = None @HOI_PIPELINES.register_module() class LoadImageFromFile: """Load an image from file. Required keys are "img_prefix" and "img_info" (...
0.787605
0.276886
from abc import abstractmethod from operator import attrgetter import itertools from ..util import ABCObject, FillMissingNotEqual class PMPackageMatcher(ABCObject): """ Base class for a package matcher. Package matcher is basically a function (or function class wrapper) which checks the package for match. """ ...
gentoopm/basepm/filter.py
from abc import abstractmethod from operator import attrgetter import itertools from ..util import ABCObject, FillMissingNotEqual class PMPackageMatcher(ABCObject): """ Base class for a package matcher. Package matcher is basically a function (or function class wrapper) which checks the package for match. """ ...
0.746693
0.328153
from typing import Union, Any, Optional from collections import abc import graphql from jessiql import QueryObjectDict, QueryObject from .query_object_argument import get_query_argument_name_for from .selection import collect_fields from .query_field import QueryFieldFunc, QueryFieldInfo, query_every_field def que...
jessiql/integration/graphql/query_object.py
from typing import Union, Any, Optional from collections import abc import graphql from jessiql import QueryObjectDict, QueryObject from .query_object_argument import get_query_argument_name_for from .selection import collect_fields from .query_field import QueryFieldFunc, QueryFieldInfo, query_every_field def que...
0.935043
0.437223
from __future__ import ( absolute_import, division, print_function, unicode_literals) import savalidation.validators as val from pprint import pprint from datetime import datetime as dt, date as d from app import db from savalidation import ValidationMixin from flask_sqlalchemy import SQLAlchemy from sqlalchem...
app/models/cronus.py
from __future__ import ( absolute_import, division, print_function, unicode_literals) import savalidation.validators as val from pprint import pprint from datetime import datetime as dt, date as d from app import db from savalidation import ValidationMixin from flask_sqlalchemy import SQLAlchemy from sqlalchem...
0.583678
0.058265
import pandas as pd import numpy as np import itertools import warnings from models.ARIMA import arima from statsmodels.tsa.stattools import adfuller from sklearn import metrics warnings.filterwarnings('ignore') def read_data(filename): """ Read the csv file and create dataframe """ df = pd.read_csv(...
data_loading.py
import pandas as pd import numpy as np import itertools import warnings from models.ARIMA import arima from statsmodels.tsa.stattools import adfuller from sklearn import metrics warnings.filterwarnings('ignore') def read_data(filename): """ Read the csv file and create dataframe """ df = pd.read_csv(...
0.383872
0.432183
from jinja2 import Template import re import madflow.custom_op.constants as op_co import madflow.custom_op.classes as op_cl import madflow.custom_op.generation as op_gen import madflow.custom_op.global_constants as op_gc def template_with_string(template_string, variable): template = Template(template_string) ...
python_package/madflow/custom_op/write_templates.py
from jinja2 import Template import re import madflow.custom_op.constants as op_co import madflow.custom_op.classes as op_cl import madflow.custom_op.generation as op_gen import madflow.custom_op.global_constants as op_gc def template_with_string(template_string, variable): template = Template(template_string) ...
0.419648
0.310995
from pykinect_azure.k4a import _k4a class Configuration: def __init__(self, configuration_handle=None): if configuration_handle: self._handle = configuration_handle else: self.create() def handle(self): return self._handle def __setattr__(self, name, value): """Run on change function when configu...
pykinect_azure/k4a/configuration.py
from pykinect_azure.k4a import _k4a class Configuration: def __init__(self, configuration_handle=None): if configuration_handle: self._handle = configuration_handle else: self.create() def handle(self): return self._handle def __setattr__(self, name, value): """Run on change function when configu...
0.525369
0.288506
from event import Event from mouseevent import MouseEvent class TouchEvent(MouseEvent): TOUCH_BEGIN = "touchBegin" TOUCH_END = "touchEnd" TOUCH_MOVE = "touchMove" TOUCH_OUT = "touchOut" TOUCH_OVER = "touchOver" TOUCH_ROLL_OUT = "touchRollOut" TOUCH_R...
flappy/events/touchevent.py
from event import Event from mouseevent import MouseEvent class TouchEvent(MouseEvent): TOUCH_BEGIN = "touchBegin" TOUCH_END = "touchEnd" TOUCH_MOVE = "touchMove" TOUCH_OUT = "touchOut" TOUCH_OVER = "touchOver" TOUCH_ROLL_OUT = "touchRollOut" TOUCH_R...
0.494385
0.094636
import numba as nb import numpy as np from numpy import int32, float64 @nb.njit(fastmath=True) def csr_to_coo(data, indices, indptr): row = np.empty(len(data), dtype=int32) col = np.empty(len(data), dtype=int32) nz = 0 for i in range(len(indptr) - 1): for c in range(indptr[i], indptr[i+1]): ...
fastse/performance.py
import numba as nb import numpy as np from numpy import int32, float64 @nb.njit(fastmath=True) def csr_to_coo(data, indices, indptr): row = np.empty(len(data), dtype=int32) col = np.empty(len(data), dtype=int32) nz = 0 for i in range(len(indptr) - 1): for c in range(indptr[i], indptr[i+1]): ...
0.518546
0.543711
import numpy as np from tqdm import tqdm from .candidate import Candidate from .double_metaphone import dm from .edit_distance import edits_n, damerau_levenshtein_distance from .vocab import Vocab class CandidatesGenerator(Vocab): """ Vocab provides dictionary to query lexicon data as strings as well as toke...
scripts/non_trainable/candidates_generation.py
import numpy as np from tqdm import tqdm from .candidate import Candidate from .double_metaphone import dm from .edit_distance import edits_n, damerau_levenshtein_distance from .vocab import Vocab class CandidatesGenerator(Vocab): """ Vocab provides dictionary to query lexicon data as strings as well as toke...
0.592667
0.241109
import unittest import numpy as np from btb import HyperParameter, ParamTypes from btb.tuning.gcp import GCP, GCPEi, GCPEiVelocity from btb.tuning.gp import GP, GPEi, GPEiVelocity from btb.tuning.tuner import BaseTuner from btb.tuning.uniform import Uniform class TestTuner(unittest.TestCase): def setUp(self): ...
tests/btb/tuning/test_tuner_old.py
import unittest import numpy as np from btb import HyperParameter, ParamTypes from btb.tuning.gcp import GCP, GCPEi, GCPEiVelocity from btb.tuning.gp import GP, GPEi, GPEiVelocity from btb.tuning.tuner import BaseTuner from btb.tuning.uniform import Uniform class TestTuner(unittest.TestCase): def setUp(self): ...
0.550366
0.630742
"""fabric tensors in Mandel6 notation """ import numpy as np import mechkit class Basic(object): r""" Fabric tensors of the first kind ([Kanatani1984]_) for special cases - iso - planar_iso_xy - planar_iso_xz - planar_iso_yz - ud_x - ud_y - ud_z .. rubric:: References .....
mechkit/fabric_tensors.py
"""fabric tensors in Mandel6 notation """ import numpy as np import mechkit class Basic(object): r""" Fabric tensors of the first kind ([Kanatani1984]_) for special cases - iso - planar_iso_xy - planar_iso_xz - planar_iso_yz - ud_x - ud_y - ud_z .. rubric:: References .....
0.769687
0.524943
import json from odoo import http, tests from odoo.tools import mute_logger @tests.tagged('post_install', '-at_install') class TestUi(tests.HttpCase): @mute_logger('odoo.addons.http_routing.models.ir_http', 'odoo.http') def test_01_portal_attachment(self): """Test the portal chatter attachment rout...
odoo-13.0/addons/account/tests/test_portal_attachment.py
import json from odoo import http, tests from odoo.tools import mute_logger @tests.tagged('post_install', '-at_install') class TestUi(tests.HttpCase): @mute_logger('odoo.addons.http_routing.models.ir_http', 'odoo.http') def test_01_portal_attachment(self): """Test the portal chatter attachment rout...
0.522933
0.166913
import random from .. import utils from . import Document, const, Element class CommentsBookDocument(Document): """ `CommentsBookDocument` as central object correspond XMind comment file. such as: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <comments version="2.0" xmlns="urn:xmind:xmap:xm...
clitool/utils/xmind_sdk/core/comments.py
import random from .. import utils from . import Document, const, Element class CommentsBookDocument(Document): """ `CommentsBookDocument` as central object correspond XMind comment file. such as: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <comments version="2.0" xmlns="urn:xmind:xmap:xm...
0.586878
0.161849
from pubnub import Pubnub as PubnubNetwork import sys import urllib2 """ {"response_channel":"client","request":{"url":"http://a.pubnub.com/time/0"}} """ ## -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ## Get Args ## -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=...
server/server.py
from pubnub import Pubnub as PubnubNetwork import sys import urllib2 """ {"response_channel":"client","request":{"url":"http://a.pubnub.com/time/0"}} """ ## -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ## Get Args ## -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=...
0.195402
0.042483
import numpy as np import cv2 import glob import matplotlib.pyplot as plt from Line import Line class Camera(): def __init__(self): self.M = None self.M_inv = None self.img_size = None self.ret = None self.mtx = None self.dist = None self.rvecs = Non...
Camera.py
import numpy as np import cv2 import glob import matplotlib.pyplot as plt from Line import Line class Camera(): def __init__(self): self.M = None self.M_inv = None self.img_size = None self.ret = None self.mtx = None self.dist = None self.rvecs = Non...
0.596903
0.396769
import io import os import shutil import argparse from pkg_resources import resource_filename, resource_string from serene_metadata import DEFINED_FIELDS_DICT def gen_patch(lines): data = [ '212,{}d188'.format(212 + len(lines) - 1) ] data.extend( map( lambda _:u'< {}'.f...
serene_solr_config/serene_solr_config/main.py
import io import os import shutil import argparse from pkg_resources import resource_filename, resource_string from serene_metadata import DEFINED_FIELDS_DICT def gen_patch(lines): data = [ '212,{}d188'.format(212 + len(lines) - 1) ] data.extend( map( lambda _:u'< {}'.f...
0.271348
0.078926
import cv2 import numpy as np import face_recognition import os from datetime import datetime path = 'attendence_images' images = [] classNames = [] myList = os.listdir(path) for cls in myList: curImg = cv2.imread(f'{path}/{cls}') images.append(curImg) classNames.append(os.path.splitext(cls)[0]) print(classNames)...
AttendenceProject.py
import cv2 import numpy as np import face_recognition import os from datetime import datetime path = 'attendence_images' images = [] classNames = [] myList = os.listdir(path) for cls in myList: curImg = cv2.imread(f'{path}/{cls}') images.append(curImg) classNames.append(os.path.splitext(cls)[0]) print(classNames)...
0.177704
0.197039
import datetime from ddt import ddt from mock import Mock, MagicMock, call, ANY from tests import TestCase, ReadContentMixin from sqlalchemy import Column, Integer, ForeignKey, String from monitorrent.utils.bittorrent_ex import Torrent from monitorrent.engine import Engine, EngineExecute, EngineTrackers, EngineTracke...
tests/test_engine_execute.py
import datetime from ddt import ddt from mock import Mock, MagicMock, call, ANY from tests import TestCase, ReadContentMixin from sqlalchemy import Column, Integer, ForeignKey, String from monitorrent.utils.bittorrent_ex import Torrent from monitorrent.engine import Engine, EngineExecute, EngineTrackers, EngineTracke...
0.652906
0.237698
expected_output = { 'version': { 'bootldr_version': 'System Bootstrap, Version 17.1.1r, ' 'RELEASE SOFTWARE (P)', 'chassis': 'C9500-12Q', 'code_name': 'Amsterdam', 'compiled_by': 'mcpre', 'compiled_dat...
src/genie/libs/parser/iosxe/c9500/tests/ShowVersion/cli/equal/golden_output_c9500_2_expected.py
expected_output = { 'version': { 'bootldr_version': 'System Bootstrap, Version 17.1.1r, ' 'RELEASE SOFTWARE (P)', 'chassis': 'C9500-12Q', 'code_name': 'Amsterdam', 'compiled_by': 'mcpre', 'compiled_dat...
0.442155
0.313551
import numpy as np key = "YOUR_YOUTUBE_API_KEY" # replace this key value with Youtube API key arrholo = np.array([ "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<N...
data.py
import numpy as np key = "YOUR_YOUTUBE_API_KEY" # replace this key value with Youtube API key arrholo = np.array([ "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<N...
0.091633
0.049612
import time import logging from django.conf import settings from zipkin import local from zipkin.api import get_current_trace, stack_trace from zipkin.models import Trace, Annotation, Endpoint from zipkin.util import int_or_none from zipkin.client import log as zipkin_log from .apps import ZipkinConfig log = loggi...
zipkin/binding/django/middleware.py
import time import logging from django.conf import settings from zipkin import local from zipkin.api import get_current_trace, stack_trace from zipkin.models import Trace, Annotation, Endpoint from zipkin.util import int_or_none from zipkin.client import log as zipkin_log from .apps import ZipkinConfig log = loggi...
0.324021
0.095814
from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import UserManager from django.db import models from django.urls import reverse_lazy from django.utils.translation import ugettext_lazy from .utils import update_player_racing_stats from trax.utils import get_object_by_string c...
website/players/models.py
from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import UserManager from django.db import models from django.urls import reverse_lazy from django.utils.translation import ugettext_lazy from .utils import update_player_racing_stats from trax.utils import get_object_by_string c...
0.513668
0.083703
class ActionMappings(object): """ Stores the mappings of the input events to game specific actions. """ def __init__(self, name): self.name = name self.mappings = {} # keys are the event names and values the action names def getName(self): ...
src/pano/model/ActionMappings.py
class ActionMappings(object): """ Stores the mappings of the input events to game specific actions. """ def __init__(self, name): self.name = name self.mappings = {} # keys are the event names and values the action names def getName(self): ...
0.817938
0.280233
from server.search.search_result import SearchResult from providers.entities.abstract_entity import AbstractEntity from providers.providers_manager import ProviderManager from providers.abstract_search_provider import AbstractSearchProvider from threading import Thread from providers.entities.genre import Genre from pr...
server/search/search.py
from server.search.search_result import SearchResult from providers.entities.abstract_entity import AbstractEntity from providers.providers_manager import ProviderManager from providers.abstract_search_provider import AbstractSearchProvider from threading import Thread from providers.entities.genre import Genre from pr...
0.735452
0.239939
from transX import TransX import tensorflow as tf import tf_euler class TransE(TransX): def __init__(self, node_type, edge_type, node_max_id, edge_max_id, ent_dim, rel_dim, num_negs=5, margin=1., l1=True, metric_name='mrr', corr...
examples/TransX/transE.py
from transX import TransX import tensorflow as tf import tf_euler class TransE(TransX): def __init__(self, node_type, edge_type, node_max_id, edge_max_id, ent_dim, rel_dim, num_negs=5, margin=1., l1=True, metric_name='mrr', corr...
0.845847
0.201479
import os from datetime import timedelta from decouple import config, Csv from email.utils import getaddresses import secret_django_settings as secrets BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = secrets.SECRET_KEY DEBUG = config('DEBUG', default=False, cast=bool) DJANGO_ENV...
api/simplepasswords_api/settings.py
import os from datetime import timedelta from decouple import config, Csv from email.utils import getaddresses import secret_django_settings as secrets BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = secrets.SECRET_KEY DEBUG = config('DEBUG', default=False, cast=bool) DJANGO_ENV...
0.261142
0.050917
from textblob import TextBlob def get_sentiment_dict(comments): """ creates the sentiment dict. Key is the comment, value is the sentiment polarity. """ s_dict = {} for comment in comments: blob = TextBlob(comment) s_dict[comment] = blob.sentiment.polarity s = [(k, s_dict[k]) fo...
sentiment_analyzer.py
from textblob import TextBlob def get_sentiment_dict(comments): """ creates the sentiment dict. Key is the comment, value is the sentiment polarity. """ s_dict = {} for comment in comments: blob = TextBlob(comment) s_dict[comment] = blob.sentiment.polarity s = [(k, s_dict[k]) fo...
0.521959
0.416144
from spack import * class Cgns(CMakePackage): """The CFD General Notation System (CGNS) provides a general, portable, and extensible standard for the storage and retrieval of computational fluid dynamics (CFD) analysis data.""" homepage = "http://cgns.github.io/" url = "https://github.com/CG...
package/spack-cgns/package.py
from spack import * class Cgns(CMakePackage): """The CFD General Notation System (CGNS) provides a general, portable, and extensible standard for the storage and retrieval of computational fluid dynamics (CFD) analysis data.""" homepage = "http://cgns.github.io/" url = "https://github.com/CG...
0.720565
0.23392
import bs4 as bs import urllib.request import re import nltk import numpy as np import random import string import spacy dados = urllib.request.urlopen('https://tecnoblog.net/263808/o-que-e-inteligencia-artificial/') dados = dados.read() dados_html = bs.BeautifulSoup(dados, 'lxml') paragrafos = dados_html.find_all('p')...
chatbot completo.py
import bs4 as bs import urllib.request import re import nltk import numpy as np import random import string import spacy dados = urllib.request.urlopen('https://tecnoblog.net/263808/o-que-e-inteligencia-artificial/') dados = dados.read() dados_html = bs.BeautifulSoup(dados, 'lxml') paragrafos = dados_html.find_all('p')...
0.117724
0.107742
import argparse, os, h5py, pickle, time import numpy as np from scipy.stats import mode from sklearn.model_selection import StratifiedKFold from mpi4py import MPI from pyuoi import UoI_L1Logistic from pyuoi.mpi_utils import Bcast_from_root from hangul_analysis.variables import label_df, n_blocks exp_names = {'i': ...
hangul_analysis/scripts/vae/vae_logreg_uoi.py
import argparse, os, h5py, pickle, time import numpy as np from scipy.stats import mode from sklearn.model_selection import StratifiedKFold from mpi4py import MPI from pyuoi import UoI_L1Logistic from pyuoi.mpi_utils import Bcast_from_root from hangul_analysis.variables import label_df, n_blocks exp_names = {'i': ...
0.512449
0.247824
from django.conf import settings import json def is_json(storage_field): try: _ = json.loads(storage_field) return True except: return False class UserFieldMixin: """Mixin that adds the necessary data retrieval and storage functions to an object storing data from extra field...
user_fields/mixins.py
from django.conf import settings import json def is_json(storage_field): try: _ = json.loads(storage_field) return True except: return False class UserFieldMixin: """Mixin that adds the necessary data retrieval and storage functions to an object storing data from extra field...
0.584153
0.253266
import os import json import urllib.parse from flask import Flask, request, render_template, abort from linebot import ( LineBotApi, WebhookHandler ) from linebot.exceptions import ( InvalidSignatureError, LineBotApiError, ) from linebot.models import * app = Flask(__name__) # 環境変数読み込み line_channel_acce...
bot.py
import os import json import urllib.parse from flask import Flask, request, render_template, abort from linebot import ( LineBotApi, WebhookHandler ) from linebot.exceptions import ( InvalidSignatureError, LineBotApiError, ) from linebot.models import * app = Flask(__name__) # 環境変数読み込み line_channel_acce...
0.21917
0.093017
import importlib import inspect import os import pathlib import sys from functools import partial from itertools import chain from typing import Generator, Optional, Tuple, Type from xappt.constants import * from xappt.config import log as logger from xappt.models import BaseTool, BaseInterface from xappt.models.plug...
xappt/managers/plugin_manager.py
import importlib import inspect import os import pathlib import sys from functools import partial from itertools import chain from typing import Generator, Optional, Tuple, Type from xappt.constants import * from xappt.config import log as logger from xappt.models import BaseTool, BaseInterface from xappt.models.plug...
0.467089
0.057045
import json from ale.transformation import FrameNode from ale.rotation import ConstantRotation, TimeDependentRotation from ale.encoders import NumpyEncoder def to_isis(driver): """ Formatter to create ISIS sensor model meta data from a driver. Parameters ---------- driver : Driver Concret...
ale/formatters/isis_formatter.py
import json from ale.transformation import FrameNode from ale.rotation import ConstantRotation, TimeDependentRotation from ale.encoders import NumpyEncoder def to_isis(driver): """ Formatter to create ISIS sensor model meta data from a driver. Parameters ---------- driver : Driver Concret...
0.813313
0.356587
from flask_restful import Resource, reqparse from models.hotel import HotelModel hotels = [ { 'hotel_id': 'alpha', 'name': '<NAME>el', 'stars': 4.3, 'daily': 420.34, 'city': 'Rio de Janeiro' }, { 'hotel_id': 'alpha', 'name': '<NAME>el', ...
src/resources/hotel.py
from flask_restful import Resource, reqparse from models.hotel import HotelModel hotels = [ { 'hotel_id': 'alpha', 'name': '<NAME>el', 'stars': 4.3, 'daily': 420.34, 'city': 'Rio de Janeiro' }, { 'hotel_id': 'alpha', 'name': '<NAME>el', ...
0.371593
0.084568
import re from bottle import route, run, template # shamelessly stolen from https://www.w3schools.com/howto/howto_js_sort_table.asp js = """ <script> function sortTable(n) { var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0; table = document.getElementById("tbl"); switching = true; dir =...
app.py
import re from bottle import route, run, template # shamelessly stolen from https://www.w3schools.com/howto/howto_js_sort_table.asp js = """ <script> function sortTable(n) { var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0; table = document.getElementById("tbl"); switching = true; dir =...
0.215598
0.181191
import datetime import os import configparser import progressbar import string import codecs import json from instapaper import Instapaper # Init instapaper with key, secret, login and password def init(): # Read credentials from Credentials.ini file configParser = configparser.RawConfigParser() configPar...
downloader.py
import datetime import os import configparser import progressbar import string import codecs import json from instapaper import Instapaper # Init instapaper with key, secret, login and password def init(): # Read credentials from Credentials.ini file configParser = configparser.RawConfigParser() configPar...
0.234494
0.132458
from templates import * template_list = [ ("lexical_overlap", "ln_subject/object_swap", "non-entailment", lex_simple_templates), ("lexical_overlap", "ln_preposition", "non-entailment", lex_prep_templates), ("lexical_overlap", "ln_relative_clause", "non-entailment", lex_rc_templates), ...
corpus_generator.py
from templates import * template_list = [ ("lexical_overlap", "ln_subject/object_swap", "non-entailment", lex_simple_templates), ("lexical_overlap", "ln_preposition", "non-entailment", lex_prep_templates), ("lexical_overlap", "ln_relative_clause", "non-entailment", lex_rc_templates), ...
0.237046
0.271397
from time import time import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.axes3d import Axes3D from sklearn import (manifold, datasets, decomposition, ensemble, lda,random_projection) #%% #加载数据,显示数据 digits = datasets.load_digits(n_class=5) X = digits.data y = digits.target print X.shape n_img_...
ManifoldLearning/DimensionalityReduction_DataVisualizing/data_visualizing.py
from time import time import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.axes3d import Axes3D from sklearn import (manifold, datasets, decomposition, ensemble, lda,random_projection) #%% #加载数据,显示数据 digits = datasets.load_digits(n_class=5) X = digits.data y = digits.target print X.shape n_img_...
0.428473
0.560914
try: # available in Python 2.7+ from collections import OrderedDict except ImportError: from django.utils.datastructures import SortedDict as OrderedDict from django.utils.six import iteritems from .base import ParamMetadata class Output(ParamMetadata): # pylint: disable=too-few-public-methods,too-m...
eoxserver/services/ows/wps/parameters/response_form.py
try: # available in Python 2.7+ from collections import OrderedDict except ImportError: from django.utils.datastructures import SortedDict as OrderedDict from django.utils.six import iteritems from .base import ParamMetadata class Output(ParamMetadata): # pylint: disable=too-few-public-methods,too-m...
0.864711
0.305775
from api.utils import failure_response from api.utils import success_response from path.models import Path from person.models import Person from rest_framework import status from ..models import Ride class CreateRideController: def __init__(self, request, data, serializer): self._request = request ...
src/ride/controllers/create_ride_controller.py
from api.utils import failure_response from api.utils import success_response from path.models import Path from person.models import Person from rest_framework import status from ..models import Ride class CreateRideController: def __init__(self, request, data, serializer): self._request = request ...
0.669853
0.108236
class Node(object): def __init__(self, item, next=None): self.item = item self.next = next def __str__(self): if self.next == None: return '{}'.format(self.item) else: return '{}, {}'.format(self.next, self.item) class LinkedList(object): def __init__...
source_code/linkedlist.py
class Node(object): def __init__(self, item, next=None): self.item = item self.next = next def __str__(self): if self.next == None: return '{}'.format(self.item) else: return '{}, {}'.format(self.next, self.item) class LinkedList(object): def __init__...
0.42477
0.054399
from glob import glob import argparse import templaty from difflib import Differ import os import sys def write_diff(actual, expected): sys.stderr.writelines(Differ().compare(actual.splitlines(keepends=True), expected.splitlines(keepends=True))) def do_save_cmd(args): for pattern in args.files: for p...
test.py
from glob import glob import argparse import templaty from difflib import Differ import os import sys def write_diff(actual, expected): sys.stderr.writelines(Differ().compare(actual.splitlines(keepends=True), expected.splitlines(keepends=True))) def do_save_cmd(args): for pattern in args.files: for p...
0.227813
0.261817
import logging import struct import sys # this is the stupidest shit... in test context, we don't want to blow up # importing piplates because we don't have spidev, but there's not a # reasonable way to mock side-effectful imports that works in python 2, and # checking python 2 compatibility is the entire point of the...
piplate_modbus/datablocks.py
import logging import struct import sys # this is the stupidest shit... in test context, we don't want to blow up # importing piplates because we don't have spidev, but there's not a # reasonable way to mock side-effectful imports that works in python 2, and # checking python 2 compatibility is the entire point of the...
0.549157
0.293095
import numpy as np import tensorflow as tf class Encoder(tf.keras.layers.Layer): def __init__(self, n_layers, d_model, num_heads, middle_units, max_seq_len, epsilon=1e-6, dropout_rate=0.1, training=False, **kwargs): super(Encoder, self).__init__(**kwargs) self.n_layers = n_layer...
didi/deep/dfm_decor/online/modules.py
import numpy as np import tensorflow as tf class Encoder(tf.keras.layers.Layer): def __init__(self, n_layers, d_model, num_heads, middle_units, max_seq_len, epsilon=1e-6, dropout_rate=0.1, training=False, **kwargs): super(Encoder, self).__init__(**kwargs) self.n_layers = n_layer...
0.882763
0.327252
from jinja2 import Template,Environment, PackageLoader, select_autoescape from date_locals_enums import Timezone, Spacer import logging import os import datetime import sys locale = 'de_DE' messages = [] class Message(object): def __init__(self, timestamp, direction): self.timestamp = timestamp s...
threema_renderer.py
from jinja2 import Template,Environment, PackageLoader, select_autoescape from date_locals_enums import Timezone, Spacer import logging import os import datetime import sys locale = 'de_DE' messages = [] class Message(object): def __init__(self, timestamp, direction): self.timestamp = timestamp s...
0.347759
0.089933
import tkinter as tk from tkinter import * from random import randint from sudoku import SudokuBrain class TableWindow: def __init__(self): self.window = tk.Tk() self.window.geometry("300x300+100+100") # self.window.minsize(width=400, height=400) self.window.title("Sudoku Solver"...
tableUI.py
import tkinter as tk from tkinter import * from random import randint from sudoku import SudokuBrain class TableWindow: def __init__(self): self.window = tk.Tk() self.window.geometry("300x300+100+100") # self.window.minsize(width=400, height=400) self.window.title("Sudoku Solver"...
0.159675
0.193262
import os import shutil from pathlib import Path from flexlate_dev.ignore import IgnoreSpecification from tests.fixtures.temp_dir import inside_generated_dir def test_ignore_file(inside_generated_dir): ignore = IgnoreSpecification(ignore_list=["a.txt"]) _make_file_and_check_ignore("a.txt", ignore, True) ...
tests/test_ignore.py
import os import shutil from pathlib import Path from flexlate_dev.ignore import IgnoreSpecification from tests.fixtures.temp_dir import inside_generated_dir def test_ignore_file(inside_generated_dir): ignore = IgnoreSpecification(ignore_list=["a.txt"]) _make_file_and_check_ignore("a.txt", ignore, True) ...
0.228243
0.387922
from pysubyt import Settings from itertools import product import random import unittest from util4tests import run_single_test class TestSettings(unittest.TestCase): def test_statics(self): descr = Settings.describe() self.assertTrue(descr, "generic description should not be empty") self...
tests/test_settings.py
from pysubyt import Settings from itertools import product import random import unittest from util4tests import run_single_test class TestSettings(unittest.TestCase): def test_statics(self): descr = Settings.describe() self.assertTrue(descr, "generic description should not be empty") self...
0.433502
0.432782
import sys import datetime import argparse import requests from webhook_sender import CFG, models, logger, ses MULTIPLIER = int(CFG.get('webhook', 'MULTIPLIER')) RETRIES = int(CFG.get('webhook', 'RETRIES')) def send_webhook(webhook, commit=False): """ Send a single webhook. If successful, sent as recei...
webhook_sender/sender.py
import sys import datetime import argparse import requests from webhook_sender import CFG, models, logger, ses MULTIPLIER = int(CFG.get('webhook', 'MULTIPLIER')) RETRIES = int(CFG.get('webhook', 'RETRIES')) def send_webhook(webhook, commit=False): """ Send a single webhook. If successful, sent as recei...
0.258607
0.072933
import torch import torch.nn as nn def infoLOOB_loss(x, y, i, inv_tau): tau = 1 / inv_tau k = x @ y.T / tau positives = -torch.mean(torch.sum(k * i, dim=1)) # For logsumexp the zero entries must be equal to a very large negative number large_neg = -1000.0 arg_lse = k * torch.logical_not(i) + ...
src/training/methods.py
import torch import torch.nn as nn def infoLOOB_loss(x, y, i, inv_tau): tau = 1 / inv_tau k = x @ y.T / tau positives = -torch.mean(torch.sum(k * i, dim=1)) # For logsumexp the zero entries must be equal to a very large negative number large_neg = -1000.0 arg_lse = k * torch.logical_not(i) + ...
0.784236
0.583975
from marcottievents.models import DeclEnum class GroupRoundType(DeclEnum): """ Enumerated names of rounds in group stages of football competitions. """ group_stage = "Group Stage", "Group Stage" first_round = "First Round", "First Round" second_round = "Second Round", "Second Round" third_...
marcottievents/models/common/enums.py
from marcottievents.models import DeclEnum class GroupRoundType(DeclEnum): """ Enumerated names of rounds in group stages of football competitions. """ group_stage = "Group Stage", "Group Stage" first_round = "First Round", "First Round" second_round = "Second Round", "Second Round" third_...
0.692122
0.354629
from flask import Flask, json, jsonify, request, make_response from lib.config import get_config from lib.db import HapaasRedis app = Flask(__name__) config = get_config() api_base_url = "http://{}:{}/api/v1".format(config.get('api','host'), config.get('api','port')) @app.route('/config') def handle_config(): re...
api/api.py
from flask import Flask, json, jsonify, request, make_response from lib.config import get_config from lib.db import HapaasRedis app = Flask(__name__) config = get_config() api_base_url = "http://{}:{}/api/v1".format(config.get('api','host'), config.get('api','port')) @app.route('/config') def handle_config(): re...
0.265119
0.0559
from PySide import QtCore, QtGui from xldlib.controllers import bindings from xldlib.definitions import partial from xldlib.gui.views import widgets from xldlib.qt.resources import configurations as qt_config from xldlib.resources import chemical_defs from xldlib.utils import decorators, logger from . import profiles...
xldlib/gui/views/discoverer/crosslinkers.py
from PySide import QtCore, QtGui from xldlib.controllers import bindings from xldlib.definitions import partial from xldlib.gui.views import widgets from xldlib.qt.resources import configurations as qt_config from xldlib.resources import chemical_defs from xldlib.utils import decorators, logger from . import profiles...
0.710025
0.164315
import os import datetime from statslib.utils.dates import t_to_str_file_name from statslib.utils.log import Logger from statslib.utils.common import report_run_time def create_file_name(mask=None, folder=r'C:\temp', extension='csv', unique=True, ...
statslib/utils/file.py
import os import datetime from statslib.utils.dates import t_to_str_file_name from statslib.utils.log import Logger from statslib.utils.common import report_run_time def create_file_name(mask=None, folder=r'C:\temp', extension='csv', unique=True, ...
0.154089
0.059428
import unittest import json from cutlass import Study from cutlass import MIXS, MixsException from CutlassTestConfig import CutlassTestConfig from CutlassTestUtil import CutlassTestUtil # pylint: disable=W0703, C1801 class StudyTest(unittest.TestCase): """ A unit test class for the Study module. """ sessio...
tests/test_study.py
import unittest import json from cutlass import Study from cutlass import MIXS, MixsException from CutlassTestConfig import CutlassTestConfig from CutlassTestUtil import CutlassTestUtil # pylint: disable=W0703, C1801 class StudyTest(unittest.TestCase): """ A unit test class for the Study module. """ sessio...
0.569134
0.57684
"""Console script for shenshang.""" import sys import os from functools import partial from logging import getLogger import click import pandas as pd from .cooccur import compute_cooccur from .util import convert_format click.option = partial(click.option, show_default=True) def decorator_composer(*decorators): ...
shenshang/cli.py
"""Console script for shenshang.""" import sys import os from functools import partial from logging import getLogger import click import pandas as pd from .cooccur import compute_cooccur from .util import convert_format click.option = partial(click.option, show_default=True) def decorator_composer(*decorators): ...
0.592549
0.256006
import os from base64 import b64encode from pathlib import Path from subprocess import run import yaml from charmhelpers.core import hookenv from charms import layer from charms.reactive import clear_flag, hook, set_flag, when, when_any, when_not @hook('upgrade-charm') def upgrade_charm(): clear_flag('charm.sta...
charms/seldon-core/reactive/seldon_core.py
import os from base64 import b64encode from pathlib import Path from subprocess import run import yaml from charmhelpers.core import hookenv from charms import layer from charms.reactive import clear_flag, hook, set_flag, when, when_any, when_not @hook('upgrade-charm') def upgrade_charm(): clear_flag('charm.sta...
0.314577
0.056314
from PlantScriptTest import * from ScriptReader import * from Settings import * import tkinter as tk from tkinter import filedialog as tkf import os class App: def __init__(self, root): self.clearConsole() self.root = root self.root.title("PlantScriptTest App") self.path = tk.Strin...
src/PlantScriptTestApp.py
from PlantScriptTest import * from ScriptReader import * from Settings import * import tkinter as tk from tkinter import filedialog as tkf import os class App: def __init__(self, root): self.clearConsole() self.root = root self.root.title("PlantScriptTest App") self.path = tk.Strin...
0.367043
0.099514
from __future__ import absolute_import, division, print_function import numpy as np from scipy import stats import matplotlib.pyplot as plt import matplotlib.lines as mlines import statsmodels.api as sm from statsmodels.graphics.api import qqplot import nibabel as nib # Relative path to subject 1 data pathtodata = "....
final/image_scripts/tsa_plots.py
from __future__ import absolute_import, division, print_function import numpy as np from scipy import stats import matplotlib.pyplot as plt import matplotlib.lines as mlines import statsmodels.api as sm from statsmodels.graphics.api import qqplot import nibabel as nib # Relative path to subject 1 data pathtodata = "....
0.707304
0.64777
__all__ = ['AtlasFetcher'] import os import numpy as np import pandas as pd import requests import io import loompy import tempfile class AtlasFetcher(object): '''Fetch averaged cell atlas data''' atlas_table = None def fetch_atlas_table(self): '''Fetch atlas table from GitHub repo''' ur...
semiannotate/fetch_atlas.py
__all__ = ['AtlasFetcher'] import os import numpy as np import pandas as pd import requests import io import loompy import tempfile class AtlasFetcher(object): '''Fetch averaged cell atlas data''' atlas_table = None def fetch_atlas_table(self): '''Fetch atlas table from GitHub repo''' ur...
0.600891
0.366817
from google.colab import drive drive.mount('/content/drive') from pyspark import SparkContext from google.colab import drive from pyspark.sql import SQLContext, Row import pyspark.sql.functions as sqlf # Create a Spark Context sc = SparkContext.getOrCreate() # Create a sql context sqlc = SQLContext(sc) # Analysis on...
BDA_Weather_analysis.py
from google.colab import drive drive.mount('/content/drive') from pyspark import SparkContext from google.colab import drive from pyspark.sql import SQLContext, Row import pyspark.sql.functions as sqlf # Create a Spark Context sc = SparkContext.getOrCreate() # Create a sql context sqlc = SQLContext(sc) # Analysis on...
0.342462
0.394114
from datetime import datetime from typing import Optional, List from fastapi import APIRouter, Depends, HTTPException from starlette.responses import StreamingResponse, HTMLResponse from app import security from app.apis.accountAPI import CitybikeAccount, Login, UserInfo, Ride, UphillChallenge, CurrentUphillChallenge...
app/routers/account.py
from datetime import datetime from typing import Optional, List from fastapi import APIRouter, Depends, HTTPException from starlette.responses import StreamingResponse, HTMLResponse from app import security from app.apis.accountAPI import CitybikeAccount, Login, UserInfo, Ride, UphillChallenge, CurrentUphillChallenge...
0.651022
0.104752
import logging import re import sys import cmdln from project.lib.csv_celery_generator import CsvCeleryGenerator from project.lib.csv_generator import CsvGenerator from project.lib.csv_mp_generator import CsvMpGenerator from project.lib.csv_rx_generator import CsvRxGenerator from project.lib.utils import Utils loggi...
project/lib/main_command.py
import logging import re import sys import cmdln from project.lib.csv_celery_generator import CsvCeleryGenerator from project.lib.csv_generator import CsvGenerator from project.lib.csv_mp_generator import CsvMpGenerator from project.lib.csv_rx_generator import CsvRxGenerator from project.lib.utils import Utils loggi...
0.225587
0.075007
import logging import math import os from typing import Tuple ZERO_DIVISION_RETURN = -1.0 def get_log_filepath(log_filename: str) -> str: log_root = "../logs" log_filename = log_filename + ".log" return os.path.join(log_root, log_filename) def configure_logger_by_default(logger: logging.Logger) -> Non...
psob_authorship/features/utils.py
import logging import math import os from typing import Tuple ZERO_DIVISION_RETURN = -1.0 def get_log_filepath(log_filename: str) -> str: log_root = "../logs" log_filename = log_filename + ".log" return os.path.join(log_root, log_filename) def configure_logger_by_default(logger: logging.Logger) -> Non...
0.653238
0.233575
import numpy as np from sklearn.model_selection import KFold, StratifiedKFold, ShuffleSplit, StratifiedShuffleSplit from mlutils.settings import Settings from mlutils.util.serialize import save_yaml class Splitter: def __init__(self, stratified): assert hasattr(self, 'outer_splitter'), "You must define ...
mlutils/data/splitter.py
import numpy as np from sklearn.model_selection import KFold, StratifiedKFold, ShuffleSplit, StratifiedShuffleSplit from mlutils.settings import Settings from mlutils.util.serialize import save_yaml class Splitter: def __init__(self, stratified): assert hasattr(self, 'outer_splitter'), "You must define ...
0.672117
0.302031
from datetime import timedelta import logging from unittest.mock import patch from pytest_homeassistant_custom_component.common import MockConfigEntry from custom_components.keymaster.const import DOMAIN from homeassistant import setup from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassis...
tests/test_init.py
from datetime import timedelta import logging from unittest.mock import patch from pytest_homeassistant_custom_component.common import MockConfigEntry from custom_components.keymaster.const import DOMAIN from homeassistant import setup from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassis...
0.734501
0.364466
import warnings import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler # __all__ = ['CytOpT'] from CytOpT.descentAscent import cytoptDesasc from CytOpT.minmaxSwapping import cytoptMinmax from CytOpT.plots import resultPlot, BlandAltman def stopRunning(): warnings.warn("deprecated...
CytOpT/CytOpt.py
import warnings import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler # __all__ = ['CytOpT'] from CytOpT.descentAscent import cytoptDesasc from CytOpT.minmaxSwapping import cytoptMinmax from CytOpT.plots import resultPlot, BlandAltman def stopRunning(): warnings.warn("deprecated...
0.802323
0.685499
import os #clear the console and start the programme def clear_console(): os.system('clear') print('< .... AoC 2019 Day2 .... >') print() def calc_result(num1, num2, opCode): if opCode == 1: result = num1 + num2 elif opCode == 2: result = num1 * num2 else: result = -1 ...
day22019.py
import os #clear the console and start the programme def clear_console(): os.system('clear') print('< .... AoC 2019 Day2 .... >') print() def calc_result(num1, num2, opCode): if opCode == 1: result = num1 + num2 elif opCode == 2: result = num1 * num2 else: result = -1 ...
0.309128
0.614076
import argparse import sys import json from feedgen.feed import FeedGenerator def posts_type(raw_posts): posts = json.loads(raw_posts) assert isinstance(posts, list) for post in posts: assert isinstance(post, dict) assert "title" in post assert "link" in post assert "year"...
scripts/rss.py
import argparse import sys import json from feedgen.feed import FeedGenerator def posts_type(raw_posts): posts = json.loads(raw_posts) assert isinstance(posts, list) for post in posts: assert isinstance(post, dict) assert "title" in post assert "link" in post assert "year"...
0.410756
0.277702
import json mate_in_1 = []; mate_in_2 = []; mate_in_3 = []; mate_in_4 = []; mate_in_5 = []; mate_in_6 = []; mate_in_7 = []; with open('puzzles_verified.json') as fr: games = json.loads(fr.read()) for game in games: if 'Mate in 1 ' in game['title']: mate_in_1.append(game) elif 'Mate in 2 '...
puzzle_generator/sort_puzzles.py
import json mate_in_1 = []; mate_in_2 = []; mate_in_3 = []; mate_in_4 = []; mate_in_5 = []; mate_in_6 = []; mate_in_7 = []; with open('puzzles_verified.json') as fr: games = json.loads(fr.read()) for game in games: if 'Mate in 1 ' in game['title']: mate_in_1.append(game) elif 'Mate in 2 '...
0.155303
0.266122
import pygame as pg from pygame.locals import * from connect_4_images import * # BLIT, RECT, SCREEN from connect_4_scene_switch import * from _connect4_logic import * class GAME_MODE(): def __init__(self): self.gear_top_left = ROTATE(image.GEAR,(176,63),1.5) self.gear_top_right = ROTATE(image.GEA...
Connect4Game-x64/connect_4_game_mode.py
import pygame as pg from pygame.locals import * from connect_4_images import * # BLIT, RECT, SCREEN from connect_4_scene_switch import * from _connect4_logic import * class GAME_MODE(): def __init__(self): self.gear_top_left = ROTATE(image.GEAR,(176,63),1.5) self.gear_top_right = ROTATE(image.GEA...
0.156814
0.089058
from homeassistant.components.fan import SUPPORT_SET_SPEED from homeassistant.const import ( PERCENTAGE, TIME_MINUTES, ) from ..const import HIMOX_H06_PURIFIER_PAYLOAD from ..helpers import assert_device_properties_set from ..mixins.light import BasicLightTests from ..mixins.select import MultiSelectT...
tests/devices/test_himox_h06_purifier.py
from homeassistant.components.fan import SUPPORT_SET_SPEED from homeassistant.const import ( PERCENTAGE, TIME_MINUTES, ) from ..const import HIMOX_H06_PURIFIER_PAYLOAD from ..helpers import assert_device_properties_set from ..mixins.light import BasicLightTests from ..mixins.select import MultiSelectT...
0.361165
0.16502
from enum import Enum, EnumMeta from six import with_metaclass class _CaseInsensitiveEnumMeta(EnumMeta): def __getitem__(self, name): return super().__getitem__(name.upper()) def __getattr__(cls, name): """Return the enum member matching `name` We use __getattr__ instead of descriptor...
msgraph-cli-extensions/beta/bookings_beta/azext_bookings_beta/vendored_sdks/bookings/models/_bookings_enums.py
from enum import Enum, EnumMeta from six import with_metaclass class _CaseInsensitiveEnumMeta(EnumMeta): def __getitem__(self, name): return super().__getitem__(name.upper()) def __getattr__(cls, name): """Return the enum member matching `name` We use __getattr__ instead of descriptor...
0.577853
0.04798
import logging import unicodedata from typing import List, Optional from aispace.datasets.vocabulary import Vocabulary from aispace.datasets.tokenizer.tokenizer_base import BaseTokenizer from aispace.utils.hparams import Hparams from aispace.utils.str_utils import truncate_seq_pair, preprocess_text __all__ = [ "...
aispace/datasets/tokenizer/xlnet_tokenizer.py
import logging import unicodedata from typing import List, Optional from aispace.datasets.vocabulary import Vocabulary from aispace.datasets.tokenizer.tokenizer_base import BaseTokenizer from aispace.utils.hparams import Hparams from aispace.utils.str_utils import truncate_seq_pair, preprocess_text __all__ = [ "...
0.827515
0.306877
import numpy as np from utils import (DEBUG, random_row, NORTH, EAST, SOUTH, WEST) from numpy.random import RandomState import sys def exceptions_magic(self, car): """Handles special cases for turning cars. Arguments: car {Car} -- The car that should drive. Returns: int -- The state of ...
magic.py
import numpy as np from utils import (DEBUG, random_row, NORTH, EAST, SOUTH, WEST) from numpy.random import RandomState import sys def exceptions_magic(self, car): """Handles special cases for turning cars. Arguments: car {Car} -- The car that should drive. Returns: int -- The state of ...
0.498535
0.421254
from typing import List from unittest import TestCase from oci.core import ComputeClient, ComputeClientCompositeOperations from oci.core.models.instance import Instance from oci.response import Response from oci.exceptions import ServiceError from oci_emulator import app from app.enums.compute.instance_action import ...
tests/compute/test_perform_action.py
from typing import List from unittest import TestCase from oci.core import ComputeClient, ComputeClientCompositeOperations from oci.core.models.instance import Instance from oci.response import Response from oci.exceptions import ServiceError from oci_emulator import app from app.enums.compute.instance_action import ...
0.653127
0.326486
from kmip.core.enums import CredentialType from kmip.core.objects import Credential class CredentialFactory(object): def __init__(self): pass def _create_credential(self, credential_type, credential_value): credential_type = Credential.CredentialType(credential_type) return Credenti...
kmip/core/factories/credentials.py
from kmip.core.enums import CredentialType from kmip.core.objects import Credential class CredentialFactory(object): def __init__(self): pass def _create_credential(self, credential_type, credential_value): credential_type = Credential.CredentialType(credential_type) return Credenti...
0.649467
0.099689
# REST basics # ======================================== # Stateless. Roulette. Base class definitions. from typing import Dict, Tuple, Optional, List, Iterable, Any, TYPE_CHECKING, cast if TYPE_CHECKING: from wsgiref.types import WSGIApplication, WSGIEnvironment, StartResponse import random from Chapter_13.ch...
Chapter_13/ch13_e1_ex4.py
# REST basics # ======================================== # Stateless. Roulette. Base class definitions. from typing import Dict, Tuple, Optional, List, Iterable, Any, TYPE_CHECKING, cast if TYPE_CHECKING: from wsgiref.types import WSGIApplication, WSGIEnvironment, StartResponse import random from Chapter_13.ch...
0.348756
0.211478
"""""" from pysec.core import is_int, is_str, is_dict SPECIAL_CHARS = '\\', '*', '?', '!', '[', ']', '{', '}', '-', ',', '#', '@' ALPHA = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' DIGITS = '0123456789' LOWER = 'abcdefghijklmnopqrstuvwxyz' UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ALPHANUMERIC = DIGITS + ALPH...
pysec/binary.py
"""""" from pysec.core import is_int, is_str, is_dict SPECIAL_CHARS = '\\', '*', '?', '!', '[', ']', '{', '}', '-', ',', '#', '@' ALPHA = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' DIGITS = '0123456789' LOWER = 'abcdefghijklmnopqrstuvwxyz' UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ALPHANUMERIC = DIGITS + ALPH...
0.308607
0.352007
from __future__ import annotations import json import random import time from typing import Any, Dict, List, Optional, Type, TypeVar, Union import flask from trickster import TricksterException class RouteConfigurationError(TricksterException, ValueError): """Raised when route could not be configured because ...
trickster/routing/__init__.py
from __future__ import annotations import json import random import time from typing import Any, Dict, List, Optional, Type, TypeVar, Union import flask from trickster import TricksterException class RouteConfigurationError(TricksterException, ValueError): """Raised when route could not be configured because ...
0.919412
0.209146
import os import sys sys.path.append('../common') import TCWordSeg OUT_WORD = TCWordSeg.OUT_WORD OUT_PHRASE = TCWordSeg.OUT_PHRASE OUT_SUBPHRASE = TCWordSeg.OUT_SUBPHRASE TC_ENGU = TCWordSeg.TC_ENGU TC_GU = TCWordSeg.TC_GU TC_POS = TCWordSeg.TC_POS TC_USR = TCWordSeg.TC_USR TC_S2D = TCWordSeg.TC_S2D TC_U2L = TCWordSe...
common/tcseg.py
import os import sys sys.path.append('../common') import TCWordSeg OUT_WORD = TCWordSeg.OUT_WORD OUT_PHRASE = TCWordSeg.OUT_PHRASE OUT_SUBPHRASE = TCWordSeg.OUT_SUBPHRASE TC_ENGU = TCWordSeg.TC_ENGU TC_GU = TCWordSeg.TC_GU TC_POS = TCWordSeg.TC_POS TC_USR = TCWordSeg.TC_USR TC_S2D = TCWordSeg.TC_S2D TC_U2L = TCWordSe...
0.145905
0.044806
import time print("Setting up") start = time.time() import os import RPi.GPIO as GPIO import pygame import pygame.camera from pygame.locals import * from time import sleep from fastai.vision import * from fastai.metrics import error_rate from pathlib import Path from glob2 import glob from sklearn.metrics import conf...
fastai/test2.py
import time print("Setting up") start = time.time() import os import RPi.GPIO as GPIO import pygame import pygame.camera from pygame.locals import * from time import sleep from fastai.vision import * from fastai.metrics import error_rate from pathlib import Path from glob2 import glob from sklearn.metrics import conf...
0.257672
0.145813
import os import sys import cv2 import numpy as np ''' Display result Left = Original Image Right = Reconstructed Face ''' def displayResult(left, right) : output = np.hstack((left,right)) output = cv2.resize(output, (0,0), fx=4, fy=4) cv2.imshow("Result", output) # Recontruct face using mean face and EigenFac...
ITEM 20-29/ITEM22 reconstructFace/reconstructFace.py
import os import sys import cv2 import numpy as np ''' Display result Left = Original Image Right = Reconstructed Face ''' def displayResult(left, right) : output = np.hstack((left,right)) output = cv2.resize(output, (0,0), fx=4, fy=4) cv2.imshow("Result", output) # Recontruct face using mean face and EigenFac...
0.377541
0.51623
from os import truncate import sys import random from typing import Dict def custom_hash(key:str) -> int: """ Hashes the key in a consistent manner, since python changes the seeding between sessions for ''''''security reasons'''''' """ h = "" for character in key: h += str(ord(characte...
Cryptography/substitution.py
from os import truncate import sys import random from typing import Dict def custom_hash(key:str) -> int: """ Hashes the key in a consistent manner, since python changes the seeding between sessions for ''''''security reasons'''''' """ h = "" for character in key: h += str(ord(characte...
0.496582
0.265714
import torch import torch.nn as nn from tree_to_sequence.tree_to_sequence import TreeToSequence class TreeToSequenceAttention(TreeToSequence): def __init__(self, encoder, decoder, hidden_size, nclass, embedding_size, alignment_size=50, align_type=1): super(TreeToSequenceAttention, self)....
tree_to_sequence/tree_to_sequence_attention.py
import torch import torch.nn as nn from tree_to_sequence.tree_to_sequence import TreeToSequence class TreeToSequenceAttention(TreeToSequence): def __init__(self, encoder, decoder, hidden_size, nclass, embedding_size, alignment_size=50, align_type=1): super(TreeToSequenceAttention, self)....
0.904636
0.696281
import pycuda.autoinit import pycuda.driver as drv import pycuda.gpuarray as gpuarray import numpy as np import matplotlib.pyplot as plt import time import scipy.io as sio import pkg_resources import sys from Alignment.Alignments import * from Alignment.AlignmentTools import * from Alignment.DTWGPU import * import Alig...
GPUExamples.py
import pycuda.autoinit import pycuda.driver as drv import pycuda.gpuarray as gpuarray import numpy as np import matplotlib.pyplot as plt import time import scipy.io as sio import pkg_resources import sys from Alignment.Alignments import * from Alignment.AlignmentTools import * from Alignment.DTWGPU import * import Alig...
0.188473
0.55935
import urllib.request as urlreq import json import shutil from datetime import datetime import textwrap import sys # Description size must be dynamic because of different dishes, but other columns are stable def drawAsciiTable(entries, descriptionSize, sdate=''): tableWidth = 21 + 2 + descriptionSize windowSiz...
sict2.py
import urllib.request as urlreq import json import shutil from datetime import datetime import textwrap import sys # Description size must be dynamic because of different dishes, but other columns are stable def drawAsciiTable(entries, descriptionSize, sdate=''): tableWidth = 21 + 2 + descriptionSize windowSiz...
0.141341
0.142978
import re import json import urllib from lib import helpers from urlresolver9 import common from urlresolver9.resolver import UrlResolver, ResolverError class MailRuResolver(UrlResolver): name = "mail.ru" domains = ['mail.ru', 'my.mail.ru', 'videoapi.my.mail.ru', 'api.video.mail.ru'] pattern = '(?://|\.)(m...
script.mrknow.urlresolver/lib/urlresolver9/plugins/mailru.py
import re import json import urllib from lib import helpers from urlresolver9 import common from urlresolver9.resolver import UrlResolver, ResolverError class MailRuResolver(UrlResolver): name = "mail.ru" domains = ['mail.ru', 'my.mail.ru', 'videoapi.my.mail.ru', 'api.video.mail.ru'] pattern = '(?://|\.)(m...
0.146392
0.066418