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 argparse import re import time from utils import call_subprocess, unit_translation if __name__ == '__main__': my_parser = argparse.ArgumentParser() my_parser.add_argument('--label', action='store', type=str) args = my_parser.parse_args() ts = int(time.time()) stats_output =...
bin/docker_stats.py
import argparse import re import time from utils import call_subprocess, unit_translation if __name__ == '__main__': my_parser = argparse.ArgumentParser() my_parser.add_argument('--label', action='store', type=str) args = my_parser.parse_args() ts = int(time.time()) stats_output =...
0.147893
0.254324
import json import os import time import datetime import random import hashlib import requests from core.settings import * class GenshinID(object): def __init__(self, genshinID: str): self.GenshinID = genshinID def showGenshinID(self): print(self.GenshinID) def getDailyNote(self): ...
core/GenshinUtility.py
import json import os import time import datetime import random import hashlib import requests from core.settings import * class GenshinID(object): def __init__(self, genshinID: str): self.GenshinID = genshinID def showGenshinID(self): print(self.GenshinID) def getDailyNote(self): ...
0.288469
0.155751
import warnings import numpy as np from ..data import units from ..computation import Transformer, Graph from .util import apply, apply_to_axis from ..computation.nodes import Add, Subtract, Multiply, Divide, Constant from .queries import Slice __all__ = [ 'Add', 'Subtract', 'Multiply', 'Divide', ...
tsfuse/transformers/mathematics.py
import warnings import numpy as np from ..data import units from ..computation import Transformer, Graph from .util import apply, apply_to_axis from ..computation.nodes import Add, Subtract, Multiply, Divide, Constant from .queries import Slice __all__ = [ 'Add', 'Subtract', 'Multiply', 'Divide', ...
0.862279
0.495972
from pprint import pformat from six import iteritems import re class History(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, id=None, labels_added=None, labels_removed=None, messages=None, messages_added=...
gmail_client/models/history.py
from pprint import pformat from six import iteritems import re class History(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, id=None, labels_added=None, labels_removed=None, messages=None, messages_added=...
0.772702
0.262523
from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.core.files.uploadedfile import InMemoryUploadedFile from .models import * class AddNoteForm(forms.ModelForm): class Meta: model = Note fields = ('name', 'text', 'file') widgets ...
Evernote_Django/evernote/forms.py
from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.core.files.uploadedfile import InMemoryUploadedFile from .models import * class AddNoteForm(forms.ModelForm): class Meta: model = Note fields = ('name', 'text', 'file') widgets ...
0.3492
0.098642
import sys import os from lxml import html import requests import xmltodict from xml.parsers.expat import ExpatError import re import threading import Queue import time import datetime qURL = Queue.Queue() qReport = Queue.Queue() class P3PScanner(threading.Thread): def __init__(self, qURL, qReport): th...
P3PscanMT.py
import sys import os from lxml import html import requests import xmltodict from xml.parsers.expat import ExpatError import re import threading import Queue import time import datetime qURL = Queue.Queue() qReport = Queue.Queue() class P3PScanner(threading.Thread): def __init__(self, qURL, qReport): th...
0.185947
0.12692
import torch from torch import nn import torch.nn.functional as F from torch.autograd import Variable class BCEFocalLoss(nn.Module): def __init__(self, gamma=2): super(BCEFocalLoss, self).__init__() self.gamma = gamma def forward(self, input, target): BCE_loss = F.binary_cross_entropy...
src/utility/loss.py
import torch from torch import nn import torch.nn.functional as F from torch.autograd import Variable class BCEFocalLoss(nn.Module): def __init__(self, gamma=2): super(BCEFocalLoss, self).__init__() self.gamma = gamma def forward(self, input, target): BCE_loss = F.binary_cross_entropy...
0.959856
0.453625
import unittest from . utils import TranspileTestCase class TestJs2Py(TranspileTestCase): def js2py_test(self, decl, check, result): self.assertJavaScriptExecution( """ from harness import testfunc val = testfunc() %s print("Done.") ...
tests/test_types.py
import unittest from . utils import TranspileTestCase class TestJs2Py(TranspileTestCase): def js2py_test(self, decl, check, result): self.assertJavaScriptExecution( """ from harness import testfunc val = testfunc() %s print("Done.") ...
0.395368
0.403273
import glob import os import pandas as pd import trimesh from im2mesh.eval import MeshEvaluator import numpy as np pix3d_path = '../../datasets/pix3d' eval_dicts = [] evaluator = MeshEvaluator(n_points=200000) folders = ['occupancy', 'occupancy_manifold', 'occupancy_manifoldPlus'] classes = ['bookcase', 'desk', 'sofa'...
scripts/eval_pix3d_occ.py
import glob import os import pandas as pd import trimesh from im2mesh.eval import MeshEvaluator import numpy as np pix3d_path = '../../datasets/pix3d' eval_dicts = [] evaluator = MeshEvaluator(n_points=200000) folders = ['occupancy', 'occupancy_manifold', 'occupancy_manifoldPlus'] classes = ['bookcase', 'desk', 'sofa'...
0.287968
0.17989
import boto3 import pytest import sure # noqa # pylint: disable=unused-import from botocore.exceptions import ClientError from moto import mock_redshiftdata from tests.test_redshiftdata.test_redshiftdata_constants import ErrorAttributes REGION = "us-east-1" INVALID_ID_ERROR_MESSAGE = ( "id must satisfy regex pat...
tests/test_redshiftdata/test_redshiftdata.py
import boto3 import pytest import sure # noqa # pylint: disable=unused-import from botocore.exceptions import ClientError from moto import mock_redshiftdata from tests.test_redshiftdata.test_redshiftdata_constants import ErrorAttributes REGION = "us-east-1" INVALID_ID_ERROR_MESSAGE = ( "id must satisfy regex pat...
0.481698
0.292198
import os import asyncio import aiohttp import json import time import pymongo def save_to_mongo(content): content = json.loads(content) try: projects = content['response']['discoverables'] except KeyError: print("It's most likely that the scraping is already done.") exit(0) f...
IndiegogoSpider/spider.py
import os import asyncio import aiohttp import json import time import pymongo def save_to_mongo(content): content = json.loads(content) try: projects = content['response']['discoverables'] except KeyError: print("It's most likely that the scraping is already done.") exit(0) f...
0.165222
0.138084
from typing import List, Sequence, Tuple, DefaultDict, Dict, Union import functools from itertools import chain, repeat import numpy as np from numpy.lib.arraysetops import isin import pandas as pd # pytorch import torch from torch import Tensor import torch.nn as nn import torch.nn.functional as F # networkx import ...
segnlp/layers/pair_reps/dep_treelstm.py
from typing import List, Sequence, Tuple, DefaultDict, Dict, Union import functools from itertools import chain, repeat import numpy as np from numpy.lib.arraysetops import isin import pandas as pd # pytorch import torch from torch import Tensor import torch.nn as nn import torch.nn.functional as F # networkx import ...
0.946621
0.459864
from rest_framework.permissions import AllowAny, IsAdminUser from rest_framework.viewsets import ModelViewSet, ViewSet from django_filters.rest_framework import DjangoFilterBackend from rest_framework import filters from core.serializers import * from core.models import * list_permission_classes = { "list": [All...
backend/core/views.py
from rest_framework.permissions import AllowAny, IsAdminUser from rest_framework.viewsets import ModelViewSet, ViewSet from django_filters.rest_framework import DjangoFilterBackend from rest_framework import filters from core.serializers import * from core.models import * list_permission_classes = { "list": [All...
0.411229
0.198938
from scipy import ndimage import csv import numpy as np import cv2 import math from sklearn.model_selection import train_test_split from sklearn.utils import shuffle # Configuration training_valid_dataset = ['/root/opt/track1_3lap_new', '/root/opt/track1_1lap_clockwise'] correction_factor = 0.2 batch_size = 32 epochs ...
model.py
from scipy import ndimage import csv import numpy as np import cv2 import math from sklearn.model_selection import train_test_split from sklearn.utils import shuffle # Configuration training_valid_dataset = ['/root/opt/track1_3lap_new', '/root/opt/track1_1lap_clockwise'] correction_factor = 0.2 batch_size = 32 epochs ...
0.737631
0.520984
from os.path import dirname, join, abspath from django import VERSION as DJANGO_VERSION try: import raven except ImportError: raven = None #Django settings below, do not touch! APPEND_SLASH = False TEMPLATE_DEBUG = False SILENCED_SYSTEM_CHECKS = ['urls.W002'] TEMPLATES = [ { 'BACKEND': 'django.te...
webapp/graphite/app_settings.py
from os.path import dirname, join, abspath from django import VERSION as DJANGO_VERSION try: import raven except ImportError: raven = None #Django settings below, do not touch! APPEND_SLASH = False TEMPLATE_DEBUG = False SILENCED_SYSTEM_CHECKS = ['urls.W002'] TEMPLATES = [ { 'BACKEND': 'django.te...
0.31321
0.04363
import os from typing import Dict, Optional, Any import requests from flask import Flask, jsonify, redirect from flask_cors import CORS from lxml import html app = Flask(__name__) app.config['JSON_SORT_KEYS'] = False CORS(app) def get_page_src(url: str) -> Optional[Any]: response = requests.get(url) src = html.f...
main.py
import os from typing import Dict, Optional, Any import requests from flask import Flask, jsonify, redirect from flask_cors import CORS from lxml import html app = Flask(__name__) app.config['JSON_SORT_KEYS'] = False CORS(app) def get_page_src(url: str) -> Optional[Any]: response = requests.get(url) src = html.f...
0.515376
0.075858
from botaclan.constants import GOOGLEAPI_CALENDAR_ID from google.oauth2 import service_account from googleapiclient.discovery import build, Resource from typing import List, Dict import botaclan.helpers.lists import copy import datetime import logging log = logging.getLogger(__name__) def create_calendar_client(cred...
botaclan/google/google_calendar.py
from botaclan.constants import GOOGLEAPI_CALENDAR_ID from google.oauth2 import service_account from googleapiclient.discovery import build, Resource from typing import List, Dict import botaclan.helpers.lists import copy import datetime import logging log = logging.getLogger(__name__) def create_calendar_client(cred...
0.518059
0.120646
import copy import pytest from impacts_estimation.impacts_estimation import ImpactEstimator, estimate_impacts from impacts_estimation.exceptions import NoCharacterizedIngredientsError, NoKnownIngredientsError from impacts_estimation.utils import flat_ingredients_list_DFS from data import ingredients_data, off_taxonom...
tests/impacts_estimation/test_impact_estimator.py
import copy import pytest from impacts_estimation.impacts_estimation import ImpactEstimator, estimate_impacts from impacts_estimation.exceptions import NoCharacterizedIngredientsError, NoKnownIngredientsError from impacts_estimation.utils import flat_ingredients_list_DFS from data import ingredients_data, off_taxonom...
0.776708
0.576482
import subprocess from datetime import datetime from email.mime.text import MIMEText from smtplib import SMTP_SSL from uuid import uuid4 from pymongo.collection import Collection def send_confirmation_email(col: Collection, email: str): # Generate a code confirmation_code = str(uuid4()) col.update_one({'e...
listening-test-server/tools/email_tool.py
import subprocess from datetime import datetime from email.mime.text import MIMEText from smtplib import SMTP_SSL from uuid import uuid4 from pymongo.collection import Collection def send_confirmation_email(col: Collection, email: str): # Generate a code confirmation_code = str(uuid4()) col.update_one({'e...
0.207616
0.112698
from typing import Union from torch.nn import Module from . import ClassificationFactory from .backbones.backbone_factory import BACKBONES import logging logging.basicConfig(level=logging.INFO) class ModelFacade: """ Class realize facade pattern for all models Arguments: task: ...
opti_models/models/models_facade.py
from typing import Union from torch.nn import Module from . import ClassificationFactory from .backbones.backbone_factory import BACKBONES import logging logging.basicConfig(level=logging.INFO) class ModelFacade: """ Class realize facade pattern for all models Arguments: task: ...
0.902144
0.291472
from .._tier0 import Image from .._tier0 import plugin_function from .._tier0 import create_labels_like @plugin_function(categories=['label processing', 'in assistant'], output_creator=create_labels_like) def erode_labels(labels_input : Image, labels_destination : Image = None, radius: int = 1, relabel_islands : bool ...
pyclesperanto_prototype/_tier4/_erode_labels.py
from .._tier0 import Image from .._tier0 import plugin_function from .._tier0 import create_labels_like @plugin_function(categories=['label processing', 'in assistant'], output_creator=create_labels_like) def erode_labels(labels_input : Image, labels_destination : Image = None, radius: int = 1, relabel_islands : bool ...
0.820685
0.559651
import popupcad from popupcad.filetypes.operation2 import Operation2, LayerBasedOperation import qt.QtCore as qc import qt.QtGui as qg from popupcad.filetypes.laminate import Laminate from popupcad.filetypes.validators import StrictDoubleValidator from dev_tools.enum import enum from popupcad.filetypes.operationoutp...
popupcad_manufacturing_plugins/manufacturing/customsupport4.py
import popupcad from popupcad.filetypes.operation2 import Operation2, LayerBasedOperation import qt.QtCore as qc import qt.QtGui as qg from popupcad.filetypes.laminate import Laminate from popupcad.filetypes.validators import StrictDoubleValidator from dev_tools.enum import enum from popupcad.filetypes.operationoutp...
0.504639
0.144089
from dash.development.base_component import Component, _explicitize_args class Row(Component): """A Row component. Row is one of the core layout components in Bootstrap. Build up your layout as a series of rows of columns. Row has arguments for controlling the vertical and horizontal alignment of its children, a...
venv/lib/python3.9/site-packages/dash_bootstrap_components/_components/Row.py
from dash.development.base_component import Component, _explicitize_args class Row(Component): """A Row component. Row is one of the core layout components in Bootstrap. Build up your layout as a series of rows of columns. Row has arguments for controlling the vertical and horizontal alignment of its children, a...
0.894011
0.463384
import logging import multiprocessing import random import signal import time import unittest from coapthon.client.helperclient import HelperClient from Entity.attack import Attack from Entity.input_format import InputFormat from protocols import CoAP as PeniotCoAP class CoAPPayloadSizeFuzzerAttack(Attack): """...
src/protocols/CoAP/attacks/coap_payload_size_fuzzer.py
import logging import multiprocessing import random import signal import time import unittest from coapthon.client.helperclient import HelperClient from Entity.attack import Attack from Entity.input_format import InputFormat from protocols import CoAP as PeniotCoAP class CoAPPayloadSizeFuzzerAttack(Attack): """...
0.481698
0.245413
import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import i2c, sensor from esphome.const import ( CONF_GAIN, CONF_ID, CONF_NAME, CONF_INTEGRATION_TIME, CONF_FULL_SPECTRUM, CONF_INFRARED, CONF_POWER_SAVE_MODE, CONF_VISIBLE, CONF_CALCULATED_LUX...
esphome/components/tsl2591/sensor.py
import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import i2c, sensor from esphome.const import ( CONF_GAIN, CONF_ID, CONF_NAME, CONF_INTEGRATION_TIME, CONF_FULL_SPECTRUM, CONF_INFRARED, CONF_POWER_SAVE_MODE, CONF_VISIBLE, CONF_CALCULATED_LUX...
0.385837
0.155431
from socket import socket import pytest from mock import Mock, PropertyMock, patch from microBrew.brew_repository import BrewInfo, BrewRepository from microBrew.decision_module import DecisionModule, TargetState from microBrew.device_manager import DeviceManager from microBrew.server import Server from microBrew.temp...
src/test/test_server.py
from socket import socket import pytest from mock import Mock, PropertyMock, patch from microBrew.brew_repository import BrewInfo, BrewRepository from microBrew.decision_module import DecisionModule, TargetState from microBrew.device_manager import DeviceManager from microBrew.server import Server from microBrew.temp...
0.455683
0.288272
from __future__ import with_statement from lamson import queue from config import settings from datetime import datetime import os import shutil import simplejson as json import base64 import stat ALLOWED_HEADERS = set([ "From", "In-Reply-To", "List-Id", "Precedence", "References", "Reply-To", "Return-Path", "Sende...
examples/librelist/app/model/archive.py
from __future__ import with_statement from lamson import queue from config import settings from datetime import datetime import os import shutil import simplejson as json import base64 import stat ALLOWED_HEADERS = set([ "From", "In-Reply-To", "List-Id", "Precedence", "References", "Reply-To", "Return-Path", "Sende...
0.536799
0.088387
import asyncio import time import uuid from ruamel import yaml from discord.ext import commands import discord from .spoilers import SADAMA_ROLE, VSPOILER_ROLE, SPOILER_ROLE debug = 0 if debug == 1: # hanss314 MEMELORD_CHANNEL = 368282610910363648 JOINBOT_CHANNEL = 368282610910363648 MODERATOR_ROLE = 2...
cogs/other_bots/moderation.py
import asyncio import time import uuid from ruamel import yaml from discord.ext import commands import discord from .spoilers import SADAMA_ROLE, VSPOILER_ROLE, SPOILER_ROLE debug = 0 if debug == 1: # hanss314 MEMELORD_CHANNEL = 368282610910363648 JOINBOT_CHANNEL = 368282610910363648 MODERATOR_ROLE = 2...
0.214774
0.082697
import json import logging import os import sched import sys import time try: import pika import psutil from pika.exceptions import AMQPError except ImportError: pass def get_channel(rabbit_config): credentials = pika.PlainCredentials(rabbit_config['broker_user'], ...
psutil_agent/loop.py
import json import logging import os import sched import sys import time try: import pika import psutil from pika.exceptions import AMQPError except ImportError: pass def get_channel(rabbit_config): credentials = pika.PlainCredentials(rabbit_config['broker_user'], ...
0.353986
0.116312
import re from typing import Any, NamedTuple, Tuple __all__ = ["expand_contractions"] class Rule(NamedTuple): pattern: Any replacement: str FLAGS = re.IGNORECASE # Ordering of the rules matters. # Contractions based on the following references: # https://stackoverflow.com/a/19794953/519951 ...
src/scml/nlp/contractions.py
import re from typing import Any, NamedTuple, Tuple __all__ = ["expand_contractions"] class Rule(NamedTuple): pattern: Any replacement: str FLAGS = re.IGNORECASE # Ordering of the rules matters. # Contractions based on the following references: # https://stackoverflow.com/a/19794953/519951 ...
0.694717
0.274133
import http import logging import sys import time from collections import abc from copy import copy from os import getpid import click TRACE_LOG_LEVEL = 5 class ColourizedFormatter(logging.Formatter): """ A custom log formatter class that: * Outputs the LOG_LEVEL with an appropriate color. * If a l...
uvicorn/logging.py
import http import logging import sys import time from collections import abc from copy import copy from os import getpid import click TRACE_LOG_LEVEL = 5 class ColourizedFormatter(logging.Formatter): """ A custom log formatter class that: * Outputs the LOG_LEVEL with an appropriate color. * If a l...
0.423458
0.143608
import os import json from collections.abc import Mapping from numpy.lib.format import read_array from spectrochempy.utils import json_decoder __all__ = ["make_zipfile", "ScpFile"] # ====================================================================================================================== # ZIP UTILITI...
spectrochempy/utils/zip.py
import os import json from collections.abc import Mapping from numpy.lib.format import read_array from spectrochempy.utils import json_decoder __all__ = ["make_zipfile", "ScpFile"] # ====================================================================================================================== # ZIP UTILITI...
0.582016
0.279669
__author__ = "Telefonica I+D, @jframos" __project__ = "python-qautils [https://github.com/qaenablers/python-qautils]" __copyright__ = "Copyright 2015" __license__ = " Apache License, Version 2.0" __version__ = "1.2.1" import logging import logging.config from xml.dom.minidom import parseString import json import os f...
qautils/logger/logger_utils.py
__author__ = "Telefonica I+D, @jframos" __project__ = "python-qautils [https://github.com/qaenablers/python-qautils]" __copyright__ = "Copyright 2015" __license__ = " Apache License, Version 2.0" __version__ = "1.2.1" import logging import logging.config from xml.dom.minidom import parseString import json import os f...
0.503662
0.101411
import numpy as np import vampyre from ebmrPy.inference.ebmr import EBMR from ebmrPy.inference.iridge import IRidge import collections def fit_ebmr_base(X, y, prior = 'point', grr = 'mle', grid = np.array([0.001, 1.0, 2.0, 3.0, 4.0]), ignore_convergence = True): # EBMR does not add int...
dsc/functions/fit.py
import numpy as np import vampyre from ebmrPy.inference.ebmr import EBMR from ebmrPy.inference.iridge import IRidge import collections def fit_ebmr_base(X, y, prior = 'point', grr = 'mle', grid = np.array([0.001, 1.0, 2.0, 3.0, 4.0]), ignore_convergence = True): # EBMR does not add int...
0.630344
0.345188
import re import random import json import xml.etree.ElementTree import os from urllib.parse import unquote import logger def safeCast(val, to_type, default=None): try: return to_type(val) except (ValueError, TypeError): return default def getFontResultIndex(txt): lineRegEx = re.search('f...
system/converter.py
import re import random import json import xml.etree.ElementTree import os from urllib.parse import unquote import logger def safeCast(val, to_type, default=None): try: return to_type(val) except (ValueError, TypeError): return default def getFontResultIndex(txt): lineRegEx = re.search('f...
0.156846
0.096025
import os import json import paho.mqtt.client as mqtt class MQTTConnector: def __init__(self, controller): self.controller = controller self.user = os.environ.get("MQTT_USER") self.password = os.environ.get("MQTT_PSW") self.host = os.environ.get("MQTT_HOST") self.po...
utils/MQTTConnector.py
import os import json import paho.mqtt.client as mqtt class MQTTConnector: def __init__(self, controller): self.controller = controller self.user = os.environ.get("MQTT_USER") self.password = os.environ.get("MQTT_PSW") self.host = os.environ.get("MQTT_HOST") self.po...
0.316581
0.04714
from __future__ import unicode_literals from .common import InfoExtractor from ..utils import parse_iso8601 class PeriscopeIE(InfoExtractor): IE_DESC = 'Periscope' _VALID_URL = r'https?://(?:www\.)?periscope\.tv/[^/]+/(?P<id>[^/?#]+)' # Alive example URLs can be found here http://onperiscope.com/ _TE...
youtube_dl/extractor/periscope.py
from __future__ import unicode_literals from .common import InfoExtractor from ..utils import parse_iso8601 class PeriscopeIE(InfoExtractor): IE_DESC = 'Periscope' _VALID_URL = r'https?://(?:www\.)?periscope\.tv/[^/]+/(?P<id>[^/?#]+)' # Alive example URLs can be found here http://onperiscope.com/ _TE...
0.535827
0.152568
import re import os import hashlib from importlib import import_module from click import echo _rx_pp = re.compile(r"^[\w_.:]+$", re.ASCII) _rx_file = re.compile(r"\.[a-z]*$", re.IGNORECASE) def safe_print(x, nl=True, **kwds): """Fault-safe print function. Parameters ---------- x : any An obje...
taukit/utils.py
import re import os import hashlib from importlib import import_module from click import echo _rx_pp = re.compile(r"^[\w_.:]+$", re.ASCII) _rx_file = re.compile(r"\.[a-z]*$", re.IGNORECASE) def safe_print(x, nl=True, **kwds): """Fault-safe print function. Parameters ---------- x : any An obje...
0.603932
0.201892
import logging from pprint import pprint from unittest import TestCase from future.utils import lmap from foxylib.tools.log.foxylib_logger import FoxylibLogger from foxylib.tools.math.tournament.tourney_tool import TourneyTool class TestTourneyTool(TestCase): @classmethod def setUpClass(cls): Foxyli...
foxylib/tools/math/tournament/tests/test_tournament_tool.py
import logging from pprint import pprint from unittest import TestCase from future.utils import lmap from foxylib.tools.log.foxylib_logger import FoxylibLogger from foxylib.tools.math.tournament.tourney_tool import TourneyTool class TestTourneyTool(TestCase): @classmethod def setUpClass(cls): Foxyli...
0.340047
0.421254
from __future__ import absolute_import import responses import pytest from sentry.auth.exceptions import IdentityNotValid from sentry.models import Identity from sentry.utils import json from .testutils import GitLabTestCase class GitlabRefreshAuthTest(GitLabTestCase): get_user_should_succeed = True def set...
tests/sentry/integrations/gitlab/test_client.py
from __future__ import absolute_import import responses import pytest from sentry.auth.exceptions import IdentityNotValid from sentry.models import Identity from sentry.utils import json from .testutils import GitLabTestCase class GitlabRefreshAuthTest(GitLabTestCase): get_user_should_succeed = True def set...
0.668015
0.331093
import types import re import logging import buzz import utils.consts class PostAttributes(object): def __init__(self, post): self.attributes = {'lc':None, 'sc':None, 'mc':None, 'fc':None, 'mw':None, 'fw':None, 'ml':None, 'fl':None, 'op':None, 'first':None, 'last':None, 'caller':None, 'creator':utils.consts.BUZ...
lib/post_attributes.py
import types import re import logging import buzz import utils.consts class PostAttributes(object): def __init__(self, post): self.attributes = {'lc':None, 'sc':None, 'mc':None, 'fc':None, 'mw':None, 'fw':None, 'ml':None, 'fl':None, 'op':None, 'first':None, 'last':None, 'caller':None, 'creator':utils.consts.BUZ...
0.215351
0.152442
print("assignment #1\n") def format_address(address_string): x = address_string.split() return "house number {} on street named {}".format(x[0],x[1]+" "+x[2]) print(format_address("123 Main Street")) print(format_address("1001 1st Ave")) print(format_address("55 North Center Drive")) print("assignment #2\n") d...
c1_python-crash-course/4_strings-lists-and-dictionaries/_scripts/practice_3.py
print("assignment #1\n") def format_address(address_string): x = address_string.split() return "house number {} on street named {}".format(x[0],x[1]+" "+x[2]) print(format_address("123 Main Street")) print(format_address("1001 1st Ave")) print(format_address("55 North Center Drive")) print("assignment #2\n") d...
0.193681
0.318922
from datetime import timedelta from homeassistant.components.iotawatt.const import ATTR_LAST_UPDATE from homeassistant.components.sensor import ( ATTR_STATE_CLASS, DEVICE_CLASS_ENERGY, STATE_CLASS_MEASUREMENT, STATE_CLASS_TOTAL_INCREASING, ) from homeassistant.const import ( ATTR_DEVICE_CLASS, ...
tests/components/iotawatt/test_sensor.py
from datetime import timedelta from homeassistant.components.iotawatt.const import ATTR_LAST_UPDATE from homeassistant.components.sensor import ( ATTR_STATE_CLASS, DEVICE_CLASS_ENERGY, STATE_CLASS_MEASUREMENT, STATE_CLASS_TOTAL_INCREASING, ) from homeassistant.const import ( ATTR_DEVICE_CLASS, ...
0.73029
0.458531
from base_scraper import BaseScraper import requests def objectid(d): # Different datasets represent objectid in different ways return d.get('OBJECTID') or d['ObjectID'] def shelter_name(d): return d.get('SHELTER_NAME') or d['label'] def shelter_county(d): return d.get('COUNTY_PARISH') or d['count...
gis_scrapers.py
from base_scraper import BaseScraper import requests def objectid(d): # Different datasets represent objectid in different ways return d.get('OBJECTID') or d['ObjectID'] def shelter_name(d): return d.get('SHELTER_NAME') or d['label'] def shelter_county(d): return d.get('COUNTY_PARISH') or d['count...
0.372962
0.126111
import os from tqdm import tqdm from scipy import sparse from syn_net.utils.data_utils import * from syn_net.utils.prep_utils import organize if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument("-n", "--numbersave", type=int, default=999999999999, ...
scripts/st2steps.py
import os from tqdm import tqdm from scipy import sparse from syn_net.utils.data_utils import * from syn_net.utils.prep_utils import organize if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument("-n", "--numbersave", type=int, default=999999999999, ...
0.236516
0.092688
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the...
strawberryfields/configuration.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the...
0.880508
0.297802
#La funcion print se usa a menudo para imprimir variables print('Hola') #Python no tiene ningun comando para declarar variables mivariable = 0 x = 5.10 y = '<NAME>' x1= 5 y2 = 'David' #Las variables incluso pueden cambiarse de tipo de datos despues de haberle establecido anteriormente. x = 5 x = 'Wilder' print(x) ...
Clase 2/Clase2.py
#La funcion print se usa a menudo para imprimir variables print('Hola') #Python no tiene ningun comando para declarar variables mivariable = 0 x = 5.10 y = '<NAME>' x1= 5 y2 = 'David' #Las variables incluso pueden cambiarse de tipo de datos despues de haberle establecido anteriormente. x = 5 x = 'Wilder' print(x) ...
0.116425
0.398289
import os import sys import csv import cv2 from labels import labels_all def readlabels(filename): imagenames = [] if os.path.isfile(filename): with open(filename,'r') as f: lines = f.readlines() imagenames = [l.split(',')[0] for l in lines] return imagenames def printlabel...
labeltool.py
import os import sys import csv import cv2 from labels import labels_all def readlabels(filename): imagenames = [] if os.path.isfile(filename): with open(filename,'r') as f: lines = f.readlines() imagenames = [l.split(',')[0] for l in lines] return imagenames def printlabel...
0.090554
0.190272
from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from django_countries.fields import CountryField class UserAccount(models.Model): """ A user account that's linked to the user's authentication log-...
account/models.py
from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from django_countries.fields import CountryField class UserAccount(models.Model): """ A user account that's linked to the user's authentication log-...
0.628065
0.206914
import sys import os if sys.version_info[0] != 3: print("This script requires Python 3") exit(1) if 'py-json' not in sys.path: sys.path.append(os.path.join(os.path.abspath('..'), 'py-json')) import argparse from LANforge.lfcli_base import LFCliBase from LANforge.LFUtils import * from LANforge import LFUti...
py-scripts/test_ipv4_l4_ftp_urls_per_ten.py
import sys import os if sys.version_info[0] != 3: print("This script requires Python 3") exit(1) if 'py-json' not in sys.path: sys.path.append(os.path.join(os.path.abspath('..'), 'py-json')) import argparse from LANforge.lfcli_base import LFCliBase from LANforge.LFUtils import * from LANforge import LFUti...
0.209631
0.076132
import sklearn as sk import numpy as np np.random.seed(1337) import et_cleartk_io as ctk_io import nn_models import sys import os.path import dataset import keras as k from keras.utils.np_utils import to_categorical from keras.optimizers import RMSprop from keras.preprocessing.sequence import pad_sequences from keras....
ctakes-temporal/scripts/nn/lstm_train.py
import sklearn as sk import numpy as np np.random.seed(1337) import et_cleartk_io as ctk_io import nn_models import sys import os.path import dataset import keras as k from keras.utils.np_utils import to_categorical from keras.optimizers import RMSprop from keras.preprocessing.sequence import pad_sequences from keras....
0.443118
0.262145
from __future__ import annotations from typing import Any, Callable, List, NoReturn, Optional, Tuple class CPU: def __init__(self, vm: VM) -> None: self.vm = vm self.mem = vm.mem self.operations = { 1: (self.op_1, 4), 2: (self.op_2, 4), 3: (self.op_3, 2...
day-11/solution.py
from __future__ import annotations from typing import Any, Callable, List, NoReturn, Optional, Tuple class CPU: def __init__(self, vm: VM) -> None: self.vm = vm self.mem = vm.mem self.operations = { 1: (self.op_1, 4), 2: (self.op_2, 4), 3: (self.op_3, 2...
0.892058
0.460046
import sys from threading import Thread, Lock from typing import Callable, Iterable from warnings import warn import pandas as pd import numpy as np import multiprocessing class StoppableThread(Thread): def __init__( self, func: Callable, items: Iterable, callback: Callable = None,...
utils/parallelize.py
import sys from threading import Thread, Lock from typing import Callable, Iterable from warnings import warn import pandas as pd import numpy as np import multiprocessing class StoppableThread(Thread): def __init__( self, func: Callable, items: Iterable, callback: Callable = None,...
0.386995
0.101322
from functools import partial from typing import Any, Callable, DefaultDict, Hashable from wildebeest.constants import PathOrStr def report_output( func_input: Any, func: Callable, inpath: PathOrStr, log_dict: DefaultDict[str, dict], key: Hashable, ) -> Any: """ Add the output of a functi...
wildebeest/ops/helpers/report.py
from functools import partial from typing import Any, Callable, DefaultDict, Hashable from wildebeest.constants import PathOrStr def report_output( func_input: Any, func: Callable, inpath: PathOrStr, log_dict: DefaultDict[str, dict], key: Hashable, ) -> Any: """ Add the output of a functi...
0.866387
0.500793
from dataclasses import dataclass from typing import Optional, List from .client import Client from .room import Room from .content import ContentBase from .utils import ReactionRelation, MessageRelation @dataclass class EventBase: client: Client content: ContentBase type: str sender: str @class...
morpheus/core/events.py
from dataclasses import dataclass from typing import Optional, List from .client import Client from .room import Room from .content import ContentBase from .utils import ReactionRelation, MessageRelation @dataclass class EventBase: client: Client content: ContentBase type: str sender: str @class...
0.657758
0.080285
import datetime import flask import flask.views import sqlalchemy as sql import json import typing import app.api.helper_class as api_class import app.common.utils as utils import app.database as db_module import app.database.jwt as jwt_module import app.database.bca.profile as profile_module import app.database.bca.c...
app/api/bca/profile/profile_manage.py
import datetime import flask import flask.views import sqlalchemy as sql import json import typing import app.api.helper_class as api_class import app.common.utils as utils import app.database as db_module import app.database.jwt as jwt_module import app.database.bca.profile as profile_module import app.database.bca.c...
0.407687
0.074164
import collections from collections import defaultdict import pandas as pd from surprise import Dataset,KNNWithMeans, accuracy from surprise import Reader from surprise.model_selection import train_test_split # von https://surprise.readthedocs.io/en/stable/FAQ.html def get_top_n(predictions, n=10): """Return the to...
scripts/knn_amazon_rec.py
import collections from collections import defaultdict import pandas as pd from surprise import Dataset,KNNWithMeans, accuracy from surprise import Reader from surprise.model_selection import train_test_split # von https://surprise.readthedocs.io/en/stable/FAQ.html def get_top_n(predictions, n=10): """Return the to...
0.783658
0.417271
import numpy as np from libfmp.c3 import compute_strict_alignment_path_mask from synctoolbox.dtw.core import compute_warping_path from synctoolbox.dtw.cost import * from synctoolbox.feature.utils import shift_chroma_vectors def compute_optimal_chroma_shift(f_chroma1: np.ndarray, f_ch...
synctoolbox/dtw/utils.py
import numpy as np from libfmp.c3 import compute_strict_alignment_path_mask from synctoolbox.dtw.core import compute_warping_path from synctoolbox.dtw.cost import * from synctoolbox.feature.utils import shift_chroma_vectors def compute_optimal_chroma_shift(f_chroma1: np.ndarray, f_ch...
0.839306
0.593285
import abc from typing import Dict, Generic, Optional, TypeVar T = TypeVar("T") Header = Dict[str, str] DEFAULT_TIMEOUT = 10.0 class ClientError(Exception): """Basic exception raised by a client.""" pass class BaseHTTPClient(abc.ABC, Generic[T]): """Interface class for HTTP clients.""" _url: s...
src/noos_pyk/clients/base.py
import abc from typing import Dict, Generic, Optional, TypeVar T = TypeVar("T") Header = Dict[str, str] DEFAULT_TIMEOUT = 10.0 class ClientError(Exception): """Basic exception raised by a client.""" pass class BaseHTTPClient(abc.ABC, Generic[T]): """Interface class for HTTP clients.""" _url: s...
0.914257
0.182826
from wxpy import * from wxpy.utils import start_new_thread from config import * import itchat import re import time import os import platform import trigger import notice ''' 使用 cache 来缓存登陆信息,同时使用控制台登陆 ''' console_qr = (False if platform.system() == 'Windows' else True) bot = Bot('bot.pkl', console_qr=console_qr) bo...
bot.py
from wxpy import * from wxpy.utils import start_new_thread from config import * import itchat import re import time import os import platform import trigger import notice ''' 使用 cache 来缓存登陆信息,同时使用控制台登陆 ''' console_qr = (False if platform.system() == 'Windows' else True) bot = Bot('bot.pkl', console_qr=console_qr) bo...
0.121191
0.099514
from rest_framework import serializers from rest_framework.serializers import ModelSerializer, ValidationError from .models import Answer, Choice, Poll, Question, Score class ChoiceSerializer(ModelSerializer): class Meta: model = Choice fields = ['id', 'text'] class QuestionSerializer(ModelSeri...
polls/serializers.py
from rest_framework import serializers from rest_framework.serializers import ModelSerializer, ValidationError from .models import Answer, Choice, Poll, Question, Score class ChoiceSerializer(ModelSerializer): class Meta: model = Choice fields = ['id', 'text'] class QuestionSerializer(ModelSeri...
0.695338
0.308672
import logging import torch import torch.nn as nn import numpy as np from scipy.stats import ks_2samp def mass_ks_test(x, y): """mass-univariate two-sample kolmogorov-smirnov test Args: x ([type]): 1D numpy array y ([type]): 1D numpy array """ pvals = [] num_dims = x.shape...
core/muks.py
import logging import torch import torch.nn as nn import numpy as np from scipy.stats import ks_2samp def mass_ks_test(x, y): """mass-univariate two-sample kolmogorov-smirnov test Args: x ([type]): 1D numpy array y ([type]): 1D numpy array """ pvals = [] num_dims = x.shape...
0.760828
0.571587
from django.core.management.base import BaseCommand, CommandError import re import requests import pprint from pokemon_api.models import Pokemon, Stats, EvolutionChain URL_EVOLUTION = "https://pokeapi.co/api/v2/evolution-chain/" URL_POKEMON = "https://pokeapi.co/api/v2/pokemon/" class Command(BaseCommand): help ...
pokemon_api/management/commands/pokemon.py
from django.core.management.base import BaseCommand, CommandError import re import requests import pprint from pokemon_api.models import Pokemon, Stats, EvolutionChain URL_EVOLUTION = "https://pokeapi.co/api/v2/evolution-chain/" URL_POKEMON = "https://pokeapi.co/api/v2/pokemon/" class Command(BaseCommand): help ...
0.373419
0.23156
import os from datetime import datetime from math import inf from subprocess import run class Restructor(object): def __init__(self, shell='bash'): self.rules = {} def add(self, target, prereqs, recipe=None): """Need an indirect rule? Just omit the recipe.""" if target in self.rules...
test.py
import os from datetime import datetime from math import inf from subprocess import run class Restructor(object): def __init__(self, shell='bash'): self.rules = {} def add(self, target, prereqs, recipe=None): """Need an indirect rule? Just omit the recipe.""" if target in self.rules...
0.486332
0.14685
# Built-in Imports import webbrowser from typing import Optional, List import sys import time import os import signal import ctypes # Third Party Imports from loguru import logger import requests from bs4 import BeautifulSoup # Local Application Imports class GeneralUtils: """ This class implements some use...
GeneralUtils.py
# Built-in Imports import webbrowser from typing import Optional, List import sys import time import os import signal import ctypes # Third Party Imports from loguru import logger import requests from bs4 import BeautifulSoup # Local Application Imports class GeneralUtils: """ This class implements some use...
0.467575
0.188941
import logging import data import utils def main(): # logging.basicConfig(level=logging.DEBUG, format='%(message)s') logging.basicConfig(level=logging.WARN, format='%(message)s') trans_table = utils.translation_table() max_len = 128 - 4 - 3 with open('/home/michal/dos/PUDR/PUDR/DATA.PAS', mode=...
tools/encode_texts.py
import logging import data import utils def main(): # logging.basicConfig(level=logging.DEBUG, format='%(message)s') logging.basicConfig(level=logging.WARN, format='%(message)s') trans_table = utils.translation_table() max_len = 128 - 4 - 3 with open('/home/michal/dos/PUDR/PUDR/DATA.PAS', mode=...
0.090539
0.09277
import logging from django.conf import settings from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.views.generic import TemplateView, DetailView from django.urls import reverse_lazy from rdmo.core.exports import prettify_xml from rdmo.core.imports import handle_...
rdmo/questions/views.py
import logging from django.conf import settings from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.views.generic import TemplateView, DetailView from django.urls import reverse_lazy from rdmo.core.exports import prettify_xml from rdmo.core.imports import handle_...
0.379493
0.063048
import requests from .. import LAUNCHKEY_PRODUCTION from .base import APIResponse, APIErrorResponse class RequestsTransport(object): """ Transport class for performing HTTP based queries using the requests library. """ url = LAUNCHKEY_PRODUCTION testing = False verify_ssl = True de...
launchkey/transports/http.py
import requests from .. import LAUNCHKEY_PRODUCTION from .base import APIResponse, APIErrorResponse class RequestsTransport(object): """ Transport class for performing HTTP based queries using the requests library. """ url = LAUNCHKEY_PRODUCTION testing = False verify_ssl = True de...
0.792665
0.179099
import helpers class Point(): def __init__(self, x, y, dx, dy): self.x = x self.y = y self.dx = dx self.dy = dy def __repr__(self): return '({}, {} -> {}, {})'.format(self.x, self.y, self.dx, self.dy) def tick(self): self.x = self.x + self.dx self....
days/day10.py
import helpers class Point(): def __init__(self, x, y, dx, dy): self.x = x self.y = y self.dx = dx self.dy = dy def __repr__(self): return '({}, {} -> {}, {})'.format(self.x, self.y, self.dx, self.dy) def tick(self): self.x = self.x + self.dx self....
0.746231
0.371621
from typing import List, Dict from app.types import Player from app.players import PlayerID, ConstructorID from app.types import DriverScore, PlayerOverride, Override from app.config import COSTS, CONSTRUCTOR_DRIVER_MAP class LineupOptimizationModelSpec: def __init__( self, driver_scores:...
app/model_spec.py
from typing import List, Dict from app.types import Player from app.players import PlayerID, ConstructorID from app.types import DriverScore, PlayerOverride, Override from app.config import COSTS, CONSTRUCTOR_DRIVER_MAP class LineupOptimizationModelSpec: def __init__( self, driver_scores:...
0.563018
0.199035
import sys, os from labMTsimple.storyLab import * import codecs ## handle utf8 if __name__ == '__main__': lang = 'english' labMT,labMTvector,labMTwordList = emotionFileReader(stopval=0.0,lang=lang,returnVector=True) ## take a look at these guys print('the word laughter in the hash has the data:') print(la...
labMT-simple/examples/example-002.py
import sys, os from labMTsimple.storyLab import * import codecs ## handle utf8 if __name__ == '__main__': lang = 'english' labMT,labMTvector,labMTwordList = emotionFileReader(stopval=0.0,lang=lang,returnVector=True) ## take a look at these guys print('the word laughter in the hash has the data:') print(la...
0.161552
0.175609
import numpy as np import pytest from ladim_plugins.chemicals import gridforce, IBM class Test_nearest_unmasked: def test_correct_when_all_unmasked(self): mask = np.zeros((4, 3)) i = np.array([1, 1, 2]) j = np.array([2, 3, 3]) ii, jj = gridforce.nearest_unmasked(mask, i, j) ...
ladim_plugins/chemicals/test_chemicals.py
import numpy as np import pytest from ladim_plugins.chemicals import gridforce, IBM class Test_nearest_unmasked: def test_correct_when_all_unmasked(self): mask = np.zeros((4, 3)) i = np.array([1, 1, 2]) j = np.array([2, 3, 3]) ii, jj = gridforce.nearest_unmasked(mask, i, j) ...
0.621656
0.849222
import sys sys.path.append("../..") import numpy as np import torch import matplotlib.pyplot as plt from pyoptmat import ode torch.set_default_tensor_type(torch.DoubleTensor) class VanderPolODE(torch.nn.Module): """ From Manichev et al 2019 x0 = [-1, 1] t = [0, 4.2*mu) """ def __ini...
examples/ode/vanderpohl.py
import sys sys.path.append("../..") import numpy as np import torch import matplotlib.pyplot as plt from pyoptmat import ode torch.set_default_tensor_type(torch.DoubleTensor) class VanderPolODE(torch.nn.Module): """ From Manichev et al 2019 x0 = [-1, 1] t = [0, 4.2*mu) """ def __ini...
0.803405
0.6806
from time import sleep try: import RPi.GPIO as gpio except ImportError: class gpio(object): """@brief Dummy class to allow testing on non Raspberry PI platform.""" BCM = 1 OUT = 1 LOW = 0 HIGH = 1 IN = 0 @staticmethod def setmode(mode): ...
ogsolar/libs/gpio_control.py
from time import sleep try: import RPi.GPIO as gpio except ImportError: class gpio(object): """@brief Dummy class to allow testing on non Raspberry PI platform.""" BCM = 1 OUT = 1 LOW = 0 HIGH = 1 IN = 0 @staticmethod def setmode(mode): ...
0.6137
0.160003
import mock from rally.benchmark.scenarios.quotas import utils from tests.benchmark.scenarios import test_base from tests import fakes from tests import test class QuotasScenarioTestCase(test.TestCase): def setUp(self): super(QuotasScenarioTestCase, self).setUp() def _test_atomic_action_timer(self...
tests/benchmark/scenarios/quotas/test_utils.py
import mock from rally.benchmark.scenarios.quotas import utils from tests.benchmark.scenarios import test_base from tests import fakes from tests import test class QuotasScenarioTestCase(test.TestCase): def setUp(self): super(QuotasScenarioTestCase, self).setUp() def _test_atomic_action_timer(self...
0.612078
0.227625
from __future__ import division, print_function, absolute_import import numpy as np # Expansion of polar term aij = np.array([[0.3043504, 0.9534641, -1.1610080], [-0.1358588, -1.8396383, 4.5258607], [1.4493329, 2.0131180, 0.9751222], [0.3556977, -7.3724958, -12.281038], ...
sgtpy/vrmie_pure/polarGV.py
from __future__ import division, print_function, absolute_import import numpy as np # Expansion of polar term aij = np.array([[0.3043504, 0.9534641, -1.1610080], [-0.1358588, -1.8396383, 4.5258607], [1.4493329, 2.0131180, 0.9751222], [0.3556977, -7.3724958, -12.281038], ...
0.68763
0.509581
from enum import Enum from pathlib import Path from little_cheesemonger._types import ConfigurationType class Architecture(str, Enum): x86_64 = "x86_64" class Platform(str, Enum): manylinux1 = "manylinux1" manylinux2010 = "manylinux2010" manylinux2014 = "manylinux2014" class PythonVersion(str, En...
little_cheesemonger/_constants.py
from enum import Enum from pathlib import Path from little_cheesemonger._types import ConfigurationType class Architecture(str, Enum): x86_64 = "x86_64" class Platform(str, Enum): manylinux1 = "manylinux1" manylinux2010 = "manylinux2010" manylinux2014 = "manylinux2014" class PythonVersion(str, En...
0.591369
0.080647
import json from alipay.aop.api.constant.ParamConstants import * class SchoolInfo(object): def __init__(self): self._address = None self._city_code = None self._inst_id = None self._inst_name = None self._inst_std_code = None self._province_code = None sel...
alipay/aop/api/domain/SchoolInfo.py
import json from alipay.aop.api.constant.ParamConstants import * class SchoolInfo(object): def __init__(self): self._address = None self._city_code = None self._inst_id = None self._inst_name = None self._inst_std_code = None self._province_code = None sel...
0.58439
0.082254
# Copyright 2019 AntiCompositeNumber # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writ...
tests/test_hyphenator.py
# Copyright 2019 AntiCompositeNumber # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writ...
0.745954
0.381652
import ast import os import markdown def iter_docstrings(root): if isinstance(root, ast.ClassDef): yield root.name, ast.get_docstring(root) yield from iter_docstrings(root.body) elif isinstance(root, ast.Module): yield None, ast.get_docstring(root) yield from iter_docstrings(r...
doc_note_untangler/build.py
import ast import os import markdown def iter_docstrings(root): if isinstance(root, ast.ClassDef): yield root.name, ast.get_docstring(root) yield from iter_docstrings(root.body) elif isinstance(root, ast.Module): yield None, ast.get_docstring(root) yield from iter_docstrings(r...
0.517083
0.302906
import unittest import congestionfinder.bpsdetector import logging logging.getLogger().level = logging.DEBUG class TestBPSDetector(unittest.TestCase): def test_getBPSCode(self): logging.debug("Starting test_getSpaceToSpaceIndex()") input = "00D00C03405B18200005" expected = inpu...
tests/test_bpsdetector.py
import unittest import congestionfinder.bpsdetector import logging logging.getLogger().level = logging.DEBUG class TestBPSDetector(unittest.TestCase): def test_getBPSCode(self): logging.debug("Starting test_getSpaceToSpaceIndex()") input = "00D00C03405B18200005" expected = inpu...
0.463201
0.29963
from dataclasses import dataclass, field from typing import Dict, List, NamedTuple, Tuple from covid_shared import workflow from covid_model_seiir_pipeline.lib import ( utilities, ) class __RegressionJobs(NamedTuple): regression: str = 'beta_regression' hospital_correction_factors: str = 'hospital_corre...
src/covid_model_seiir_pipeline/pipeline/regression/specification.py
from dataclasses import dataclass, field from typing import Dict, List, NamedTuple, Tuple from covid_shared import workflow from covid_model_seiir_pipeline.lib import ( utilities, ) class __RegressionJobs(NamedTuple): regression: str = 'beta_regression' hospital_correction_factors: str = 'hospital_corre...
0.944106
0.550426
import json import unittest from unittest import mock import responses import yaml from tempfile import TemporaryDirectory from pathlib import Path import pytest from cumulusci.tasks.bulkdata import GenerateMapping from cumulusci.core.exceptions import TaskOptionsError from cumulusci.tasks.bulkdata.generate_mapping i...
cumulusci/tasks/bulkdata/tests/test_generatemapping.py
import json import unittest from unittest import mock import responses import yaml from tempfile import TemporaryDirectory from pathlib import Path import pytest from cumulusci.tasks.bulkdata import GenerateMapping from cumulusci.core.exceptions import TaskOptionsError from cumulusci.tasks.bulkdata.generate_mapping i...
0.525612
0.463626
from marshmallow_jsonapi import Schema, fields from marshmallow import validate from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy.exc import SQLAlchemyError db = SQLAlchemy(session_options={"autoflush": False}) class CRUD(): def add(self, resource): db.session.add(resource) return db...
app/haulers/models.py
from marshmallow_jsonapi import Schema, fields from marshmallow import validate from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy.exc import SQLAlchemyError db = SQLAlchemy(session_options={"autoflush": False}) class CRUD(): def add(self, resource): db.session.add(resource) return db...
0.428712
0.049451
help = "List dependencies" options = [ { "name": ["-g", "--global"], "dest": "global_", "action": "store_true", "help": "List globally installed packages" }, { "name": ["--outdated"], "action": "store_true", "help": "List outdated packages only" } ...
vpip/commands/list.py
help = "List dependencies" options = [ { "name": ["-g", "--global"], "dest": "global_", "action": "store_true", "help": "List globally installed packages" }, { "name": ["--outdated"], "action": "store_true", "help": "List outdated packages only" } ...
0.411584
0.106505
import asyncio import json import pytest from maggma.cli.distributed import find_port, manager, worker from maggma.core import Builder from zmq import REP, REQ import zmq.asyncio as zmq import socket as pysocket # TODO: Timeout errors? HOSTNAME = pysocket.gethostname() class DummyBuilderWithNoPrechunk(Builder): ...
tests/cli/test_distributed.py
import asyncio import json import pytest from maggma.cli.distributed import find_port, manager, worker from maggma.core import Builder from zmq import REP, REQ import zmq.asyncio as zmq import socket as pysocket # TODO: Timeout errors? HOSTNAME = pysocket.gethostname() class DummyBuilderWithNoPrechunk(Builder): ...
0.236428
0.27295
import logging from ophyd.areadetector.base import EpicsSignalWithRBV, NDDerivedSignal from ophyd.device import Component as Cpt from ophyd.signal import EpicsSignal, EpicsSignalRO from pcdsdevices.areadetector.detectors import PCDSAreaDetectorTyphosTrigger logger = logging.getLogger(__name__) class ThorlabsWfs40(...
pcdsdevices/lasers/thorlabsWFS.py
import logging from ophyd.areadetector.base import EpicsSignalWithRBV, NDDerivedSignal from ophyd.device import Component as Cpt from ophyd.signal import EpicsSignal, EpicsSignalRO from pcdsdevices.areadetector.detectors import PCDSAreaDetectorTyphosTrigger logger = logging.getLogger(__name__) class ThorlabsWfs40(...
0.689515
0.538437
import tweepy, sys, os from webbrowser import open as site # For the auth token import settings keysPath = "keys.txt" if len(sys.argv) == 1: print("Arguments required!") sys.exit() numbers = eval("".join(sys.argv[1:])) auth = tweepy.OAuthHandler(settings.API_KEY, settings.API_SECRET) if os.path.exists(keysPath):...
main.py
import tweepy, sys, os from webbrowser import open as site # For the auth token import settings keysPath = "keys.txt" if len(sys.argv) == 1: print("Arguments required!") sys.exit() numbers = eval("".join(sys.argv[1:])) auth = tweepy.OAuthHandler(settings.API_KEY, settings.API_SECRET) if os.path.exists(keysPath):...
0.139426
0.079424
import os import sys import schemasim.schemas.l0_schema_templates as st import schemasim.schemas.l1_geometric_primitives as gp import schemasim.schemas.l2_geometric_primitive_relations as gpr import schemasim.schemas.l3_primitive_movement as pm import schemasim.schemas.l3_location as location import numpy as np clas...
schemasim/schemas/l4_path.py
import os import sys import schemasim.schemas.l0_schema_templates as st import schemasim.schemas.l1_geometric_primitives as gp import schemasim.schemas.l2_geometric_primitive_relations as gpr import schemasim.schemas.l3_primitive_movement as pm import schemasim.schemas.l3_location as location import numpy as np clas...
0.305179
0.234779
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import pytest from flair.embeddings import WordEmbeddings, TokenEmbeddings, StackedEmbeddings, DocumentLSTMEmbeddings, DocumentPoolEmbeddings, FlairEmbeddings from flair.d...
tests/test_embeddings.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import pytest from flair.embeddings import WordEmbeddings, TokenEmbeddings, StackedEmbeddings, DocumentLSTMEmbeddings, DocumentPoolEmbeddings, FlairEmbeddings from flair.d...
0.795022
0.333246
import pprint import json class Node(object): def __init__(self, name, value=None): self._name=name self._value=value @property def name(self): return self._name @name.setter def name(self, n): self._name = n @property def value(self): ...
acrilib/acrilib/idioms/digraph.py
import pprint import json class Node(object): def __init__(self, name, value=None): self._name=name self._value=value @property def name(self): return self._name @name.setter def name(self, n): self._name = n @property def value(self): ...
0.39222
0.142083
from datetime import timedelta from django.test import tag, TestCase from django.urls import reverse from django.utils import timezone from aidants_connect_web.tests.factories import ( AidantFactory, AutorisationFactory, MandatFactory, UsagerFactory, ) from aidants_connect_web.views.usagers import _g...
aidants_connect_web/tests/test_views/test_usagers.py
from datetime import timedelta from django.test import tag, TestCase from django.urls import reverse from django.utils import timezone from aidants_connect_web.tests.factories import ( AidantFactory, AutorisationFactory, MandatFactory, UsagerFactory, ) from aidants_connect_web.views.usagers import _g...
0.543833
0.190009
import os from os.path import join as pjoin from setuptools import setup from distutils.extension import Extension from Cython.Distutils import build_ext import numpy def find_in_path(name, path): """Find a file in a search path""" # Adapted fom http://code.activestate.com/recipes/52224 for dir in path.sp...
setup.py
import os from os.path import join as pjoin from setuptools import setup from distutils.extension import Extension from Cython.Distutils import build_ext import numpy def find_in_path(name, path): """Find a file in a search path""" # Adapted fom http://code.activestate.com/recipes/52224 for dir in path.sp...
0.482185
0.144722
import numpy as np from sklearn.base import BaseEstimator, TransformerMixin from sklearn.utils.validation import ( check_is_fitted, check_random_state, ) from sklearn.preprocessing import normalize import scipy.sparse from sklearn.utils.extmath import randomized_svd, svd_flip from scipy.sparse.linalg import svd...
vectorizers/transformers/count_feature_compression.py
import numpy as np from sklearn.base import BaseEstimator, TransformerMixin from sklearn.utils.validation import ( check_is_fitted, check_random_state, ) from sklearn.preprocessing import normalize import scipy.sparse from sklearn.utils.extmath import randomized_svd, svd_flip from scipy.sparse.linalg import svd...
0.953611
0.679531
from RFEM.initModel import Model, GetAddonStatus from RFEM.enums import AddOn class MeshSettings(): ComonMeshConfig: dict = { 'general_target_length_of_fe': None, 'general_maximum_distance_between_node_and_line': None, 'general_maximum_number_of_mesh_nodes': None, 'members_number_of...
RFEM/Calculate/meshSettings.py
from RFEM.initModel import Model, GetAddonStatus from RFEM.enums import AddOn class MeshSettings(): ComonMeshConfig: dict = { 'general_target_length_of_fe': None, 'general_maximum_distance_between_node_and_line': None, 'general_maximum_number_of_mesh_nodes': None, 'members_number_of...
0.772702
0.136608
import json from collections import defaultdict class Via3Json(object): def __init_load(self, json_path): with open(json_path, 'r', encoding='utf-8') as json_fd: self.ann_dict = json.load(json_fd) self.projects = self.ann_dict['project'] self.configs = self.ann_dict['config'] ...
mywork/via3_tool.py
import json from collections import defaultdict class Via3Json(object): def __init_load(self, json_path): with open(json_path, 'r', encoding='utf-8') as json_fd: self.ann_dict = json.load(json_fd) self.projects = self.ann_dict['project'] self.configs = self.ann_dict['config'] ...
0.293911
0.125306
from enum import IntEnum from typing import Union, Tuple from .address import b58_address_to_hash160, hash160_to_b58_address from .coind import Coind from .opcodes import Opcodes, opcode_search from .segwit_addr import encode class ParseOrUnParseError(Exception): pass class ScriptType(IntEnum): Pubkey = 0...
atomicswap/script.py
from enum import IntEnum from typing import Union, Tuple from .address import b58_address_to_hash160, hash160_to_b58_address from .coind import Coind from .opcodes import Opcodes, opcode_search from .segwit_addr import encode class ParseOrUnParseError(Exception): pass class ScriptType(IntEnum): Pubkey = 0...
0.516352
0.303435
from datetime import datetime from unittest.mock import Mock import pytest from file_writer_control.JobHandler import JobHandler from file_writer_control.JobStatus import JobState, JobStatus from file_writer_control.WriteJob import WriteJob def test_default_members(): worker_finder_mock = Mock() under_test ...
tests/test_job_handler.py
from datetime import datetime from unittest.mock import Mock import pytest from file_writer_control.JobHandler import JobHandler from file_writer_control.JobStatus import JobState, JobStatus from file_writer_control.WriteJob import WriteJob def test_default_members(): worker_finder_mock = Mock() under_test ...
0.578805
0.393793
import math import sys def main(filepath): with open(filepath, 'r') as f: for line in f.readlines(): if line: line = line.strip() line = line.split(';') n = int(line[0]) grid = map(int, line[1].split(','...
python/moderate/(78) sudoku.py
import math import sys def main(filepath): with open(filepath, 'r') as f: for line in f.readlines(): if line: line = line.strip() line = line.split(';') n = int(line[0]) grid = map(int, line[1].split(','...
0.208662
0.203312
from django.conf import settings from django.db import migrations, models from django.db.models.signals import post_migrate def assing_permissions(apps, schema_editor): def on_migrations_complete(sender=None, **kwargs): Group = apps.get_model("auth", "Group") Permission = apps.get_model("auth", "...
saleor/channel/migrations/0001_initial.py
from django.conf import settings from django.db import migrations, models from django.db.models.signals import post_migrate def assing_permissions(apps, schema_editor): def on_migrations_complete(sender=None, **kwargs): Group = apps.get_model("auth", "Group") Permission = apps.get_model("auth", "...
0.692226
0.120957