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 json from json.decoder import JSONDecodeError import jwt import requests from flask import request, current_app, jsonify, g from jwt import InvalidSignatureError, InvalidAudienceError, DecodeError from requests.exceptions import ( ConnectionError, InvalidURL, SSLError, HTTPError ) from api.erro...
code/api/utils.py
import json from json.decoder import JSONDecodeError import jwt import requests from flask import request, current_app, jsonify, g from jwt import InvalidSignatureError, InvalidAudienceError, DecodeError from requests.exceptions import ( ConnectionError, InvalidURL, SSLError, HTTPError ) from api.erro...
0.414899
0.166134
class RenderTree(object): """A tree interface where the only responsibility of subclasses is to define what it means to render. Calling str on a RenderTree will implictly call render.""" def __str__(self): return self.render() def render(self, prefix=''): raise NotImplemented("Implemen...
pcol.py
class RenderTree(object): """A tree interface where the only responsibility of subclasses is to define what it means to render. Calling str on a RenderTree will implictly call render.""" def __str__(self): return self.render() def render(self, prefix=''): raise NotImplemented("Implemen...
0.942718
0.638413
from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * import math import random colors = [] width = height = 900 eps: int iterations: int umin: float umax: float vmin: float vmax: float method: int creal: float cimag: float window: GLint def myReshape(width, height): glMatrixMode(GL_PROJECTI...
lab8/zad8.py
from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * import math import random colors = [] width = height = 900 eps: int iterations: int umin: float umax: float vmin: float vmax: float method: int creal: float cimag: float window: GLint def myReshape(width, height): glMatrixMode(GL_PROJECTI...
0.389198
0.180053
import os from test.matcher import JSPECTestMatcher os.environ["TEST_OBJECT"] = '{"hello": "world"}' os.environ["TEST_ARRAY"] = '["hello", "world", 123]' os.environ["TEST_STRING"] = '"Hello World!"' os.environ["TEST_INT"] = '456' os.environ["TEST_REAL"] = '7.89' os.environ["TEST_BOOLEAN"] = 'true' os.environ["TEST_NU...
test/matcher/macro.py
import os from test.matcher import JSPECTestMatcher os.environ["TEST_OBJECT"] = '{"hello": "world"}' os.environ["TEST_ARRAY"] = '["hello", "world", 123]' os.environ["TEST_STRING"] = '"Hello World!"' os.environ["TEST_INT"] = '456' os.environ["TEST_REAL"] = '7.89' os.environ["TEST_BOOLEAN"] = 'true' os.environ["TEST_NU...
0.617051
0.405331
import frappe from frappe.model.document import Document def wh_qnt(qt,warehouse): t=0 wh_qt=frappe.db.get_value("WH",{"wh_name":warehouse},"wh_qt") if(wh_qt-qt>=0): #frappe.db.set_value("WH",{"wh_name":warehouse},"wh_qt",wh_qt-qt) t=(wh_qt-qt) return t def add(warehouse,item,qt): C_WH_doc=frappe.get_doc...
whms/whms/doctype/stock_entry/stock_entry.py
import frappe from frappe.model.document import Document def wh_qnt(qt,warehouse): t=0 wh_qt=frappe.db.get_value("WH",{"wh_name":warehouse},"wh_qt") if(wh_qt-qt>=0): #frappe.db.set_value("WH",{"wh_name":warehouse},"wh_qt",wh_qt-qt) t=(wh_qt-qt) return t def add(warehouse,item,qt): C_WH_doc=frappe.get_doc...
0.143128
0.105856
import datetime import json import os import sys import tempfile import boto3 import torch import yaml from sagemaker_inference import content_types, errors # path munging to access the neighboring YAEDP repo HERE = os.path.dirname(os.path.realpath(__file__)) YAEDP_ROOT = os.path.join(HERE, 'Yet-Another-EfficientDet...
storyblocks/object_detection/model/code/inference.py
import datetime import json import os import sys import tempfile import boto3 import torch import yaml from sagemaker_inference import content_types, errors # path munging to access the neighboring YAEDP repo HERE = os.path.dirname(os.path.realpath(__file__)) YAEDP_ROOT = os.path.join(HERE, 'Yet-Another-EfficientDet...
0.534127
0.153486
import os os.system('pip install colorama') os.system('pip install hashlib') time.sleep(2) import hashlib import colorama import time from bunner import * import random banner() os.system('termux-open-url https://t.me/elf_security_cyber') time.sleep(5) while True: print(f"{colorama.Fore.RED}[{c...
hasher.py
import os os.system('pip install colorama') os.system('pip install hashlib') time.sleep(2) import hashlib import colorama import time from bunner import * import random banner() os.system('termux-open-url https://t.me/elf_security_cyber') time.sleep(5) while True: print(f"{colorama.Fore.RED}[{c...
0.07164
0.492249
from utils import * def imgs_from_category(dataset): filename = os.path.join(set_dir, dataset + ".txt") df = pd.read_csv( filename, delim_whitespace=True, header=None, names=['filename']) return df def imgs_from_category_as_list(dataset): df = imgs_from_category(datase...
src/texture_analisys/loadingDataset.py
from utils import * def imgs_from_category(dataset): filename = os.path.join(set_dir, dataset + ".txt") df = pd.read_csv( filename, delim_whitespace=True, header=None, names=['filename']) return df def imgs_from_category_as_list(dataset): df = imgs_from_category(datase...
0.114233
0.142799
def parse_officer(line): """ Summary: Parse a line of officer data from the FTP Inputs: line of raw ftp data Outputs: a dictionary of data parsed from the line """ results = dict() results['appointed_to_company_number'] = line[0:8] results['record_type'] = line[8] results['a...
src/parse_ftp.py
def parse_officer(line): """ Summary: Parse a line of officer data from the FTP Inputs: line of raw ftp data Outputs: a dictionary of data parsed from the line """ results = dict() results['appointed_to_company_number'] = line[0:8] results['record_type'] = line[8] results['a...
0.481698
0.375993
import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../varity'))) sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../varity/common'))) import varity import cfg import random import shutil import socket import json def configure(): cfg.MAX_EX...
tests/test_driver.py
import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../varity'))) sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../varity/common'))) import varity import cfg import random import shutil import socket import json def configure(): cfg.MAX_EX...
0.158923
0.121399
import pytest from app.models import Resource, Language, Category from tests.conftest import module_client, module_db from configs import PaginatorConfig # TODO: We need negative unit tests (what happens when bad data is sent) def test_get_resources(module_client, module_db): client = module_client response ...
tests/unit/test_persistent_routes.py
import pytest from app.models import Resource, Language, Category from tests.conftest import module_client, module_db from configs import PaginatorConfig # TODO: We need negative unit tests (what happens when bad data is sent) def test_get_resources(module_client, module_db): client = module_client response ...
0.245447
0.273093
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from typing import Optional, Iterator, Any from jina import Document from jina.executors.indexers.keyvalue import BinaryPbIndexer class LevelDBIndexer(BinaryPbIndexer): """ :class:`LevelDBIndexer` use `Leve...
indexers/keyvalue/LevelDBIndexer/__init__.py
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" from typing import Optional, Iterator, Any from jina import Document from jina.executors.indexers.keyvalue import BinaryPbIndexer class LevelDBIndexer(BinaryPbIndexer): """ :class:`LevelDBIndexer` use `Leve...
0.886807
0.133868
import csv import pyproj class TileMapper: """Tile Mapper loads a CSV file containing various geographic tiles and """ tile_list = [] PIXELS = 256 def __init__(self,pixels=256): """pixels specifies the tile resolution Program assumes that we're dealing with square tiles""" ...
tools/tile_mapper/tile_mapper.py
import csv import pyproj class TileMapper: """Tile Mapper loads a CSV file containing various geographic tiles and """ tile_list = [] PIXELS = 256 def __init__(self,pixels=256): """pixels specifies the tile resolution Program assumes that we're dealing with square tiles""" ...
0.573081
0.575767
from PySide2 import QtGui, QtCore, QtWidgets from .signal_def import signal_def from .signal import Signal from .scrollbar import ScrollBar from .xaxis import XAxis from .settings_widget import SettingsWidget from .font_resizer import FontResizer from .ymarker_manager import YMarkerManager from joulescope_ui.file_dial...
joulescope_ui/widgets/waveform/waveform.py
from PySide2 import QtGui, QtCore, QtWidgets from .signal_def import signal_def from .signal import Signal from .scrollbar import ScrollBar from .xaxis import XAxis from .settings_widget import SettingsWidget from .font_resizer import FontResizer from .ymarker_manager import YMarkerManager from joulescope_ui.file_dial...
0.715523
0.075653
import datetime from . import models class ItemAlreadyExists(Exception): pass class ItemDoesNotExist(Exception): pass class DiscountMixin(object): pass class ShopBasketContainer(object): """ Class for operate basket in session. Using request.session dict, where find BASKET_ID...
src/basket/basket.py
import datetime from . import models class ItemAlreadyExists(Exception): pass class ItemDoesNotExist(Exception): pass class DiscountMixin(object): pass class ShopBasketContainer(object): """ Class for operate basket in session. Using request.session dict, where find BASKET_ID...
0.501465
0.223864
import matplotlib.pyplot as plt import numpy as np from .base import BaseProcessor from ..plotter import OneDimPlotter, TwoDimPlotter, cdf_pdf class ImageProcessor(BaseProcessor): """ Process the information related to image, get several statistical distribution. Args: data (dict): Data to be proces...
volkscv/analyzer/statistics/processor/image_processor.py
import matplotlib.pyplot as plt import numpy as np from .base import BaseProcessor from ..plotter import OneDimPlotter, TwoDimPlotter, cdf_pdf class ImageProcessor(BaseProcessor): """ Process the information related to image, get several statistical distribution. Args: data (dict): Data to be proces...
0.907866
0.564279
import argparse import fileinput import re from typing import Dict, Iterator, Sequence, Tuple from itertools import chain, permutations def _all_sorted_subsets(s: Sequence[str]) -> Iterator[Tuple[str, ...]]: for i in range(1, len(s) + 1): for p in permutations(s, i): yield p def syn_effects...
tools/generate.py
import argparse import fileinput import re from typing import Dict, Iterator, Sequence, Tuple from itertools import chain, permutations def _all_sorted_subsets(s: Sequence[str]) -> Iterator[Tuple[str, ...]]: for i in range(1, len(s) + 1): for p in permutations(s, i): yield p def syn_effects...
0.519765
0.161485
from FichaDB import FichaDB class Ficha(object): def __init__(self, lista=None): if lista is None: self.lista = [] * 129 self.info = {} def insertFicha(self): banco = FichaDB() try: c = banco.conexao.cursor() c.execute(" insert into fich...
Ficha.py
from FichaDB import FichaDB class Ficha(object): def __init__(self, lista=None): if lista is None: self.lista = [] * 129 self.info = {} def insertFicha(self): banco = FichaDB() try: c = banco.conexao.cursor() c.execute(" insert into fich...
0.085294
0.115063
import sys import struct import marshal from osmxmlparser import Node, Way, OSMXMLParser def write_obj(fp, obj): b = marshal.dumps(obj) fp.write('+'+struct.pack('<I', len(b))+b) return def getname(names): name = None for (k,v) in names: if k == 'name' and name is None: name = v...
parseosm.py
import sys import struct import marshal from osmxmlparser import Node, Way, OSMXMLParser def write_obj(fp, obj): b = marshal.dumps(obj) fp.write('+'+struct.pack('<I', len(b))+b) return def getname(names): name = None for (k,v) in names: if k == 'name' and name is None: name = v...
0.15633
0.06389
from app import db, login_manager from flask_login import UserMixin from datetime import datetime @login_manager.user_loader def load_user(id): return User.query.get(int(id)) class Marking(db.Model): __tablename__ = "marking" marker_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True) marked_id ...
app/models.py
from app import db, login_manager from flask_login import UserMixin from datetime import datetime @login_manager.user_loader def load_user(id): return User.query.get(int(id)) class Marking(db.Model): __tablename__ = "marking" marker_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True) marked_id ...
0.377885
0.043711
from __future__ import unicode_literals import django.core.validators from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("contenttypes", "0001_initial"), ...
apps/shop/migrations/0001_initial.py
from __future__ import unicode_literals import django.core.validators from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("contenttypes", "0001_initial"), ...
0.594198
0.147709
import common def FullOTA_InstallEnd(info): OTA_InstallEnd(info, False) def IncrementalOTA_InstallEnd(info): OTA_InstallEnd(info, True) def AddImageOnly(info, basename, incremental, firmware): if incremental: input_zip = info.source_zip else: input_zip = info.input_zip if firmware: data = inpu...
releasetools.py
import common def FullOTA_InstallEnd(info): OTA_InstallEnd(info, False) def IncrementalOTA_InstallEnd(info): OTA_InstallEnd(info, True) def AddImageOnly(info, basename, incremental, firmware): if incremental: input_zip = info.source_zip else: input_zip = info.input_zip if firmware: data = inpu...
0.159512
0.16896
import numpy as n, pylab as p from scipy import stats as st a=st.norm(0,1) b=st.norm(0.1,1) domain=n.linspace(-4,4,10000) avals=a.cdf(domain) bvals=b.cdf(domain) diffN=n.abs(avals-bvals).max() a=st.norm(0,1) b=st.norm(0,1.2) domain=n.linspace(-4,4,10000) avals=a.cdf(domain) bvals=b.cdf(domain) diffN2=n.abs(avals-bvals...
tests/testTheoreticalCumulatives.py
import numpy as n, pylab as p from scipy import stats as st a=st.norm(0,1) b=st.norm(0.1,1) domain=n.linspace(-4,4,10000) avals=a.cdf(domain) bvals=b.cdf(domain) diffN=n.abs(avals-bvals).max() a=st.norm(0,1) b=st.norm(0,1.2) domain=n.linspace(-4,4,10000) avals=a.cdf(domain) bvals=b.cdf(domain) diffN2=n.abs(avals-bvals...
0.344333
0.383295
import time everything_start_time = time.time() import os import subprocess import json import argparse import cv2 import numpy import SRers parser = argparse.ArgumentParser() # Input/output file parser.add_argument('-i', '--input', # Input file type=str, help='path of vid...
run.py
import time everything_start_time = time.time() import os import subprocess import json import argparse import cv2 import numpy import SRers parser = argparse.ArgumentParser() # Input/output file parser.add_argument('-i', '--input', # Input file type=str, help='path of vid...
0.334263
0.071786
import torch from nitorch.core import py, utils from nitorch import io, spatial from .cnn import NeuriteUNet from .norm import BatchNorm from .conv import Conv from .spatial import GridExp, GridResize, GridPull from ..base import Module class SynthUNet(NeuriteUNet): """Base for SynthStuff networks This archi...
nitorch/nn/modules/pretrained.py
import torch from nitorch.core import py, utils from nitorch import io, spatial from .cnn import NeuriteUNet from .norm import BatchNorm from .conv import Conv from .spatial import GridExp, GridResize, GridPull from ..base import Module class SynthUNet(NeuriteUNet): """Base for SynthStuff networks This archi...
0.868674
0.325641
# Atom regex : ([A-Za-z]{1,}) dictionary = { "adjectives": [ # Source : https://enchantedlearning.com/wordlist/adjectivesforpeople.shtml "able", # "abnormal", "adventurous", "affectionate", "agile", "agreeable", "alert", "amazing", ...
sami/lib/dictionary.py
# Atom regex : ([A-Za-z]{1,}) dictionary = { "adjectives": [ # Source : https://enchantedlearning.com/wordlist/adjectivesforpeople.shtml "able", # "abnormal", "adventurous", "affectionate", "agile", "agreeable", "alert", "amazing", ...
0.263126
0.260436
"""Testing Module db.cls_db_core.""" import os import pathlib import shutil import cfg.cls_setup import cfg.glob import db.cls_db_core import db.cls_run import pytest import sqlalchemy import utils import dcr # ----------------------------------------------------------------------------- # Constants & Globals. # ---...
tests/test_db_cls_db_core.py
"""Testing Module db.cls_db_core.""" import os import pathlib import shutil import cfg.cls_setup import cfg.glob import db.cls_db_core import db.cls_run import pytest import sqlalchemy import utils import dcr # ----------------------------------------------------------------------------- # Constants & Globals. # ---...
0.586641
0.203193
from elastichq.globals import REQUEST_TIMEOUT from .ConnectionService import ConnectionService class QueryService: def run_query(self, cluster_name, index_name, query_json): connection = ConnectionService().get_connection(cluster_name) if connection.version.startswith("2"): from elas...
elastichq/service/QueryService.py
from elastichq.globals import REQUEST_TIMEOUT from .ConnectionService import ConnectionService class QueryService: def run_query(self, cluster_name, index_name, query_json): connection = ConnectionService().get_connection(cluster_name) if connection.version.startswith("2"): from elas...
0.395018
0.111096
import httplib2 import os import oauth2client from oauth2client import client, tools, file import base64 from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from apiclient import errors, discovery import mimetypes from email.mime.image import MIMEImage from email.mime.audio import MIMEAu...
backend/AXIOME3_app/email/gmail.py
import httplib2 import os import oauth2client from oauth2client import client, tools, file import base64 from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from apiclient import errors, discovery import mimetypes from email.mime.image import MIMEImage from email.mime.audio import MIMEAu...
0.201813
0.041423
import logging import asyncio import collections import homeassistant.helpers.config_validation as cv import voluptuous as vol from homeassistant.helpers import aiohttp_client _LOGGER = logging.getLogger(__name__) DOMAIN = 'grohe_sense' CONF_REFRESH_TOKEN = '<PASSWORD>' CONFIG_SCHEMA = vol.Schema( { D...
__init__.py
import logging import asyncio import collections import homeassistant.helpers.config_validation as cv import voluptuous as vol from homeassistant.helpers import aiohttp_client _LOGGER = logging.getLogger(__name__) DOMAIN = 'grohe_sense' CONF_REFRESH_TOKEN = '<PASSWORD>' CONFIG_SCHEMA = vol.Schema( { D...
0.446977
0.056731
from datetime import datetime from os import path import sys import textwrap collections_path = path.abspath(path.join(path.dirname(__file__), '..', '..', '..')) sys.path.append(collections_path) import cerberus_collections # noqa: E402 schema = {'a_dict': {'keyschema': {'type': 'integer'}, 'va...
docs/source/includes/generate.py
from datetime import datetime from os import path import sys import textwrap collections_path = path.abspath(path.join(path.dirname(__file__), '..', '..', '..')) sys.path.append(collections_path) import cerberus_collections # noqa: E402 schema = {'a_dict': {'keyschema': {'type': 'integer'}, 'va...
0.237487
0.124665
import pyvo as vo import warnings from astroquery.jplhorizons import Horizons from regions import PixCoord, PolygonPixelRegion, CirclePixelRegion from polygon import parse_s_region warnings.simplefilter('ignore') # block out warnings def convert_stcs_for_adql(stcs): adql = "POLYGON('ICRS', " for elem in stc...
mast_tap.py
import pyvo as vo import warnings from astroquery.jplhorizons import Horizons from regions import PixCoord, PolygonPixelRegion, CirclePixelRegion from polygon import parse_s_region warnings.simplefilter('ignore') # block out warnings def convert_stcs_for_adql(stcs): adql = "POLYGON('ICRS', " for elem in stc...
0.614047
0.355859
import datetime as dt import numpy as np import pandas as pd try: import talib except: print('PLEASE install TALIB to call these methods') pass try: import QUANTAXIS as QA from QUANTAXIS.QAUtil.QAParameter import ORDER_DIRECTION from QUANTAXIS.QAData.QADataStruct import ( QA_DataStruct...
GolemQ/indices/talib_fractal.py
import datetime as dt import numpy as np import pandas as pd try: import talib except: print('PLEASE install TALIB to call these methods') pass try: import QUANTAXIS as QA from QUANTAXIS.QAUtil.QAParameter import ORDER_DIRECTION from QUANTAXIS.QAData.QADataStruct import ( QA_DataStruct...
0.270384
0.182007
import socket import serial import pyttsx class CellphoneServer(object): def __init__(self,bind_addr,bind_port): self.engine = pyttsx.init() self.engine.setProperty('voice', 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0') #ser = serial.Serial('COM3', 9600, timeout=0) ...
ServerCellphone.py
import socket import serial import pyttsx class CellphoneServer(object): def __init__(self,bind_addr,bind_port): self.engine = pyttsx.init() self.engine.setProperty('voice', 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0') #ser = serial.Serial('COM3', 9600, timeout=0) ...
0.244093
0.039158
from scripts.helpful_scripts import get_account, get_event_value from scripts.modify_metadata import modify_metadata from scripts.set_token_uri import set_token_uri from scripts.deploy_nft import deploy_nft from scripts.safe_mint import safe_mint from nft_config import ( AMOUNT_TO_MINT, COLLECTION_NAME, COL...
tests/integration/test_integration_main.py
from scripts.helpful_scripts import get_account, get_event_value from scripts.modify_metadata import modify_metadata from scripts.set_token_uri import set_token_uri from scripts.deploy_nft import deploy_nft from scripts.safe_mint import safe_mint from nft_config import ( AMOUNT_TO_MINT, COLLECTION_NAME, COL...
0.488283
0.152694
import unittest from wikisync.plugin import WikiSyncEnvironment from wikisync.model import WikiSyncDao from trac.test import EnvironmentStub from pkg_resources import resource_filename class WikiSyncModelTestCase(unittest.TestCase): def setUp(self): self.env = EnvironmentStub() self.plugin = WikiS...
wikisync/tests/model.py
import unittest from wikisync.plugin import WikiSyncEnvironment from wikisync.model import WikiSyncDao from trac.test import EnvironmentStub from pkg_resources import resource_filename class WikiSyncModelTestCase(unittest.TestCase): def setUp(self): self.env = EnvironmentStub() self.plugin = WikiS...
0.378
0.289246
import sys sys.path.append("..") import os import json import numpy as np import pandas as pd from tqdm import tqdm import functools import matplotlib.pyplot as plt import tensorflow as tf from dqn import molecules from dqn import deep_q_networks from dqn.py.SA_Score import sascorer from chemutil import similarity ...
examples/generation/docking_generation/moldqn/chemgraph/docking_eval.py
import sys sys.path.append("..") import os import json import numpy as np import pandas as pd from tqdm import tqdm import functools import matplotlib.pyplot as plt import tensorflow as tf from dqn import molecules from dqn import deep_q_networks from dqn.py.SA_Score import sascorer from chemutil import similarity ...
0.21215
0.115886
import os import sys import time import hikari import tanjun from bot import constants component = tanjun.Component() @component.with_slash_command @tanjun.as_slash_command("status", "Get the status of the bot.") async def command_status( ctx: tanjun.abc.SlashContext, bot: hikari.GatewayBot = tanjun.injec...
bot/modules/status.py
import os import sys import time import hikari import tanjun from bot import constants component = tanjun.Component() @component.with_slash_command @tanjun.as_slash_command("status", "Get the status of the bot.") async def command_status( ctx: tanjun.abc.SlashContext, bot: hikari.GatewayBot = tanjun.injec...
0.602296
0.235812
"""Tests for the Hough transform.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from moonlight.vision import hough class HoughTest(tf.test.TestCase): def testHorizontalLines(self): image = np.asarray...
moonlight/vision/hough_test.py
"""Tests for the Hough transform.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from moonlight.vision import hough class HoughTest(tf.test.TestCase): def testHorizontalLines(self): image = np.asarray...
0.832543
0.74895
import math import torch, torchvision import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self, num_classes, num_decoder_layers=6, num_decoder_heads=8, uncertainty_gate_type="entropy", uncertainty_threshold=0, weighted_prediction=False, extended_output=False, gpu_streams=T...
core/model.py
import math import torch, torchvision import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self, num_classes, num_decoder_layers=6, num_decoder_heads=8, uncertainty_gate_type="entropy", uncertainty_threshold=0, weighted_prediction=False, extended_output=False, gpu_streams=T...
0.920003
0.630372
import unittest import os from metis.File import File from metis.Task import Task from metis.Constants import Constants class TaskTest(unittest.TestCase): def test_task_initialized(self): t1 = Task() self.assertEqual(t1.initialized(), True) def test_task_clone(self): t1 = Task(a=1,b...
test/Task_t.py
import unittest import os from metis.File import File from metis.Task import Task from metis.Constants import Constants class TaskTest(unittest.TestCase): def test_task_initialized(self): t1 = Task() self.assertEqual(t1.initialized(), True) def test_task_clone(self): t1 = Task(a=1,b...
0.408277
0.575648
import os import sys import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec # Add server root to path so that imports work properly regardless # where script is called from. root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) if root_path not in sys.path: sys.path.append(roo...
server/scripts/orbit_vis.py
import os import sys import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec # Add server root to path so that imports work properly regardless # where script is called from. root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) if root_path not in sys.path: sys.path.append(roo...
0.475362
0.515803
from os import listdir from os.path import isfile, join import argparse import re import string from PIL import Image, ImageFont, ImageDraw import pystache def print_hex(val): return "{0:#0{1}x}".format(val,4) def process_char(font, char): # Calculate char info char_size = font.getsize(char); char_mask = font....
scripts/build-font.py
from os import listdir from os.path import isfile, join import argparse import re import string from PIL import Image, ImageFont, ImageDraw import pystache def print_hex(val): return "{0:#0{1}x}".format(val,4) def process_char(font, char): # Calculate char info char_size = font.getsize(char); char_mask = font....
0.195594
0.184988
import os import threading from base64 import b64decode import asyncio import boto3 import discord import requests token = os.environ.get("DISCORD_TOKEN", None) CHANNEL_NAME = "announcements" class DClient(discord.Client): async def on_ready(self): print("Logged in as {}".format(self.user.name)) class...
discord_client.py
import os import threading from base64 import b64decode import asyncio import boto3 import discord import requests token = os.environ.get("DISCORD_TOKEN", None) CHANNEL_NAME = "announcements" class DClient(discord.Client): async def on_ready(self): print("Logged in as {}".format(self.user.name)) class...
0.370339
0.053403
from ctypes import * from win32api import * import psutil import win32security """WinApi methods""" K32 = windll.kernel32 ReadProcessMemory = K32.ReadProcessMemory WriteProcessMemory = K32.WriteProcessMemory OpenProcess = K32.OpenProcess GetLastError = K32.GetLastError """All access""" PAA = 0x1F0FFF class ProcessE...
ProcessHandler.py
from ctypes import * from win32api import * import psutil import win32security """WinApi methods""" K32 = windll.kernel32 ReadProcessMemory = K32.ReadProcessMemory WriteProcessMemory = K32.WriteProcessMemory OpenProcess = K32.OpenProcess GetLastError = K32.GetLastError """All access""" PAA = 0x1F0FFF class ProcessE...
0.378
0.103115
from eliot.testing import ( assertHasMessage, capture_logging ) from eliot import Field, MessageType from pyrsistent import PClass, field, InvariantException from testtools.matchers import Is, Equals, Raises, MatchesException from zope.interface import Interface, implementer from .. import ( interface_decora...
flocker/common/test/test_interface.py
from eliot.testing import ( assertHasMessage, capture_logging ) from eliot import Field, MessageType from pyrsistent import PClass, field, InvariantException from testtools.matchers import Is, Equals, Raises, MatchesException from zope.interface import Interface, implementer from .. import ( interface_decora...
0.86129
0.582877
import lasagne import theano import theano.tensor as t from lasagne.layers import ConcatLayer, Conv2DLayer, DenseLayer, GlobalPoolLayer from lasagne.layers import InputLayer, Pool2DLayer from lasagne.layers.normalization import batch_norm from lasagne.nonlinearities import softmax new_pool_size = 3 new_pad = 1 def p...
scripts/ann_architectures/imagenet/refine_inceptionV3_lasagne.py
import lasagne import theano import theano.tensor as t from lasagne.layers import ConcatLayer, Conv2DLayer, DenseLayer, GlobalPoolLayer from lasagne.layers import InputLayer, Pool2DLayer from lasagne.layers.normalization import batch_norm from lasagne.nonlinearities import softmax new_pool_size = 3 new_pad = 1 def p...
0.897785
0.567158
import requests import os import json from dateutil.parser import parse from datetime import datetime, timedelta from Crypto.PublicKey import RSA from Crypto.Random import get_random_bytes from Crypto.Cipher import AES, PKCS1_OAEP # Begin Private File Paths def _ACCOUNT_ID(): return '132591' def __PRIVATE_PATH():...
PyProjects/LightSpeed_auth/Token.py
import requests import os import json from dateutil.parser import parse from datetime import datetime, timedelta from Crypto.PublicKey import RSA from Crypto.Random import get_random_bytes from Crypto.Cipher import AES, PKCS1_OAEP # Begin Private File Paths def _ACCOUNT_ID(): return '132591' def __PRIVATE_PATH():...
0.270673
0.0643
from typing import Set import re def tokenize(text: str) -> Set[str]: text = text.lower() # standardize all_words = re.findall("[a-z0-9']+", text) # extract words return set(all_words) # remove duplicates assert tokenize("Data science is science") == {"data", "science", "is", "science"} # define c...
python_da/dsfs/mycode/ch13.py
from typing import Set import re def tokenize(text: str) -> Set[str]: text = text.lower() # standardize all_words = re.findall("[a-z0-9']+", text) # extract words return set(all_words) # remove duplicates assert tokenize("Data science is science") == {"data", "science", "is", "science"} # define c...
0.760339
0.414662
import os import subprocess import time class File(object): def __init__(self, filename): self.name, self.extension = os.path.splitext(filename) self.filename = filename def open(self, flag): return open(self.filename, flag) def remove(self): try: os.remove(se...
fast/files.py
import os import subprocess import time class File(object): def __init__(self, filename): self.name, self.extension = os.path.splitext(filename) self.filename = filename def open(self, flag): return open(self.filename, flag) def remove(self): try: os.remove(se...
0.459804
0.096706
class InvalidResourceError(Exception): """Raised when a resource does not match the spec.""" pass class InvalidSpecError(Exception): """Raised when a resource spec is invalid.""" pass class ResourceSpec(dict): """A syntax specification for a class of valid resource IDs. A resource ID is a path-like str...
service/data_store/resource_id.py
class InvalidResourceError(Exception): """Raised when a resource does not match the spec.""" pass class InvalidSpecError(Exception): """Raised when a resource spec is invalid.""" pass class ResourceSpec(dict): """A syntax specification for a class of valid resource IDs. A resource ID is a path-like str...
0.885607
0.335623
import keras.backend as K class Doi(object): ''' Interface for a distribution of interest. The *distribution of interest* lets us specify the set of instances over which we want our explanations to be faithful. ''' def __call__(self, z): ''' Takes a tensor, z, which is the i...
attribution/distributions.py
import keras.backend as K class Doi(object): ''' Interface for a distribution of interest. The *distribution of interest* lets us specify the set of instances over which we want our explanations to be faithful. ''' def __call__(self, z): ''' Takes a tensor, z, which is the i...
0.920754
0.604428
import torch as th import torch.nn as nn import torch.nn.functional as F import numpy as np class QTran(nn.Module): def __init__(self, args): super(QTran, self).__init__() self.args = args self.n_agents = args.n_agents self.n_actions = args.n_actions self.state_dim = int(...
MAVEN/maven_code/src/modules/mixers/qtran.py
import torch as th import torch.nn as nn import torch.nn.functional as F import numpy as np class QTran(nn.Module): def __init__(self, args): super(QTran, self).__init__() self.args = args self.n_agents = args.n_agents self.n_actions = args.n_actions self.state_dim = int(...
0.929728
0.539287
import matplotlib from data.imsitu_loader import ImSitu, CudaDataLoader from config import ModelConfig import torch from lib.misc import get_ranking import numpy as np from lib.imsitu_model import ImsituModel import pandas as pd from tqdm import tqdm from lib.attribute_loss import AttributeLoss from copy import deepcop...
figures/viz_activations.py
import matplotlib from data.imsitu_loader import ImSitu, CudaDataLoader from config import ModelConfig import torch from lib.misc import get_ranking import numpy as np from lib.imsitu_model import ImsituModel import pandas as pd from tqdm import tqdm from lib.attribute_loss import AttributeLoss from copy import deepcop...
0.549641
0.303493
from __future__ import annotations from typing import Text, List, Tuple, Dict from nltk import wordpunct_tokenize, word_tokenize from liyi_cute.utils.common import doubleQuotes class WordTokenizerFast(): def __init__(self, *args, **kwargs): self.do_lower_case = kwargs.pop("do_lower_case", True) ...
liyi_cute/processor/tokenizers/nltk_tokenizer.py
from __future__ import annotations from typing import Text, List, Tuple, Dict from nltk import wordpunct_tokenize, word_tokenize from liyi_cute.utils.common import doubleQuotes class WordTokenizerFast(): def __init__(self, *args, **kwargs): self.do_lower_case = kwargs.pop("do_lower_case", True) ...
0.696784
0.240451
from __future__ import unicode_literals import django from django.conf import settings from django.contrib.auth import get_user_model # noqa try: from django.urls import NoReverseMatch, reverse, Resolver404, get_script_prefix # noqa except ImportError: # 1.8 backwards compat from django.core.urlresolvers i...
tastypie/compat.py
from __future__ import unicode_literals import django from django.conf import settings from django.contrib.auth import get_user_model # noqa try: from django.urls import NoReverseMatch, reverse, Resolver404, get_script_prefix # noqa except ImportError: # 1.8 backwards compat from django.core.urlresolvers i...
0.394551
0.063919
from unittest import TestCase from pythonzimbra.request_json import RequestJson from pythonzimbra.request_xml import RequestXml from pythonzimbra.tools.auth import authenticate from pythonzimbra.communication import Communication from tests import get_config class TestAutoresponse(TestCase): def test_autorespons...
tests/test_autoresponse.py
from unittest import TestCase from pythonzimbra.request_json import RequestJson from pythonzimbra.request_xml import RequestXml from pythonzimbra.tools.auth import authenticate from pythonzimbra.communication import Communication from tests import get_config class TestAutoresponse(TestCase): def test_autorespons...
0.770162
0.294177
import unittest import numpy as np import lightly from lightly.active_learning.scorers import ScorerSemanticSegmentation from lightly.active_learning.scorers import ScorerClassification class TestScorerSemanticSegmentation(unittest.TestCase): def setUp(self): self.N = 100 self.W, self.H, self.C...
tests/active_learning/test_ScorerSemanticSegmentation.py
import unittest import numpy as np import lightly from lightly.active_learning.scorers import ScorerSemanticSegmentation from lightly.active_learning.scorers import ScorerClassification class TestScorerSemanticSegmentation(unittest.TestCase): def setUp(self): self.N = 100 self.W, self.H, self.C...
0.613931
0.594845
import os from os.path import basename from os.path import join import subprocess import sys import cv2 import config import utils from pdf_to_jpg import PDF_TO_JPG_DIR NEW_JPG_DIR = 'devided_jpgs' CLEAN_PDF_DIR = 'clean_pdf' CLEAN_PDF_SUFFIX = '_clean' def is_color_img(img): h, w = img.shape[:2] # 画像の画素値(...
src/jpg_to_clean_pdf.py
import os from os.path import basename from os.path import join import subprocess import sys import cv2 import config import utils from pdf_to_jpg import PDF_TO_JPG_DIR NEW_JPG_DIR = 'devided_jpgs' CLEAN_PDF_DIR = 'clean_pdf' CLEAN_PDF_SUFFIX = '_clean' def is_color_img(img): h, w = img.shape[:2] # 画像の画素値(...
0.132683
0.207897
import random, pygame pygame.init() #Gets all pygame libraries whiteSquare = pygame.image.load('Snake Piece.png') class Snake(object): #The entire Snake. Basically a doubly - linked list def __init__(self, xRange, yRange): self.tail = self.head = SnakePiece(int(int(xRange/10)/2)*10, int(int(...
SnakeObjects.py
import random, pygame pygame.init() #Gets all pygame libraries whiteSquare = pygame.image.load('Snake Piece.png') class Snake(object): #The entire Snake. Basically a doubly - linked list def __init__(self, xRange, yRange): self.tail = self.head = SnakePiece(int(int(xRange/10)/2)*10, int(int(...
0.430866
0.240931
from tempfile import gettempdir from time import time from pathlib import Path from mock import patch import pytest from bets.model.match import Match from bets.program_io.matches_output import ( fmt_to_csv, fmt_to_table, MatchesOutput ) MATCHES = [ Match("Man UTD. - Arsenal", 2.78, 3.45, 2.90), ...
tests/program_io/test_matches_output.py
from tempfile import gettempdir from time import time from pathlib import Path from mock import patch import pytest from bets.model.match import Match from bets.program_io.matches_output import ( fmt_to_csv, fmt_to_table, MatchesOutput ) MATCHES = [ Match("Man UTD. - Arsenal", 2.78, 3.45, 2.90), ...
0.356447
0.424114
from django.forms.utils import flatatt from django.forms.widgets import Widget, Textarea from django.template import loader from django.utils.safestring import mark_safe from django.conf import settings class ImageWidget(Widget): template_name = 'widgets/image.html' def get_context(self, name, value, attrs=N...
cruds_adminlte/widgets.py
from django.forms.utils import flatatt from django.forms.widgets import Widget, Textarea from django.template import loader from django.utils.safestring import mark_safe from django.conf import settings class ImageWidget(Widget): template_name = 'widgets/image.html' def get_context(self, name, value, attrs=N...
0.385837
0.103341
import torch from torch import nn from torch.nn import functional as F from torch.autograd import Variable import torch.utils.data import torch.utils.data.distributed class Generator(nn.Module): def __init__(self, z_dim, nlabels=1, size=256, embe...
DeepEBM/Torture/Models/GAN/resnet_imagenet.py
import torch from torch import nn from torch.nn import functional as F from torch.autograd import Variable import torch.utils.data import torch.utils.data.distributed class Generator(nn.Module): def __init__(self, z_dim, nlabels=1, size=256, embe...
0.936757
0.334019
import pylab import numpy from matplotlib import pyplot def plotPhaseSpace( b, aTheta, aOmega, t, power, k): pylab.clf() pylab.cla() label = str(b) pylab.subplot(221) pylab.plot( aTheta, aOmega, color="m", lw = 2) pylab.xlabel(r"$\theta$ (radians) ", fontsize=10) pylab.ylabel('$\om...
homework3_linear_algebra_FFT/time_series_analysis/plotter.py
import pylab import numpy from matplotlib import pyplot def plotPhaseSpace( b, aTheta, aOmega, t, power, k): pylab.clf() pylab.cla() label = str(b) pylab.subplot(221) pylab.plot( aTheta, aOmega, color="m", lw = 2) pylab.xlabel(r"$\theta$ (radians) ", fontsize=10) pylab.ylabel('$\om...
0.581897
0.531513
import collections import seaborn as sns import matplotlib from sklearn import metrics from src.utils import utils from src.models import ML matplotlib.use('Agg', warn=False) import matplotlib.pyplot as plt from matplotlib.pyplot import figure import numpy as np import operator import pandas as pd plt.ioff() conver...
src/visualization/visualization.py
import collections import seaborn as sns import matplotlib from sklearn import metrics from src.utils import utils from src.models import ML matplotlib.use('Agg', warn=False) import matplotlib.pyplot as plt from matplotlib.pyplot import figure import numpy as np import operator import pandas as pd plt.ioff() conver...
0.596551
0.273969
import json from typing import Any, cast from unittest.mock import patch from django.http import HttpRequest from django.http.response import JsonResponse from django.test.client import RequestFactory from rest_framework import status from posthog.api.test.test_capture import mocked_get_ingest_context_from_token from...
posthog/api/test/test_utils.py
import json from typing import Any, cast from unittest.mock import patch from django.http import HttpRequest from django.http.response import JsonResponse from django.test.client import RequestFactory from rest_framework import status from posthog.api.test.test_capture import mocked_get_ingest_context_from_token from...
0.657648
0.212702
from torchvision import datasets from torchvision import transforms from torch.utils.data import DataLoader, DistributedSampler from fltk.datasets.distributed.dataset import DistDataset from fltk.util.data_sampler_utils import LimitLabelsSampler from fltk.util.non_iid_sampler import PDegreeSampler class NonIIDMNISTDa...
fltk/datasets/non_iid_dataset/non_iid_mnist.py
from torchvision import datasets from torchvision import transforms from torch.utils.data import DataLoader, DistributedSampler from fltk.datasets.distributed.dataset import DistDataset from fltk.util.data_sampler_utils import LimitLabelsSampler from fltk.util.non_iid_sampler import PDegreeSampler class NonIIDMNISTDa...
0.87401
0.55646
import pandas as pd import numpy as np import matplotlib.pyplot as plt import csv as csv from sklearn.ensemble import GradientBoostingRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.cross_validation import train_test_split from math import * from datetime import datetime import sklearn.cluster...
20171126-258-assignment2/code/ref/code/pca.py
import pandas as pd import numpy as np import matplotlib.pyplot as plt import csv as csv from sklearn.ensemble import GradientBoostingRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.cross_validation import train_test_split from math import * from datetime import datetime import sklearn.cluster...
0.319227
0.504944
import torch import torch.nn as nn import numpy as np import tqdm from lib.options import BaseOption class DGM_Layer(nn.Module): def __init__(self, dim_x, dim_S, activation='Tanh'): super(DGM_Layer, self).__init__() if activation == 'ReLU': self.activation = nn.ReLU() ...
lib/dgm.py
import torch import torch.nn as nn import numpy as np import tqdm from lib.options import BaseOption class DGM_Layer(nn.Module): def __init__(self, dim_x, dim_S, activation='Tanh'): super(DGM_Layer, self).__init__() if activation == 'ReLU': self.activation = nn.ReLU() ...
0.940147
0.489198
from naoqi import ALProxy class ALMotion(object): def __init__(self, session): self.proxy = None self.session = session def force_connect(self): self.proxy = self.session.service("ALMotion") def angleInterpolation(self, names, angleLists, timeLists, isAbsolute): """Int...
naoqi_proxy_python_classes/ALMotion.py
from naoqi import ALProxy class ALMotion(object): def __init__(self, session): self.proxy = None self.session = session def force_connect(self): self.proxy = self.session.service("ALMotion") def angleInterpolation(self, names, angleLists, timeLists, isAbsolute): """Int...
0.836721
0.59072
import os import sys import unittest from collections import OrderedDict import mock import unittest2 from cnpsdk import (utils, chargeback_update) package_root = os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) sys.path.insert(0, package_root) conf = utils.Configuration() class TestCh...
tests/unit/test_chargeback_update.py
import os import sys import unittest from collections import OrderedDict import mock import unittest2 from cnpsdk import (utils, chargeback_update) package_root = os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) sys.path.insert(0, package_root) conf = utils.Configuration() class TestCh...
0.36727
0.187226
import logging from collections import namedtuple from autotrail.core.dag import Step, topological_traverse from autotrail.core.socket_communication import HandlerResult class APICallName: """Namepsace for the API call names. Use this class instead of plain strings.""" # List of valid API call names # T...
autotrail/layer1/api.py
import logging from collections import namedtuple from autotrail.core.dag import Step, topological_traverse from autotrail.core.socket_communication import HandlerResult class APICallName: """Namepsace for the API call names. Use this class instead of plain strings.""" # List of valid API call names # T...
0.82566
0.396535
import os import sys import argparse from .context import setup_context, gather_tags from .exceptions import YaggyError from .logging import setup_logging, get_logger from .parser import run_parser from .ssh import disconnect from .templates import render from .utils import pick, mutate def tags_type(value): re...
src/yaggy/cli.py
import os import sys import argparse from .context import setup_context, gather_tags from .exceptions import YaggyError from .logging import setup_logging, get_logger from .parser import run_parser from .ssh import disconnect from .templates import render from .utils import pick, mutate def tags_type(value): re...
0.329068
0.106877
from typing import Generator from abc import ABC, abstractmethod class BaseScraper(ABC): """Scraper Abstract Base Class.""" @abstractmethod def scrape(self, chunksize: int, **kwargs) -> Generator: """ Download any new information not yet downloaded. The first time this method is ...
geniepy/src/geniepy/datamgmt/scrapers.py
from typing import Generator from abc import ABC, abstractmethod class BaseScraper(ABC): """Scraper Abstract Base Class.""" @abstractmethod def scrape(self, chunksize: int, **kwargs) -> Generator: """ Download any new information not yet downloaded. The first time this method is ...
0.897844
0.597579
import statistics from typing import Iterable, Collection, Union, ValuesView def get_set_by_setting_name(name: str, measurements: Iterable) -> set: result = set() for m in measurements: result.add(m.settings.dict[name]) return result def get_summary_by_set(my_set: set) -> str: result = "" ...
pi88reader/utils_pi88measurements.py
import statistics from typing import Iterable, Collection, Union, ValuesView def get_set_by_setting_name(name: str, measurements: Iterable) -> set: result = set() for m in measurements: result.add(m.settings.dict[name]) return result def get_summary_by_set(my_set: set) -> str: result = "" ...
0.53777
0.320542
import os # Turn off some memory warning by changing warning level before loading module os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import tensorflow as tf import numpy as np from tensorflow.keras import layers from tensorflow.keras.layers import Dense, Flatten, Conv2D from tensorflow.keras import Model from tensorflow...
main.py
import os # Turn off some memory warning by changing warning level before loading module os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import tensorflow as tf import numpy as np from tensorflow.keras import layers from tensorflow.keras.layers import Dense, Flatten, Conv2D from tensorflow.keras import Model from tensorflow...
0.696578
0.362574
from flask import Flask, render_template, session, url_for, request, redirect, escape import os app = Flask(__name__) app.config['SECRET_KEY'] = 'leyni' vorur = [ [0,"Arnar","arnar.jpg","1000000"], [1,"Guðjón","gudjon.jpg","700000"], [2,"Ágúst","agust.jpg","850000"], [3,"Lorraine...
app.py
from flask import Flask, render_template, session, url_for, request, redirect, escape import os app = Flask(__name__) app.config['SECRET_KEY'] = 'leyni' vorur = [ [0,"Arnar","arnar.jpg","1000000"], [1,"Guðjón","gudjon.jpg","700000"], [2,"Ágúst","agust.jpg","850000"], [3,"Lorraine...
0.253399
0.074198
from pathlib import Path import pytest from puzzle.__main__ import ( _random_words, _validate_puzzle_grid_size, _validate_puzzle_word, _validate_puzzle_words_path, ) pytestmark = pytest.mark.unittest _test_path: Path = Path(__file__).parent / 'words.txt' @pytest.mark.parametrize( 'word, grid_si...
tests/test_tool_payload.py
from pathlib import Path import pytest from puzzle.__main__ import ( _random_words, _validate_puzzle_grid_size, _validate_puzzle_word, _validate_puzzle_words_path, ) pytestmark = pytest.mark.unittest _test_path: Path = Path(__file__).parent / 'words.txt' @pytest.mark.parametrize( 'word, grid_si...
0.857932
0.413803
import json ## Session def RealTimeResponseBatchInitSession(self, ids, timeout=30, timeout_duration="30s", batch=None): '''/real-time-response/combined/batch-init-session/v1''' body = { "host_ids": ids if type(ids) == list else [ids], "queue_offline": True } if batch: body["e...
crowdstrikeclient/_CrowdstrikeRTR.py
import json ## Session def RealTimeResponseBatchInitSession(self, ids, timeout=30, timeout_duration="30s", batch=None): '''/real-time-response/combined/batch-init-session/v1''' body = { "host_ids": ids if type(ids) == list else [ids], "queue_offline": True } if batch: body["e...
0.31216
0.081483
import asyncio import argparse import json import logging from kin import KinClient, Environment, Keypair from kin.blockchain.builder import Builder from helpers import (NETWORK_NAME, MIN_FEE, load_accounts, generate_keypairs, get_sequences_multiple_endpoints, create_accounts...
cmd/python/create.py
import asyncio import argparse import json import logging from kin import KinClient, Environment, Keypair from kin.blockchain.builder import Builder from helpers import (NETWORK_NAME, MIN_FEE, load_accounts, generate_keypairs, get_sequences_multiple_endpoints, create_accounts...
0.613815
0.122313
from typing import Any from uuid import UUID from .....typing import UserID from ....ticketing.dbmodels.ticket_bundle import TicketBundle from ....ticketing import ( category_service as ticket_category_service, ticket_bundle_service, ) from ....ticketing.transfer.models import TicketBundleID, TicketCategoryID...
byceps/services/shop/order/actions/ticket_bundle.py
from typing import Any from uuid import UUID from .....typing import UserID from ....ticketing.dbmodels.ticket_bundle import TicketBundle from ....ticketing import ( category_service as ticket_category_service, ticket_bundle_service, ) from ....ticketing.transfer.models import TicketBundleID, TicketCategoryID...
0.633524
0.173183
import tensorflow as tf # tfjs-converter cannot convert tf.linspace due to broadcasting issues def _linspace(start, stop, num, dtype=tf.float32): range = tf.range(0, num, dtype=dtype) start = tf.cast(start, dtype) stop = tf.cast(stop, dtype) num = tf.cast(num, dtype) return start + (stop - start) ...
lidbox/features/mel_ops.py
import tensorflow as tf # tfjs-converter cannot convert tf.linspace due to broadcasting issues def _linspace(start, stop, num, dtype=tf.float32): range = tf.range(0, num, dtype=dtype) start = tf.cast(start, dtype) stop = tf.cast(stop, dtype) num = tf.cast(num, dtype) return start + (stop - start) ...
0.897105
0.364891
from __future__ import absolute_import, unicode_literals from django.conf import settings as django_settings from django.utils import translation import elasticsearch from elasticsearch import NotFoundError, ImproperlyConfigured import haystack from haystack.backends import BaseEngine from haystack.backends.elasticsear...
multilingual/elasticsearch_backend.py
from __future__ import absolute_import, unicode_literals from django.conf import settings as django_settings from django.utils import translation import elasticsearch from elasticsearch import NotFoundError, ImproperlyConfigured import haystack from haystack.backends import BaseEngine from haystack.backends.elasticsear...
0.695648
0.101991
import logging import threading import argparse from queue import Queue from collections import deque import fakesmartrowble import fakerower logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logHandler = logging.StreamHandler() filelogHandler = logging.FileHandler("logs.log") formatter = logging....
src/testing/fakesmartrowthreads.py
import logging import threading import argparse from queue import Queue from collections import deque import fakesmartrowble import fakerower logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logHandler = logging.StreamHandler() filelogHandler = logging.FileHandler("logs.log") formatter = logging....
0.098101
0.050682
class Category: ledger: list[dict] total: float name: str def __init__(self, name): self.name = name self.ledger = [] self.total = 0.0 def __str__(self): result = '' result += self.name.center(30, '*') + '\n' for item in self.ledger: a, m...
Budget-app/budget.py
class Category: ledger: list[dict] total: float name: str def __init__(self, name): self.name = name self.ledger = [] self.total = 0.0 def __str__(self): result = '' result += self.name.center(30, '*') + '\n' for item in self.ledger: a, m...
0.489748
0.17037
from __future__ import division from os.path import dirname, join from datetime import datetime from pyNN.nineml.read import Network from pyNN.utility import SimulationProgressBar import nineml.user as nineml from nineml.units import ms, mV, nA, unitless, Hz, Mohm from utility import psp_height #CATALOG_URL = "/home/d...
python/simple_network/simple_network_nineml.py
from __future__ import division from os.path import dirname, join from datetime import datetime from pyNN.nineml.read import Network from pyNN.utility import SimulationProgressBar import nineml.user as nineml from nineml.units import ms, mV, nA, unitless, Hz, Mohm from utility import psp_height #CATALOG_URL = "/home/d...
0.487063
0.259878
import os import argparse import tensorflow as tf import pdb from scripts import configs_cv as C from rl.configs import parser as ps from rl.tools.utils import tf_utils as U def setup_pdb(mode): if mode == 'on': pdb.set_trace_force = pdb.set_trace return elif mode == 'off': pdb.set_tr...
scripts/rl_exp_cv_var.py
import os import argparse import tensorflow as tf import pdb from scripts import configs_cv as C from rl.configs import parser as ps from rl.tools.utils import tf_utils as U def setup_pdb(mode): if mode == 'on': pdb.set_trace_force = pdb.set_trace return elif mode == 'off': pdb.set_tr...
0.215598
0.095687
from biocrnpyler.chemical_reaction_network import Species, Reaction, ComplexSpecies, ChemicalReactionNetwork print("Start") #Names of different supported propensities propensity_types = ['hillpositive', 'proportionalhillpositive', 'hillnegative', 'proportionalhillnegative', 'massaction', 'general'] kb = 100 ku = 10 ...
examples/Old Examples and Tests/Testing Propensities.py
from biocrnpyler.chemical_reaction_network import Species, Reaction, ComplexSpecies, ChemicalReactionNetwork print("Start") #Names of different supported propensities propensity_types = ['hillpositive', 'proportionalhillpositive', 'hillnegative', 'proportionalhillnegative', 'massaction', 'general'] kb = 100 ku = 10 ...
0.277669
0.484075
from gpxpy import * import unittest import StringIO import math import gpxpy.tests import datetime class ParseTest(unittest.TestCase): def test_parse_track1(self): gpx = gpxpy.tests.load('track-1.gpx') # parsed correctly - 1 track self.assertEquals(len(gpx.tracks),1) self.assertEquals(len(gpx.way...
gpxpy/tests/gpxpy_test.py
from gpxpy import * import unittest import StringIO import math import gpxpy.tests import datetime class ParseTest(unittest.TestCase): def test_parse_track1(self): gpx = gpxpy.tests.load('track-1.gpx') # parsed correctly - 1 track self.assertEquals(len(gpx.tracks),1) self.assertEquals(len(gpx.way...
0.48438
0.550245
import os import argparse import numpy as np import tensorflow as tf import smdebug.tensorflow as smd from model_def import get_resnet50 hook = smd.KerasHook.create_from_json_file() os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def parse_args(): parser = argparse.ArgumentParser() # hyperparameters are passed a...
tf-2-data-parallelism/src/train_resnet_simple.py
import os import argparse import numpy as np import tensorflow as tf import smdebug.tensorflow as smd from model_def import get_resnet50 hook = smd.KerasHook.create_from_json_file() os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def parse_args(): parser = argparse.ArgumentParser() # hyperparameters are passed a...
0.707809
0.213521
__all__ = ['img2tensor', 'leaf_modules', 'gram_matrix', 'get_in_channels', 'get_out_channels', 'reflection_conv', 'conv_layer', 'res_block', 'Halve', 'Double', 'get_encoder', 'FeatureLoss', 'AutoEncoder'] # Cell from functools import partial from pathlib import Path import matplotlib.pyplot as plt import ...
style_transfer/models.py
__all__ = ['img2tensor', 'leaf_modules', 'gram_matrix', 'get_in_channels', 'get_out_channels', 'reflection_conv', 'conv_layer', 'res_block', 'Halve', 'Double', 'get_encoder', 'FeatureLoss', 'AutoEncoder'] # Cell from functools import partial from pathlib import Path import matplotlib.pyplot as plt import ...
0.810779
0.351951
import mimetypes from pathlib import Path from PIL import Image class ResizeImage: """ Redimensiona una imagen indicando la anchura y la altura. """ def __init__(self, file_in, file_out, args): """ Args: file_in (Path): Archivo de entrada (imagen) file_out (Pa...
reto-08/fpellicer/src/resize_image.py
import mimetypes from pathlib import Path from PIL import Image class ResizeImage: """ Redimensiona una imagen indicando la anchura y la altura. """ def __init__(self, file_in, file_out, args): """ Args: file_in (Path): Archivo de entrada (imagen) file_out (Pa...
0.624408
0.280561
# Copyright (c) 2021, 2022 Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ import logging from ads.common.model_metadata import Framework from ads.model.extractor.model_info_extractor import ModelInfoExtractor class LightgbmExtra...
ads/model/extractor/lightgbm_extractor.py
# Copyright (c) 2021, 2022 Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ import logging from ads.common.model_metadata import Framework from ads.model.extractor.model_info_extractor import ModelInfoExtractor class LightgbmExtra...
0.935383
0.545407
from covsirphy.util.evaluator import Evaluator from covsirphy.util.term import Term from covsirphy.ode.mbase import ModelBase from covsirphy.regression.param_elastic_net import _ParamElasticNetRegressor from covsirphy.regression.rate_elastic_net import _RateElasticNetRegressor class RegressionHandler(Term): """ ...
covsirphy/regression/reg_handler.py
from covsirphy.util.evaluator import Evaluator from covsirphy.util.term import Term from covsirphy.ode.mbase import ModelBase from covsirphy.regression.param_elastic_net import _ParamElasticNetRegressor from covsirphy.regression.rate_elastic_net import _RateElasticNetRegressor class RegressionHandler(Term): """ ...
0.954932
0.688658
import tkinter as tk from tkinter import ttk """ Display tkinter widgets in a resizable grid. WidgetGrid.content is derived from tkinter.Text. Its appearance can be configured with all the options of Text. The tabs option controls the space between columns of widgets. The spacing2 option controls the space between row...
widgetgrid.py
import tkinter as tk from tkinter import ttk """ Display tkinter widgets in a resizable grid. WidgetGrid.content is derived from tkinter.Text. Its appearance can be configured with all the options of Text. The tabs option controls the space between columns of widgets. The spacing2 option controls the space between row...
0.705379
0.281461
from user import User from cred import Info def create_account(name,e_mail): ''' creating a new account ''' new_user=User(name,e_mail) return new_user def create_credentials(facebk_pass,email_pass): ''' create credentials of password and email ''' new_cred=Info(facebk_pass,email_p...
run.py
from user import User from cred import Info def create_account(name,e_mail): ''' creating a new account ''' new_user=User(name,e_mail) return new_user def create_credentials(facebk_pass,email_pass): ''' create credentials of password and email ''' new_cred=Info(facebk_pass,email_p...
0.164483
0.075007
# <markdowncell> # #Generates Urdu versions of output # # This is a bit sloppy right now. # <codecell> import sys sys.path.append('./graphparser/') import graphparser urdup = graphparser.GraphParser('./graphparser/settings/urdu.yaml') nagarip = graphparser.GraphParser('./graphparser/settings/devanagari.yaml') # ...
generate_urdu.py
# <markdowncell> # #Generates Urdu versions of output # # This is a bit sloppy right now. # <codecell> import sys sys.path.append('./graphparser/') import graphparser urdup = graphparser.GraphParser('./graphparser/settings/urdu.yaml') nagarip = graphparser.GraphParser('./graphparser/settings/devanagari.yaml') # ...
0.36139
0.123023
r""" Set of utilities to open databases. """ from m4db_database.configuration import read_config_from_environ from m4db_database import global_vars from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import NullPool from m4db_database.orm.latest import Base as BaseLates...
lib/m4db_database/sessions.py
r""" Set of utilities to open databases. """ from m4db_database.configuration import read_config_from_environ from m4db_database import global_vars from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import NullPool from m4db_database.orm.latest import Base as BaseLates...
0.567697
0.161916
from datetime import timedelta from django.apps import apps from django.contrib.contenttypes.models import ContentType from django.core.management import BaseCommand from django.db import DEFAULT_DB_ALIAS, models, transaction from django.utils.timezone import now from polymorphic.models import PolymorphicModel from ....
paper_uploads/management/commands/clean_uploads.py
from datetime import timedelta from django.apps import apps from django.contrib.contenttypes.models import ContentType from django.core.management import BaseCommand from django.db import DEFAULT_DB_ALIAS, models, transaction from django.utils.timezone import now from polymorphic.models import PolymorphicModel from ....
0.527317
0.209369
from pid import PID from lowpass import LowPassFilter from yaw_controller import YawController import rospy GAS_DENSITY = 2.858 ONE_MPH = 0.44704 class Controller(object): def __init__(self, vehicle_mass, fuel_capacity, brake_deadband, decel_limit, accel_limit, wheel_radius, wheel_base, steer_r...
ros/src/twist_controller/twist_controller.py
from pid import PID from lowpass import LowPassFilter from yaw_controller import YawController import rospy GAS_DENSITY = 2.858 ONE_MPH = 0.44704 class Controller(object): def __init__(self, vehicle_mass, fuel_capacity, brake_deadband, decel_limit, accel_limit, wheel_radius, wheel_base, steer_r...
0.547222
0.165897