code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from ply import lex
from beamr.lexers.generic import t_error # Used internally by lex() @UnusedImport
import beamr.interpreters
import beamr.debug as dbg
tokens = ('COMMENT', 'RAW', 'HEADING', 'SLIDE', 'SCISSOR', 'MACRO', 'YAML', 'TEXT')
def t_COMMENT(t):
r'#.*(?=(\n|$))'
t.value = beamr.interpreters.Comment... | beamr/lexers/document.py | from ply import lex
from beamr.lexers.generic import t_error # Used internally by lex() @UnusedImport
import beamr.interpreters
import beamr.debug as dbg
tokens = ('COMMENT', 'RAW', 'HEADING', 'SLIDE', 'SCISSOR', 'MACRO', 'YAML', 'TEXT')
def t_COMMENT(t):
r'#.*(?=(\n|$))'
t.value = beamr.interpreters.Comment... | 0.433742 | 0.198958 |
import random, math
from itertools import *
def respond(challenge, f, g):
n = len(challenge)
a = [f[challenge[i]] for i in range(0,n)]
b = [0 for i in range(0,n)]
b[0]=int(g[(a[0]+a[-1]) % 10])
for i in range(1,n):
b[i] = int(g[(b[i-1]+a[i]) % 10])
return b
def checkg(g, pairs):
f ... | code/kjk.py | import random, math
from itertools import *
def respond(challenge, f, g):
n = len(challenge)
a = [f[challenge[i]] for i in range(0,n)]
b = [0 for i in range(0,n)]
b[0]=int(g[(a[0]+a[-1]) % 10])
for i in range(1,n):
b[i] = int(g[(b[i-1]+a[i]) % 10])
return b
def checkg(g, pairs):
f ... | 0.110771 | 0.163112 |
import discord
import time
import stripe
from config import *
from datetime import date, datetime, timedelta
from discord.ui import Button, View
from discord.ext import commands
from discord.utils import get
from math import perm
from string import digits
# Create today event for general embed information
today = date... | main.py | import discord
import time
import stripe
from config import *
from datetime import date, datetime, timedelta
from discord.ui import Button, View
from discord.ext import commands
from discord.utils import get
from math import perm
from string import digits
# Create today event for general embed information
today = date... | 0.427158 | 0.079246 |
from pathlib import Path
import pandas as pd
import pytest
from ertk.dataset.annotation import read_annotations, write_annotations
from .constants import test_data_dir
def test_read_annotations_str_1() -> None:
annotations = read_annotations(test_data_dir / "annot2_str.csv", dtype=str)
assert type(annotati... | tests/dataset/test_annotation.py | from pathlib import Path
import pandas as pd
import pytest
from ertk.dataset.annotation import read_annotations, write_annotations
from .constants import test_data_dir
def test_read_annotations_str_1() -> None:
annotations = read_annotations(test_data_dir / "annot2_str.csv", dtype=str)
assert type(annotati... | 0.719285 | 0.51312 |
import os
import pdb
import pipfile
from dep_appearances.dependency import Dependency
from dep_appearances.import_statement import ImportStatement
class AppearancesReport:
def __init__(self, project_root):
self.project_root = os.path.abspath(project_root)
self.dependencies = []
def compile(se... | src/dep_appearances/appearances_report.py | import os
import pdb
import pipfile
from dep_appearances.dependency import Dependency
from dep_appearances.import_statement import ImportStatement
class AppearancesReport:
def __init__(self, project_root):
self.project_root = os.path.abspath(project_root)
self.dependencies = []
def compile(se... | 0.296654 | 0.078572 |
__all__ = (
'MalformedNetworkData',
'ServerMessage',
'read_demo_file',
'clear_cache',
)
import dataclasses
import enum
import functools
import inspect
import math
import os
import struct
class MalformedNetworkData(Exception):
pass
def _read(f, n):
s = f.read(n)
if len(s) != n:
... | pyquake/proto.py |
__all__ = (
'MalformedNetworkData',
'ServerMessage',
'read_demo_file',
'clear_cache',
)
import dataclasses
import enum
import functools
import inspect
import math
import os
import struct
class MalformedNetworkData(Exception):
pass
def _read(f, n):
s = f.read(n)
if len(s) != n:
... | 0.387922 | 0.109921 |
from tkinter import *
import math
import polyomino as _mino
SYM_OPTS = ["free", "one-sided", "fixed"]
SYM_COLORS = {'|-\\/%@+XO': "tan",
'|-%+': "magenta",
'\\/%X': "yellow",
'%@': "cyan",
'|': "red",
'-': "red",
'\\': "green",
'/': "g... | polyomino_app.py | from tkinter import *
import math
import polyomino as _mino
SYM_OPTS = ["free", "one-sided", "fixed"]
SYM_COLORS = {'|-\\/%@+XO': "tan",
'|-%+': "magenta",
'\\/%X': "yellow",
'%@': "cyan",
'|': "red",
'-': "red",
'\\': "green",
'/': "g... | 0.538255 | 0.159446 |
import os
import time
import pandas as pd
import numpy as np
import json
from hydroDL import kPath, utils
from hydroDL.data import usgs, gageII, gridMET, ntn, transform
from hydroDL.master import basins
from hydroDL.app import waterQuality
"""
instead of saving time series by rho, save the full time series here.
f an... | app/streamflow/prep/wrap-test.py | import os
import time
import pandas as pd
import numpy as np
import json
from hydroDL import kPath, utils
from hydroDL.data import usgs, gageII, gridMET, ntn, transform
from hydroDL.master import basins
from hydroDL.app import waterQuality
"""
instead of saving time series by rho, save the full time series here.
f an... | 0.239616 | 0.170888 |
import math
from datetime import timedelta
from datetime import datetime
MAX_GEE_PIXELS_DOWNLOAD = 1048576
GEE_ERROR_PLACEHOLDER = "ImageCollection.getRegion: Too many values: "
__all__ = ('tile_coordinates', 'retrieve_max_pixel_count_from_pattern',
'cmp_coords', 'get_date_interval_array', 'make_polygon')
... | geesarfetcher/utils/__init__.py | import math
from datetime import timedelta
from datetime import datetime
MAX_GEE_PIXELS_DOWNLOAD = 1048576
GEE_ERROR_PLACEHOLDER = "ImageCollection.getRegion: Too many values: "
__all__ = ('tile_coordinates', 'retrieve_max_pixel_count_from_pattern',
'cmp_coords', 'get_date_interval_array', 'make_polygon')
... | 0.840193 | 0.673903 |
import unittest
import pywintypes
import wellcad.com
from ._extra_asserts import ExtraAsserts
from ._sample_path import SamplePath
class TestEquipmentItem(unittest.TestCase, ExtraAsserts, SamplePath):
@classmethod
def setUpClass(cls):
cls.app = wellcad.com.Application()
cls.sample_path = cls._... | test/test_equipment_item.py | import unittest
import pywintypes
import wellcad.com
from ._extra_asserts import ExtraAsserts
from ._sample_path import SamplePath
class TestEquipmentItem(unittest.TestCase, ExtraAsserts, SamplePath):
@classmethod
def setUpClass(cls):
cls.app = wellcad.com.Application()
cls.sample_path = cls._... | 0.661376 | 0.596727 |
from types import MappingProxyType
from typing import Optional, Iterable
from dataclasses import field
from websockets.server import WebSocketServerProtocol
from dataclasses import dataclass
from ..types import ChannelId, SubscriptionId
@dataclass
class ClientState:
"""
ClientState holds information about su... | python/src/foxglove_websocket/server/client_state.py | from types import MappingProxyType
from typing import Optional, Iterable
from dataclasses import field
from websockets.server import WebSocketServerProtocol
from dataclasses import dataclass
from ..types import ChannelId, SubscriptionId
@dataclass
class ClientState:
"""
ClientState holds information about su... | 0.829146 | 0.107836 |
import discord
from discord.ext import commands,tasks
from discord.utils import get
from discord import FFmpegPCMAudio
import asyncio
import youtube_dl
import os
import math
from dotenv import load_dotenv
load_dotenv()
help_command = commands.DefaultHelpCommand(
no_category = 'Commands'
)
os.system('cls')
bot = c... | bot.py | import discord
from discord.ext import commands,tasks
from discord.utils import get
from discord import FFmpegPCMAudio
import asyncio
import youtube_dl
import os
import math
from dotenv import load_dotenv
load_dotenv()
help_command = commands.DefaultHelpCommand(
no_category = 'Commands'
)
os.system('cls')
bot = c... | 0.16248 | 0.078078 |
import tensorflow as tf
import numpy as np
from sklearn.manifold import TSNE
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
from segmentpy.tf114.util import check_N_mkdir
def tsne_on_activation(embedded_tensor, l... | src/segmentpy/tf114/tsne.py | import tensorflow as tf
import numpy as np
from sklearn.manifold import TSNE
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
from segmentpy.tf114.util import check_N_mkdir
def tsne_on_activation(embedded_tensor, l... | 0.769124 | 0.637905 |
import os
from login import *
list_categorias = []
def categorias ():
os.system('cls')
print(":::: MENU CATEGORIAS ::::")
print("[1.] INGRESAR NUEVA CATEGORIA")
print("[2.] LISTAR CATEGORIAS")
print("[3.] BUSCAR UNA CATEGORIA")
print("[4.] MODIFICAR CATEGORIA")
print("[5.] ELIMINAR CATEGORIA")
print("[... | Final/categorias.py | import os
from login import *
list_categorias = []
def categorias ():
os.system('cls')
print(":::: MENU CATEGORIAS ::::")
print("[1.] INGRESAR NUEVA CATEGORIA")
print("[2.] LISTAR CATEGORIAS")
print("[3.] BUSCAR UNA CATEGORIA")
print("[4.] MODIFICAR CATEGORIA")
print("[5.] ELIMINAR CATEGORIA")
print("[... | 0.053949 | 0.194119 |
from __future__ import print_function
import argparse
import os
import sys
import numpy as np
import pandas as pd
def process_header_lines(header_lines):
h = {}
for l in header_lines:
split = l.strip('#').strip("\n").split("=", 1)
try:
if not split[0] in h:
h[spli... | full_pipeline/oncodrivefm_input_file_generator.py |
from __future__ import print_function
import argparse
import os
import sys
import numpy as np
import pandas as pd
def process_header_lines(header_lines):
h = {}
for l in header_lines:
split = l.strip('#').strip("\n").split("=", 1)
try:
if not split[0] in h:
h[spli... | 0.368065 | 0.275118 |
class CoalaIpError(Exception):
"""Base class for all Coala IP errors."""
class IncompatiblePluginError(CoalaIpError, ValueError):
"""Raised when entities with incompatible plugins are used together.
Should contain a list of the incompatible plugins as the first
argument.
"""
@property
def... | coalaip/exceptions.py | class CoalaIpError(Exception):
"""Base class for all Coala IP errors."""
class IncompatiblePluginError(CoalaIpError, ValueError):
"""Raised when entities with incompatible plugins are used together.
Should contain a list of the incompatible plugins as the first
argument.
"""
@property
def... | 0.931252 | 0.356167 |
import numpy as np
import paddle
from paddle.autograd.functional import vjp as _vjp
def ternary(cond, x, y):
expanding_dim = x.dim() - cond.dim()
assert expanding_dim >= 0
for _ in range(expanding_dim):
cond = cond.unsqueeze(-1)
if cond.shape != x.shape:
cond = cond.broadcast_t... | python/paddle/incubate/optimizer/functional/bfgs_utils.py |
import numpy as np
import paddle
from paddle.autograd.functional import vjp as _vjp
def ternary(cond, x, y):
expanding_dim = x.dim() - cond.dim()
assert expanding_dim >= 0
for _ in range(expanding_dim):
cond = cond.unsqueeze(-1)
if cond.shape != x.shape:
cond = cond.broadcast_t... | 0.927306 | 0.637496 |
import base64
import json
import os
from django.conf import settings
from waiting import wait, TimeoutExpired
from sandbox.apps.devices.core.emulators import emulators_controller
from sandbox.libs.logs.core.ws import ws_log_message
from sandbox.apps.provision.core.common import provision_generated_predicate
from sand... | iot-sandbox/sandbox/sandbox/apps/devices/core/provision.py | import base64
import json
import os
from django.conf import settings
from waiting import wait, TimeoutExpired
from sandbox.apps.devices.core.emulators import emulators_controller
from sandbox.libs.logs.core.ws import ws_log_message
from sandbox.apps.provision.core.common import provision_generated_predicate
from sand... | 0.427516 | 0.097691 |
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from bluebottle.utils.model_dispatcher import get_model_mapping
MODEL_MAP = get_model_mapping()
class Migration(DataMigration):
depends_on = (
('bluebottle.payments_logger', '0001_initial'),
(... | apps/fund/migrations/0005_migrate_paymentlogs.py | import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from bluebottle.utils.model_dispatcher import get_model_mapping
MODEL_MAP = get_model_mapping()
class Migration(DataMigration):
depends_on = (
('bluebottle.payments_logger', '0001_initial'),
(... | 0.432543 | 0.116387 |
__version__ = '0.1'
__versionTime__ = '2013-03-29'
__author__ = '<NAME> <<EMAIL>>'
__doc__ = '''
pybass_sfx.py - is ctypes python module for
BASS_SFX - An extension allowing the use of Sonique, Winamp,
Windows Media Player, and BassBox visual plugins with BASS.
'''
import ctypes
try:
import bass
import py... | modpybass/pybass_sfx.py |
__version__ = '0.1'
__versionTime__ = '2013-03-29'
__author__ = '<NAME> <<EMAIL>>'
__doc__ = '''
pybass_sfx.py - is ctypes python module for
BASS_SFX - An extension allowing the use of Sonique, Winamp,
Windows Media Player, and BassBox visual plugins with BASS.
'''
import ctypes
try:
import bass
import py... | 0.335677 | 0.155655 |
import doubly_linked_list as dll
class LRUCache:
'''
LRUCache represents cache with LRU Heuristic
'''
capacity = 0
doubly_list = dll.DoublyLinkedList()
node_map = {}
def __init__(self, capacity):
'''
Initliaze the cache with fixed capacity
'''
self.capacity... | algorithms/lru_cache.py | import doubly_linked_list as dll
class LRUCache:
'''
LRUCache represents cache with LRU Heuristic
'''
capacity = 0
doubly_list = dll.DoublyLinkedList()
node_map = {}
def __init__(self, capacity):
'''
Initliaze the cache with fixed capacity
'''
self.capacity... | 0.596198 | 0.354992 |
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import torch
import torch.utils.data as data
from RandAugment import RandAugment
def get_cifar_transforms(args):
mean = [0.49139968, 0.48215827, 0.44653124]
std = [0.24703233, 0.24348505, 0.26158768]
normalize = transform... | src/dataset/cifar.py | import torchvision.datasets as datasets
import torchvision.transforms as transforms
import torch
import torch.utils.data as data
from RandAugment import RandAugment
def get_cifar_transforms(args):
mean = [0.49139968, 0.48215827, 0.44653124]
std = [0.24703233, 0.24348505, 0.26158768]
normalize = transform... | 0.7641 | 0.662455 |
from typing import Union
import torch
from torch import distributions
class BoxUniform(distributions.Independent):
def __init__(
self,
low: Union[torch.Tensor, float],
high: Union[torch.Tensor, float],
reinterpreted_batch_ndims: int = 1,
):
"""Multidimensionqal uniform... | nflows/distributions/uniform.py | from typing import Union
import torch
from torch import distributions
class BoxUniform(distributions.Independent):
def __init__(
self,
low: Union[torch.Tensor, float],
high: Union[torch.Tensor, float],
reinterpreted_batch_ndims: int = 1,
):
"""Multidimensionqal uniform... | 0.974215 | 0.868827 |
import nltk.tokenize.punkt
from os import listdir
from os import path
import re
import io
import shutil
import os
import sys, getopt
# load the sentence tokenizer
ab_tokenizer = nltk.data.load("abkhaz_tokenizer.pickle")
ru_tokenizer = nltk.data.load("russian.pickle")
speech_tokenset = (
"иҳәеит", "рҳәеит", "сҳәеит", ... | utils/tokenize_ab_ru.py | import nltk.tokenize.punkt
from os import listdir
from os import path
import re
import io
import shutil
import os
import sys, getopt
# load the sentence tokenizer
ab_tokenizer = nltk.data.load("abkhaz_tokenizer.pickle")
ru_tokenizer = nltk.data.load("russian.pickle")
speech_tokenset = (
"иҳәеит", "рҳәеит", "сҳәеит", ... | 0.112918 | 0.303706 |
import itertools # set iterator for next word in the file
import pandas as pd
from sklearn.preprocessing import LabelEncoder # convert categorical variables into numerical variables
from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier
from sklearn import metrics # Import scikit-learn me... | NLP/SENTENCE_BOUNDARY_DICTION.py | import itertools # set iterator for next word in the file
import pandas as pd
from sklearn.preprocessing import LabelEncoder # convert categorical variables into numerical variables
from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier
from sklearn import metrics # Import scikit-learn me... | 0.439747 | 0.472136 |
import unittest
from setup.settings import *
from numpy.testing import *
import numpy as np
import dolphindb_numpy as dnp
import pandas as pd
import orca
class FunctionMedianTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
# connect to a DolphinDB server
orca.connect(HOST, PORT, "ad... | tests/numpy_unit_testing/test_function_statistical_median.py | import unittest
from setup.settings import *
from numpy.testing import *
import numpy as np
import dolphindb_numpy as dnp
import pandas as pd
import orca
class FunctionMedianTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
# connect to a DolphinDB server
orca.connect(HOST, PORT, "ad... | 0.611034 | 0.642713 |
LIST_VIDEO_RESPONSES = [
{
"nextPageToken": "~!!~AI9FV7Tc4k5BiAr1Ckwyu",
"files": [
{
"id": "12JCgxaoHrGvd_Vy5grfCTHr",
"name": "test_video_1.mp4",
"mimeType": "video/mp4",
"parents": ["1lSSPf_kx83O0fcmSA9n4-c3dnB"],
... | gdrive_sync/conftest.py |
LIST_VIDEO_RESPONSES = [
{
"nextPageToken": "~!!~AI9FV7Tc4k5BiAr1Ckwyu",
"files": [
{
"id": "12JCgxaoHrGvd_Vy5grfCTHr",
"name": "test_video_1.mp4",
"mimeType": "video/mp4",
"parents": ["1lSSPf_kx83O0fcmSA9n4-c3dnB"],
... | 0.380068 | 0.302229 |
from local_file_system import LocalFileSystem
from language_guesser import LanguageGuesser
from support import is_comment
from linear_phase_parser import LinearPhaseParser
def run_study(args):
sentence = args.get('sentence', '')
local_file_system = LocalFileSystem()
local_file_system.initialize(args)
... | lpparse/main.py | from local_file_system import LocalFileSystem
from language_guesser import LanguageGuesser
from support import is_comment
from linear_phase_parser import LinearPhaseParser
def run_study(args):
sentence = args.get('sentence', '')
local_file_system = LocalFileSystem()
local_file_system.initialize(args)
... | 0.301979 | 0.10711 |
from panda3d.core import Vec3
from GameObject import *
from Item import Item
from Trigger import Trigger
from Spawner import Spawner
import SpecificItems
import SpecificEnemies
import SpecificMiscObjects
class Level():
def __init__(self, levelFile):
self.levelFile = levelFile
self.geometry = loade... | Level.py | from panda3d.core import Vec3
from GameObject import *
from Item import Item
from Trigger import Trigger
from Spawner import Spawner
import SpecificItems
import SpecificEnemies
import SpecificMiscObjects
class Level():
def __init__(self, levelFile):
self.levelFile = levelFile
self.geometry = loade... | 0.324342 | 0.113138 |
import sqlite3 as db
from lib.logger import logger as log
class SQLite:
def __init__(self, dbf):
self.conn = db.connect(dbf)
self.cursor = self.conn.cursor()
def fetchall(self, sql, data=[]):
result = None
if self.cursor.execute(sql, list(data)):
result = self.cur... | commander/lib/sqlite.py | import sqlite3 as db
from lib.logger import logger as log
class SQLite:
def __init__(self, dbf):
self.conn = db.connect(dbf)
self.cursor = self.conn.cursor()
def fetchall(self, sql, data=[]):
result = None
if self.cursor.execute(sql, list(data)):
result = self.cur... | 0.119177 | 0.179674 |
import random
def choose_first():
if random.randint(0, 1) == 0:
return 'Player 2'
else:
return 'Player 1'
def change_player(player):
if player=='Player 1':
return 'Player 2'
else:
return 'Player 1'
def get_board():
b = []
for i in range(0, 24):
... | bingo.py | import random
def choose_first():
if random.randint(0, 1) == 0:
return 'Player 2'
else:
return 'Player 1'
def change_player(player):
if player=='Player 1':
return 'Player 2'
else:
return 'Player 1'
def get_board():
b = []
for i in range(0, 24):
... | 0.045649 | 0.336195 |
import requests
import datetime
from config import DefaultConfig
from database import get_movies, get_recommended
from helpers.keywords import keywords_unique
from helpers.genres import genres
CONFIG = DefaultConfig()
imgURL = 'https://image.tmdb.org/t/p/'
posterURL = f'{imgURL}w342'
backdropURL = f'{imgURL}w300'
M... | helpers/movie_helper.py | import requests
import datetime
from config import DefaultConfig
from database import get_movies, get_recommended
from helpers.keywords import keywords_unique
from helpers.genres import genres
CONFIG = DefaultConfig()
imgURL = 'https://image.tmdb.org/t/p/'
posterURL = f'{imgURL}w342'
backdropURL = f'{imgURL}w300'
M... | 0.230833 | 0.091301 |
import logging
from neon.backends.backend import Block
from neon.backends.gpu import GPU
from nervanagpu import NervanaGPU, GPUTensor
import pycuda.driver as drv
import numpy as np
from functools import wraps
import atexit
logger = logging.getLogger(__name__)
def replicate(method):
def decorate(cls):
@w... | neon/backends/mgpu.py | import logging
from neon.backends.backend import Block
from neon.backends.gpu import GPU
from nervanagpu import NervanaGPU, GPUTensor
import pycuda.driver as drv
import numpy as np
from functools import wraps
import atexit
logger = logging.getLogger(__name__)
def replicate(method):
def decorate(cls):
@w... | 0.584271 | 0.072243 |
import bs4
try:
import Product_Finder.backend.sortResults as sortResults
except:
import sortResults
import datetime as date
from urllib.request import urlopen as urlReq
from bs4 import BeautifulSoup as soup
neweggDBPK = 1
def searchInNewegg(searchString, blockedWord, searchPageDepth, sortPreference, c... | backend/newegg_scrapper.py | import bs4
try:
import Product_Finder.backend.sortResults as sortResults
except:
import sortResults
import datetime as date
from urllib.request import urlopen as urlReq
from bs4 import BeautifulSoup as soup
neweggDBPK = 1
def searchInNewegg(searchString, blockedWord, searchPageDepth, sortPreference, c... | 0.050776 | 0.074804 |
import nltk
import re
import pprint
import random
class Markov(object):
def __init__(self, order=2, dictFile="", maxWordInSentence=20):
self.table = {}
self.inputLineCount = 0
self.inputWordCount = 0
self.setOrder( order )
self.setMaxWordInSentence(maxWordInSentence)
if dictFile:
self.lo... | MarkovChain.py | import nltk
import re
import pprint
import random
class Markov(object):
def __init__(self, order=2, dictFile="", maxWordInSentence=20):
self.table = {}
self.inputLineCount = 0
self.inputWordCount = 0
self.setOrder( order )
self.setMaxWordInSentence(maxWordInSentence)
if dictFile:
self.lo... | 0.082248 | 0.105671 |
import hashlib
import requests
from xml.etree import ElementTree
from aws_requests_auth.aws_auth import AWSRequestsAuth
def create_bucket(host, bucketName, accessKey, secretKey):
"""
Create a bucket.
@param host: S3/Cleversafe host
@param bucketName: Bucket name
@param accessKey: Access Key ID
... | bobos3/bobos3.py |
import hashlib
import requests
from xml.etree import ElementTree
from aws_requests_auth.aws_auth import AWSRequestsAuth
def create_bucket(host, bucketName, accessKey, secretKey):
"""
Create a bucket.
@param host: S3/Cleversafe host
@param bucketName: Bucket name
@param accessKey: Access Key ID
... | 0.747432 | 0.08389 |
from __future__ import absolute_import
import datetime
import re
import pytz
from pytz import UTC
from .util import if_none
#-------------------------------------------------------------------------------
def ensure_date(date):
"""
Attempts to convert an object to a date.
Accepts the following:... | ngrid/datetime.py |
from __future__ import absolute_import
import datetime
import re
import pytz
from pytz import UTC
from .util import if_none
#-------------------------------------------------------------------------------
def ensure_date(date):
"""
Attempts to convert an object to a date.
Accepts the following:... | 0.722037 | 0.340184 |
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sip
from application.view.target_button import TargetButton
from application.view.chess_button import ChessButton
INTERVAL = 50
LONG_RADIUS = INTERVAL * 4
SHORT_RADIUS = INTERVAL * 2
CHESS_SIZE = 30
class GameView(QWidget):
... | surakarta_client/application/view/game_view.py | from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sip
from application.view.target_button import TargetButton
from application.view.chess_button import ChessButton
INTERVAL = 50
LONG_RADIUS = INTERVAL * 4
SHORT_RADIUS = INTERVAL * 2
CHESS_SIZE = 30
class GameView(QWidget):
... | 0.474631 | 0.069321 |
from PIL import Image
import coremltools as ct
import os
import numpy as np
import cv2
import json
from json import JSONEncoder
from pathlib import Path
from objectDetectionMetrics.BoundingBox import BoundingBox
from objectDetectionMetrics.BoundingBoxes import BoundingBoxes
from objectDetectionMetrics.Evaluator impor... | src/coreml_metrics/main.py |
from PIL import Image
import coremltools as ct
import os
import numpy as np
import cv2
import json
from json import JSONEncoder
from pathlib import Path
from objectDetectionMetrics.BoundingBox import BoundingBox
from objectDetectionMetrics.BoundingBoxes import BoundingBoxes
from objectDetectionMetrics.Evaluator impor... | 0.505615 | 0.371393 |
from sqlite3 import connect
from datetime import datetime
from event import Event
from datetime_functions import date_with_dots
class EventsStorage:
"""
Creates database with table 'races' to store info about events.
Manages and stores class Event instances
"""
def __init__(self, db_file):
... | src/eventsstorage.py | from sqlite3 import connect
from datetime import datetime
from event import Event
from datetime_functions import date_with_dots
class EventsStorage:
"""
Creates database with table 'races' to store info about events.
Manages and stores class Event instances
"""
def __init__(self, db_file):
... | 0.632503 | 0.122812 |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_in... | flowable_service_sdk/api/process_definition/delete_process_definition_pb2.py |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_in... | 0.189334 | 0.092237 |
import json
import pickle
import numpy as np
#=======================================================================
PERIODIC_DICT = {'True': 1, 'False': 0}
#=======================================================================
def pickle_load(file_name):
return pickle.load(open(file_name, 'rb'))
def pickle... | ParamGenerator/Phoenics/Utils/utils.py |
import json
import pickle
import numpy as np
#=======================================================================
PERIODIC_DICT = {'True': 1, 'False': 0}
#=======================================================================
def pickle_load(file_name):
return pickle.load(open(file_name, 'rb'))
def pickle... | 0.072423 | 0.052887 |
import os
import json
import sys
import boto3
import fire
# TODO: Accept command line args
SAVE_TO_FILE_DIRECTORY = './data'
SAVE_TO_FILE_PATH = '{}/ecr__enum_repos_data.json'.format(SAVE_TO_FILE_DIRECTORY)
module_info = {
'name': 'ecr__enum_repos',
'author': '<NAME> of Rhino Security Labs',
'catego... | modules/ecr__enum_repos/main.py | import os
import json
import sys
import boto3
import fire
# TODO: Accept command line args
SAVE_TO_FILE_DIRECTORY = './data'
SAVE_TO_FILE_PATH = '{}/ecr__enum_repos_data.json'.format(SAVE_TO_FILE_DIRECTORY)
module_info = {
'name': 'ecr__enum_repos',
'author': '<NAME> of Rhino Security Labs',
'catego... | 0.147279 | 0.088544 |
import re
from jwt import PyJWTError
from tornado.httputil import HTTPServerRequest
from kairon.shared.account.processor import AccountProcessor
from kairon.shared.authorization.processor import IntegrationProcessor
from kairon.shared.data.constant import TOKEN_TYPE
from kairon.shared.models import User
from kairon.s... | kairon/shared/tornado/auth.py | import re
from jwt import PyJWTError
from tornado.httputil import HTTPServerRequest
from kairon.shared.account.processor import AccountProcessor
from kairon.shared.authorization.processor import IntegrationProcessor
from kairon.shared.data.constant import TOKEN_TYPE
from kairon.shared.models import User
from kairon.s... | 0.665954 | 0.095223 |
import argparse
import string
class TestGroup:
def __init__(self, name, parent = None):
self.parent = parent
self.name = name
self.testGroups = {}
self.testCases = {}
if parent:
assert not name in parent.testGroups
parent.testGroups[name] = self
def getName (self):
return self.name
def getPath ... | android/scripts/GenAndroidCTSXML.py | import argparse
import string
class TestGroup:
def __init__(self, name, parent = None):
self.parent = parent
self.name = name
self.testGroups = {}
self.testCases = {}
if parent:
assert not name in parent.testGroups
parent.testGroups[name] = self
def getName (self):
return self.name
def getPath ... | 0.257672 | 0.425009 |
from bs4 import BeautifulSoup
from covidvu.pipeline.vujson import SITE_DATA
from covidvu.pipeline.vuupdate import SCRAPED_US_DATA
from covidvu.pipeline.vuupdate import SCRAPED_WORLD_DATA
import copy
import csv
import os
# --- constants ---
TABLES_FILES = {
'LOCATION': {
... | work/covidvu/pipeline/pyavka.py |
from bs4 import BeautifulSoup
from covidvu.pipeline.vujson import SITE_DATA
from covidvu.pipeline.vuupdate import SCRAPED_US_DATA
from covidvu.pipeline.vuupdate import SCRAPED_WORLD_DATA
import copy
import csv
import os
# --- constants ---
TABLES_FILES = {
'LOCATION': {
... | 0.339718 | 0.087759 |
from PyQt5.QtCore import QVariant
import math
from qgis.core import QgsVectorLayer, QgsExpression, QgsExpressionContext, QgsExpressionContextUtils, QgsField
def get_segment_info(datalayer):
"""
Read attributes from gps segment
:param datalayer: gps segment to be read
:return: start feature id,
... | src/gps_reader_pkg/break_finder.py | from PyQt5.QtCore import QVariant
import math
from qgis.core import QgsVectorLayer, QgsExpression, QgsExpressionContext, QgsExpressionContextUtils, QgsField
def get_segment_info(datalayer):
"""
Read attributes from gps segment
:param datalayer: gps segment to be read
:return: start feature id,
... | 0.768907 | 0.60013 |
import numpy as np
from .base import RNNBase
from .linear import LinearLayer
from .activation import Tanh, Softmax, Sigmoid
class RNNCell(RNNBase):
"""
Recurrent neural network cell implementation.
"""
def __init__(self, input_dim, hidden_dim):
"""
Initialize the parameters with the in... | src/dnetworks/layers/recurrent.py | import numpy as np
from .base import RNNBase
from .linear import LinearLayer
from .activation import Tanh, Softmax, Sigmoid
class RNNCell(RNNBase):
"""
Recurrent neural network cell implementation.
"""
def __init__(self, input_dim, hidden_dim):
"""
Initialize the parameters with the in... | 0.913732 | 0.643441 |
import numpy as np
import dolfin
from dolfin import *
from mpi4py import MPI as pyMPI
from leopart import StokesStaticCondensation, FormsStokes
import geopart.stokes.incompressible
import dolfin_dg as dg
comm = pyMPI.COMM_WORLD
mpi_comm = MPI.comm_world
#load mesh,boundaries and coefficients from file
mark = {"Int... | hdg_test/3d/hdg_test.py | import numpy as np
import dolfin
from dolfin import *
from mpi4py import MPI as pyMPI
from leopart import StokesStaticCondensation, FormsStokes
import geopart.stokes.incompressible
import dolfin_dg as dg
comm = pyMPI.COMM_WORLD
mpi_comm = MPI.comm_world
#load mesh,boundaries and coefficients from file
mark = {"Int... | 0.278159 | 0.317916 |
import dask.array
import h5py
import logging
import math
import numpy as np
import os
import pickle
from pytorch_pretrained_bert import BertTokenizer, BertModel
import random
import subprocess
import torch
import urllib
nonbreaking_url = (
'https://raw.githubusercontent.com/moses-smt/mosesdecoder'
'/ef028446f... | src/corpus.py | import dask.array
import h5py
import logging
import math
import numpy as np
import os
import pickle
from pytorch_pretrained_bert import BertTokenizer, BertModel
import random
import subprocess
import torch
import urllib
nonbreaking_url = (
'https://raw.githubusercontent.com/moses-smt/mosesdecoder'
'/ef028446f... | 0.65379 | 0.172416 |
import argparse
import shutil
import sys
import tempfile
from datetime import datetime
import yaml
import socket
import os
from destinations.Destination import Destination
from Target import Target
class BackupContext:
def __init__(self, argparse_callback):
def _load_yaml(filename, required=True):
... | root/opt/der/lib/backup/BackupContext.py | import argparse
import shutil
import sys
import tempfile
from datetime import datetime
import yaml
import socket
import os
from destinations.Destination import Destination
from Target import Target
class BackupContext:
def __init__(self, argparse_callback):
def _load_yaml(filename, required=True):
... | 0.158891 | 0.062417 |
# use tdklib library,which provides a wrapper for tdk testcase script
import tdklib;
from time import sleep;
#Test component to be tested
sysObj = tdklib.TDKScriptingLibrary("sysutil","RDKB");
#IP and Port of box, No need to change,
#This will be replaced with corresponding DUT Ip and port while executing script
ip ... | testscripts/RDKB/component/WIFIAgent/TS_WIFIAGENT_CheckTelemetryMarkerCHUTIL_1_Values.py | # use tdklib library,which provides a wrapper for tdk testcase script
import tdklib;
from time import sleep;
#Test component to be tested
sysObj = tdklib.TDKScriptingLibrary("sysutil","RDKB");
#IP and Port of box, No need to change,
#This will be replaced with corresponding DUT Ip and port while executing script
ip ... | 0.269422 | 0.207094 |
import numpy as np
from tabulate import tabulate
from artemis.general.dead_easy_ui import DeadEasyUI
class TableExplorerUI(DeadEasyUI):
def __init__(self, table_data, col_headers=None, row_headers=None, col_indices=None, row_indices = None):
assert all(len(r)==len(table_data[0]) for r in table_data), "A... | artemis/general/table_ui.py | import numpy as np
from tabulate import tabulate
from artemis.general.dead_easy_ui import DeadEasyUI
class TableExplorerUI(DeadEasyUI):
def __init__(self, table_data, col_headers=None, row_headers=None, col_indices=None, row_indices = None):
assert all(len(r)==len(table_data[0]) for r in table_data), "A... | 0.563858 | 0.404037 |
import argparse
import sys
import json
from decimal import Decimal
import ijson
import requests
def parse_args():
parser = argparse.ArgumentParser(description='Load JSON documents into a CouchDB database')
parser.add_argument('-H', '--host', dest='host', default='localhost')
parser.add_argument('-P', des... | couchdb_load.py |
import argparse
import sys
import json
from decimal import Decimal
import ijson
import requests
def parse_args():
parser = argparse.ArgumentParser(description='Load JSON documents into a CouchDB database')
parser.add_argument('-H', '--host', dest='host', default='localhost')
parser.add_argument('-P', des... | 0.285372 | 0.085709 |
import os
import pdb
import sys
sys.path[0] = os.getcwd()
import cv2
import yaml
import argparse
from PIL import Image
from glob import glob
from os.path import exists, join
from easydict import EasyDict as edict
import torch
import numpy as np
import tracker.sot.lib.models as models
from tracker.so... | demo/sot_demo.py |
import os
import pdb
import sys
sys.path[0] = os.getcwd()
import cv2
import yaml
import argparse
from PIL import Image
from glob import glob
from os.path import exists, join
from easydict import EasyDict as edict
import torch
import numpy as np
import tracker.sot.lib.models as models
from tracker.so... | 0.250729 | 0.136752 |
import logging
from homeassistant.const import TEMP_CELSIUS
from homeassistant.helpers.entity import Entity
from homeassistant.const import (
ATTR_TEMPERATURE
)
from . import DOMAIN, SIGNAL_STATE_UPDATED
from homeassistant.helpers.dispatcher import (
async_dispatcher_connect,
async_dispatcher_send,
)
fr... | custom_components/vallox2mqtt/climate.py | import logging
from homeassistant.const import TEMP_CELSIUS
from homeassistant.helpers.entity import Entity
from homeassistant.const import (
ATTR_TEMPERATURE
)
from . import DOMAIN, SIGNAL_STATE_UPDATED
from homeassistant.helpers.dispatcher import (
async_dispatcher_connect,
async_dispatcher_send,
)
fr... | 0.812161 | 0.147524 |
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from swagger_client.api_client import ApiClient
class CorporationApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.... | swagger_client/api/corporation_api.py | from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from swagger_client.api_client import ApiClient
class CorporationApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.... | 0.715523 | 0.062046 |
from utils import *
import tkinter
import time
COLOUR_BACKGROUND = "#DAB887"
COLOUR_BLACK = "#251507"
COLOUR_WHITE = "#F7F0DF"
COLOUR_NORMAL = "#A96020"
COLOUR_MARKED = "#AF2020"
class Graphics:
# Constructor of the class
def __init__(self, Callback):
self.board = [0] * 51 # stores the board pieces
... | graphics.py | from utils import *
import tkinter
import time
COLOUR_BACKGROUND = "#DAB887"
COLOUR_BLACK = "#251507"
COLOUR_WHITE = "#F7F0DF"
COLOUR_NORMAL = "#A96020"
COLOUR_MARKED = "#AF2020"
class Graphics:
# Constructor of the class
def __init__(self, Callback):
self.board = [0] * 51 # stores the board pieces
... | 0.159479 | 0.10942 |
class HighscoreEntry:
# Konstruktor, der als Eingabewerte den Nickname und
# die erreichten Punkte erwartet
def __init__(self, nickname, points):
self.__nickname = nickname
self.__points = points
# Öffentliche Methode zur Ausgabe eines Strings mit der
# Angabe von Nickname und erre... | loesungen_in_python/09-referenzdatentypen/aufgabe_W_9_03_highscore/aufgabe_W_9_03_highscore.pyde | class HighscoreEntry:
# Konstruktor, der als Eingabewerte den Nickname und
# die erreichten Punkte erwartet
def __init__(self, nickname, points):
self.__nickname = nickname
self.__points = points
# Öffentliche Methode zur Ausgabe eines Strings mit der
# Angabe von Nickname und erre... | 0.358016 | 0.306838 |
# We'll work with heuristics:
# 1. Aggregate height (minimize)
# 2. Complete lines (maximize)
# 3. Holes (minimize)
# 4. Bumpiness (minimize)
import curses
import debug
class AI:
def __init__(self, game):
# The AI has access to its game object, allowing it to directly call methods in order to move and ro... | src/ai.py |
# We'll work with heuristics:
# 1. Aggregate height (minimize)
# 2. Complete lines (maximize)
# 3. Holes (minimize)
# 4. Bumpiness (minimize)
import curses
import debug
class AI:
def __init__(self, game):
# The AI has access to its game object, allowing it to directly call methods in order to move and ro... | 0.635675 | 0.66072 |
import os
import logging
import torch
import torch.nn as nn
import baseline as bl
from baseline.utils import (
export,
Offsets,
write_json,
load_vectorizers,
find_model_basename,
)
from baseline.model import load_model_for
from baseline.vectorizers import (
GOVectorizer,
Dict1DVectorizer,
... | python/mead/pytorch/exporters.py | import os
import logging
import torch
import torch.nn as nn
import baseline as bl
from baseline.utils import (
export,
Offsets,
write_json,
load_vectorizers,
find_model_basename,
)
from baseline.model import load_model_for
from baseline.vectorizers import (
GOVectorizer,
Dict1DVectorizer,
... | 0.78968 | 0.463566 |
import re
import base64
import asyncio
import logging
from typing import Optional, Union
import requests
import wechaty
from wechaty import (
FileBox,
Wechaty,
Contact,
Room,
Message
)
from config import CQ_API_URL
from crud import get_qq_by_wx, add_user
from database import Base, engine, Session,... | src/main.py | import re
import base64
import asyncio
import logging
from typing import Optional, Union
import requests
import wechaty
from wechaty import (
FileBox,
Wechaty,
Contact,
Room,
Message
)
from config import CQ_API_URL
from crud import get_qq_by_wx, add_user
from database import Base, engine, Session,... | 0.640861 | 0.063978 |
import boto3
import logging
from flask import current_app, abort, jsonify
from zappa.asynchronous import task
from reports.tasks.validation import validate_state
from reports.reporting import release_summary
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def publish(task_id, release_id):
""" Set sta... | reports/tasks/publish.py | import boto3
import logging
from flask import current_app, abort, jsonify
from zappa.asynchronous import task
from reports.tasks.validation import validate_state
from reports.reporting import release_summary
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def publish(task_id, release_id):
""" Set sta... | 0.427875 | 0.06951 |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Message',
fields=[
... | api/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Message',
fields=[
... | 0.63409 | 0.179459 |
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.db.models import Lookup, Q, Value
from django.db.models.fields import Field
from django.db.models.functions import Concat
from mptt.fields import TreeForeignKey
from mptt.models import MPTTModel
from treebeard.mp_tree imp... | tests/models.py | from __future__ import absolute_import, unicode_literals
from django.db import models
from django.db.models import Lookup, Q, Value
from django.db.models.fields import Field
from django.db.models.functions import Concat
from mptt.fields import TreeForeignKey
from mptt.models import MPTTModel
from treebeard.mp_tree imp... | 0.698432 | 0.138666 |
import decimal
from django.contrib.auth.models import User
from django.core.cache import caches
from djsettings import djsetting, DjSettingsGroup, values
from djsettings.models import DjSetting
from djsettings.exceptions import InvalidSettingValue
from .base import BaseTestCase
class BaseTestValue:
def test_de... | tests/test_values.py | import decimal
from django.contrib.auth.models import User
from django.core.cache import caches
from djsettings import djsetting, DjSettingsGroup, values
from djsettings.models import DjSetting
from djsettings.exceptions import InvalidSettingValue
from .base import BaseTestCase
class BaseTestValue:
def test_de... | 0.490724 | 0.240763 |
import click
import nisyscfg
from nisyscfg.errors import LibraryError
class DeviceNotFoundError(Exception):
pass
@click.group()
def nisyscfgcli():
"""Manipulate hardware resources detected by NI System Configuration API
========================================================================"""
@nisysc... | nisyscfgcli.py | import click
import nisyscfg
from nisyscfg.errors import LibraryError
class DeviceNotFoundError(Exception):
pass
@click.group()
def nisyscfgcli():
"""Manipulate hardware resources detected by NI System Configuration API
========================================================================"""
@nisysc... | 0.433022 | 0.123524 |
from load import ROOT as R
import numpy as N
import gna.constructors as C
from gna.bundle import *
class integral_2d1d_v01(TransformationBundleLegacy):
def __init__(self, *args, **kwargs):
TransformationBundleLegacy.__init__(self, *args, **kwargs)
self.check_cfg()
def check_cfg(self):
... | packages/legacy/bundles/integral_2d1d_v01.py | from load import ROOT as R
import numpy as N
import gna.constructors as C
from gna.bundle import *
class integral_2d1d_v01(TransformationBundleLegacy):
def __init__(self, *args, **kwargs):
TransformationBundleLegacy.__init__(self, *args, **kwargs)
self.check_cfg()
def check_cfg(self):
... | 0.391988 | 0.113973 |
# Big up for @ochsff for allowing me to rip off part of his code.
import os
import re
import sys
import time
import shutil
import argparse
def color(text, color_code):
if sys.platform == "win32":
return text
return chr(0x1b) + "[" + str(color_code) + "m" + text + chr(0x1b) + "[0m"
def red(text):
... | habu.py |
# Big up for @ochsff for allowing me to rip off part of his code.
import os
import re
import sys
import time
import shutil
import argparse
def color(text, color_code):
if sys.platform == "win32":
return text
return chr(0x1b) + "[" + str(color_code) + "m" + text + chr(0x1b) + "[0m"
def red(text):
... | 0.4917 | 0.144059 |
import json
from decaychain.MeasurementUnit import Concentration
from decaychain.MeasurementUnit import Time
from decaychain.Nuclide import Nuclide
from decaychain.DecayChain import Generator
class Request:
def __init__(self, request_dict):
self.measurements = request_dict.get('measurements')
self... | decaychain/DecayCalculation.py | import json
from decaychain.MeasurementUnit import Concentration
from decaychain.MeasurementUnit import Time
from decaychain.Nuclide import Nuclide
from decaychain.DecayChain import Generator
class Request:
def __init__(self, request_dict):
self.measurements = request_dict.get('measurements')
self... | 0.774754 | 0.250867 |
from jinjabread.functions.salt import saltyaml
import yaml
from jinja2 import Template
import re
import traceback
def lookup(d, key):
''' recursive dictionary lookup until value for a key is found '''
stack = d.items()
while stack:
k, v = stack.pop()
if isinstance(v, dict):
sta... | jinjabread/functions/render_state.py | from jinjabread.functions.salt import saltyaml
import yaml
from jinja2 import Template
import re
import traceback
def lookup(d, key):
''' recursive dictionary lookup until value for a key is found '''
stack = d.items()
while stack:
k, v = stack.pop()
if isinstance(v, dict):
sta... | 0.257392 | 0.217566 |
import re
import sys
import pytest
from num2words import num2words
def strip_non_stress(pronunciation):
return [c for c in pronunciation if c in "012"]
cached_stresses = None
def load_stresses():
global cached_stresses # hack for fast tests
if cached_stresses is not None:
return cached_stresses
... | iamb.py | import re
import sys
import pytest
from num2words import num2words
def strip_non_stress(pronunciation):
return [c for c in pronunciation if c in "012"]
cached_stresses = None
def load_stresses():
global cached_stresses # hack for fast tests
if cached_stresses is not None:
return cached_stresses
... | 0.235812 | 0.363393 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from os import system, name
import sys
import mysql.connector
from statistics import mean
def conexion_sql():
conexion=mysql.connector.connect(host="localhost",
user="-",
pas... | Resaltador Paralelo/Carpeta1/bio.py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from os import system, name
import sys
import mysql.connector
from statistics import mean
def conexion_sql():
conexion=mysql.connector.connect(host="localhost",
user="-",
pas... | 0.212395 | 0.308171 |
with open('Data.txt') as f:
for line in f:
string = line
def is_int(n):
try:
int(n)
return True
except ValueError:
return False
def sum_string(input_string):
sum = 0
for i in [j for j in ':[]{}']:
input_string = input_string.replace(i, ',')
string_com... | Days/Day 12 - JSAbacusFramework.io/Part 2.py | with open('Data.txt') as f:
for line in f:
string = line
def is_int(n):
try:
int(n)
return True
except ValueError:
return False
def sum_string(input_string):
sum = 0
for i in [j for j in ':[]{}']:
input_string = input_string.replace(i, ',')
string_com... | 0.110411 | 0.329419 |
from __future__ import (print_function, division, absolute_import,
unicode_literals)
from collections import OrderedDict, namedtuple
import logging
import os
import xml.etree.ElementTree as etree
from glyphsLib.builder.builders import UFOBuilder
from glyphsLib.builder.custom_params import to_... | Lib/glyphsLib/interpolation.py |
from __future__ import (print_function, division, absolute_import,
unicode_literals)
from collections import OrderedDict, namedtuple
import logging
import os
import xml.etree.ElementTree as etree
from glyphsLib.builder.builders import UFOBuilder
from glyphsLib.builder.custom_params import to_... | 0.61057 | 0.148201 |
import enum
import os, sys
current_path = os.path.dirname(os.path.realpath(__file__))
PROJECT_HOME = os.path.abspath(os.path.join(current_path, os.pardir))
if PROJECT_HOME not in sys.path:
sys.path.append(PROJECT_HOME)
class AgentMode(enum.Enum):
TRAIN = "TRAIN"
TEST = "TEST"
PLAY = "PLAY"
class OS... | codes/e_utils/names.py | import enum
import os, sys
current_path = os.path.dirname(os.path.realpath(__file__))
PROJECT_HOME = os.path.abspath(os.path.join(current_path, os.pardir))
if PROJECT_HOME not in sys.path:
sys.path.append(PROJECT_HOME)
class AgentMode(enum.Enum):
TRAIN = "TRAIN"
TEST = "TEST"
PLAY = "PLAY"
class OS... | 0.252476 | 0.067762 |
import unittest
from google.appengine.ext import testbed
# Local imports
from speaker_lib import speaker, speakerdir
class TestSpeakerDir(unittest.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_datastore_v3_stub()
self.test... | speaker_lib/tests/testspeakerdir.py |
import unittest
from google.appengine.ext import testbed
# Local imports
from speaker_lib import speaker, speakerdir
class TestSpeakerDir(unittest.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_datastore_v3_stub()
self.test... | 0.423339 | 0.532364 |
__author__ = '<EMAIL> (<NAME>)'
import flags
from generation import Generation
import task
def _DecreaseFlag(flags_dict, spec):
"""Decrease the value of the flag that has the specification spec.
If the flag that contains the spec is a boolean flag, it is eliminated.
Otherwise the flag is a numeric flag, its v... | bestflags/iterative_elimination.py | __author__ = '<EMAIL> (<NAME>)'
import flags
from generation import Generation
import task
def _DecreaseFlag(flags_dict, spec):
"""Decrease the value of the flag that has the specification spec.
If the flag that contains the spec is a boolean flag, it is eliminated.
Otherwise the flag is a numeric flag, its v... | 0.870941 | 0.467089 |
import argparse
import json
from common.logger import get_logger
from common.application_exception import ApplicationException
logger = get_logger(__name__)
class CommandLineParser():
def get_options(self):
config = self.__validate_arguments()
return config
def __get_parser(self):
parser = argpar... | cosmos-db-migration-utility/src/configure/commandline_parser.py | import argparse
import json
from common.logger import get_logger
from common.application_exception import ApplicationException
logger = get_logger(__name__)
class CommandLineParser():
def get_options(self):
config = self.__validate_arguments()
return config
def __get_parser(self):
parser = argpar... | 0.379493 | 0.074265 |
import ConfigParser
import random
import json
import datetime
import time
import sqlite3
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.WARNING)
logger = logging.getLogger(__name__)
class Points:
def __init__(self,dbfile):
self._mydb = sq... | points.py | import ConfigParser
import random
import json
import datetime
import time
import sqlite3
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.WARNING)
logger = logging.getLogger(__name__)
class Points:
def __init__(self,dbfile):
self._mydb = sq... | 0.313315 | 0.057998 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('accounts', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = ... | vapor_manager/accounts/migrations/0002_auto_20200319_1756.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('accounts', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = ... | 0.532911 | 0.115811 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import app
import tensorflow as tf
tf.enable_eager_execution()
def get_type_id(tgt_len, tgt_idx, type_val):
tgt_idx_left_shift = tgt_idx[:-1]
type_val_right_shift = type_val[1:]
new_type_id_sh... | pretrain/seq2seq_edit_tf.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import app
import tensorflow as tf
tf.enable_eager_execution()
def get_type_id(tgt_len, tgt_idx, type_val):
tgt_idx_left_shift = tgt_idx[:-1]
type_val_right_shift = type_val[1:]
new_type_id_sh... | 0.5564 | 0.167593 |
from unittest import TestCase, main
from program_graphs import CFG
from program_graphs.cfg.edge_contraction import is_possible_to_contract, edge_contraction_all
import networkx as nx # type: ignore
class TestCFGEdgeContraction(TestCase):
def test_is_contraction_possible_linear(self) -> None:
cfg = CFG()... | program_graphs/cfg/tests/test_edge_contraction.py | from unittest import TestCase, main
from program_graphs import CFG
from program_graphs.cfg.edge_contraction import is_possible_to_contract, edge_contraction_all
import networkx as nx # type: ignore
class TestCFGEdgeContraction(TestCase):
def test_is_contraction_possible_linear(self) -> None:
cfg = CFG()... | 0.604749 | 0.627866 |
import sys
def addFilename(outFile, filename, element):
outFile.write('/**\n')
outFile.write(' * @file: {0}\n'.format(filename))
outFile.write(' * @brief: Implementation of the {0} class\n'.format(element))
outFile.write(' * @author: <NAME>\n *\n')
def addLicence(outFile):
outFile.write(' * <!--------... | dev/fileHeaders.py |
import sys
def addFilename(outFile, filename, element):
outFile.write('/**\n')
outFile.write(' * @file: {0}\n'.format(filename))
outFile.write(' * @brief: Implementation of the {0} class\n'.format(element))
outFile.write(' * @author: <NAME>\n *\n')
def addLicence(outFile):
outFile.write(' * <!--------... | 0.312895 | 0.031351 |
import os
import random
import re
import requests
import shutil
import tempfile
SAVE_DIR = tempfile.gettempdir()
PAGE_WITH_IMAGES_URLS_REGEX = re.compile(
r"<div class=\"thumb-container-big \" id=\"thumb_([0-9]+)\">"
)
IMAGE_URL_REGEX = re.compile(
r"<img class=\"main-content\" width=\"[0-9]+\" height=\"[0-9... | user/.scripts/anime_bg/anime_bg.py |
import os
import random
import re
import requests
import shutil
import tempfile
SAVE_DIR = tempfile.gettempdir()
PAGE_WITH_IMAGES_URLS_REGEX = re.compile(
r"<div class=\"thumb-container-big \" id=\"thumb_([0-9]+)\">"
)
IMAGE_URL_REGEX = re.compile(
r"<img class=\"main-content\" width=\"[0-9]+\" height=\"[0-9... | 0.345547 | 0.082697 |
from astropy import cosmology as cosmo
import json
import numpy as np
from typing import Optional, Union
from os import path
from autoconf import conf
import autofit as af
import autoarray as aa
from autogalaxy import exc
from autogalaxy.hyper.hyper_data import HyperImageSky
from autogalaxy.hyper.hyper_da... | autogalaxy/analysis/analysis.py | from astropy import cosmology as cosmo
import json
import numpy as np
from typing import Optional, Union
from os import path
from autoconf import conf
import autofit as af
import autoarray as aa
from autogalaxy import exc
from autogalaxy.hyper.hyper_data import HyperImageSky
from autogalaxy.hyper.hyper_da... | 0.948466 | 0.476701 |
from asn1crypto.cms import ContentInfo
from asn1crypto.crl import CertificateList
import rpki.roa
import rpki.manifest
from rpki.certificate import RPKICertificate
import os
import sys
import socket
import json
from datetime import datetime
ADDRESS_FAMILY_IPV4 = b'\x00\x01'
ADDRESS_FAMILY_IPV6 = b'\x00\x02'
# Tur... | dump_json.py | from asn1crypto.cms import ContentInfo
from asn1crypto.crl import CertificateList
import rpki.roa
import rpki.manifest
from rpki.certificate import RPKICertificate
import os
import sys
import socket
import json
from datetime import datetime
ADDRESS_FAMILY_IPV4 = b'\x00\x01'
ADDRESS_FAMILY_IPV6 = b'\x00\x02'
# Tur... | 0.219087 | 0.218576 |
import os
import asyncio
import pandas as pd
import numpy as np
from time import sleep, time
from polofutures import RestClient, WsClient
_MAX_ROWS = 500
_LAST_TRADE = 0
# Account Keys
API_KEY = os.environ['PF_API_KEY']
SECRET = os.environ['PF_SECRET']
API_PASS = os.environ['PF_PASS']
# Trading parameters
SYMBOL =... | sample-MM.py |
import os
import asyncio
import pandas as pd
import numpy as np
from time import sleep, time
from polofutures import RestClient, WsClient
_MAX_ROWS = 500
_LAST_TRADE = 0
# Account Keys
API_KEY = os.environ['PF_API_KEY']
SECRET = os.environ['PF_SECRET']
API_PASS = os.environ['PF_PASS']
# Trading parameters
SYMBOL =... | 0.421195 | 0.134378 |
import redis
import json
import os
import boto3
from botocore import config
from counters import *
from vwr.common.sanitize import deep_clean
DDB_TABLE_NAME = os.environ["TOKEN_TABLE"]
EVENT_ID = os.environ["EVENT_ID"]
REDIS_HOST = os.environ["REDIS_HOST"]
REDIS_PORT = os.environ["REDIS_PORT"]
SOLUTION_ID = os.environ... | source/core-api/lambda_functions/reset_initial_state.py | import redis
import json
import os
import boto3
from botocore import config
from counters import *
from vwr.common.sanitize import deep_clean
DDB_TABLE_NAME = os.environ["TOKEN_TABLE"]
EVENT_ID = os.environ["EVENT_ID"]
REDIS_HOST = os.environ["REDIS_HOST"]
REDIS_PORT = os.environ["REDIS_PORT"]
SOLUTION_ID = os.environ... | 0.242026 | 0.109753 |
import re
from urllib.parse import urljoin
from ..base.request import check_network_state, NetworkState
from ..base.sign_in import check_final_state, SignState, Work
from ..utils.net_utils import get_module_name
from ..schema.discuz import Discuz
from ..utils import google_auth
class MainClass(Discuz):
URL = 'ht... | ptsites/sites/skyey2.py | import re
from urllib.parse import urljoin
from ..base.request import check_network_state, NetworkState
from ..base.sign_in import check_final_state, SignState, Work
from ..utils.net_utils import get_module_name
from ..schema.discuz import Discuz
from ..utils import google_auth
class MainClass(Discuz):
URL = 'ht... | 0.270288 | 0.186243 |
import gym
import numpy as np
from ctypes import *
from gym import spaces
from .helper import check_type_in_list
SL_TASK_PASS = 0
SL_TASK_RECEIVE = 1
SL_TASK_MOVE = 2
SL_TASK_INTERCEPT = 3
class ModelInput(Structure):
"""
Model input data structure.
"""
_fields_ = [('own_xyo_x', c_double), ('own_xyo_... | training/utils/structs.py | import gym
import numpy as np
from ctypes import *
from gym import spaces
from .helper import check_type_in_list
SL_TASK_PASS = 0
SL_TASK_RECEIVE = 1
SL_TASK_MOVE = 2
SL_TASK_INTERCEPT = 3
class ModelInput(Structure):
"""
Model input data structure.
"""
_fields_ = [('own_xyo_x', c_double), ('own_xyo_... | 0.830525 | 0.418816 |
from tweetbot.application import app
from service.esutil import es
from configure import es_mappings
from flask import Flask
from flask import request
from flask import abort
from datetime import date
from operator import itemgetter
import json, csv
from service.esutil.querybuilder.query_builder import QueryBu... | tweetbot/views.py | from tweetbot.application import app
from service.esutil import es
from configure import es_mappings
from flask import Flask
from flask import request
from flask import abort
from datetime import date
from operator import itemgetter
import json, csv
from service.esutil.querybuilder.query_builder import QueryBu... | 0.30715 | 0.092442 |
from __future__ import division, print_function
import numpy as np
from einops import rearrange
from math import ceil
class Coherence:
"""compute coherence magnitude and sine and cosine of coherence phase.
C: Number of sensors
T: Number of time frames
F: Number of frequency bins
>>> coherence_... | sins/features/spatial.py | from __future__ import division, print_function
import numpy as np
from einops import rearrange
from math import ceil
class Coherence:
"""compute coherence magnitude and sine and cosine of coherence phase.
C: Number of sensors
T: Number of time frames
F: Number of frequency bins
>>> coherence_... | 0.930023 | 0.508483 |
import os
import qtpy.QtCore
from qtpy.QtWidgets import (QWidget, QVBoxLayout, QSplitter)
from bioimageit_gui.core.framework import BiAction, BiComponent
from bioimageit_gui.runner import (BiRunnerStates, BiRunnerContainer,
BiRunnerModel, BiRunnerComponent,
... | bioimageit_gui/apps/runnerapp.py | import os
import qtpy.QtCore
from qtpy.QtWidgets import (QWidget, QVBoxLayout, QSplitter)
from bioimageit_gui.core.framework import BiAction, BiComponent
from bioimageit_gui.runner import (BiRunnerStates, BiRunnerContainer,
BiRunnerModel, BiRunnerComponent,
... | 0.431584 | 0.068382 |
from typing import Any, Dict, Optional
import logging
from subprocess import call
import yaml
import speech_recognition as sr
import spacy
logging.getLogger().setLevel(logging.INFO)
def _parse_configs() -> Dict[str, str]:
with open("config.yaml") as f:
config = yaml.full_load(f)
assert config, "Fail... | chatbot/util.py | from typing import Any, Dict, Optional
import logging
from subprocess import call
import yaml
import speech_recognition as sr
import spacy
logging.getLogger().setLevel(logging.INFO)
def _parse_configs() -> Dict[str, str]:
with open("config.yaml") as f:
config = yaml.full_load(f)
assert config, "Fail... | 0.587825 | 0.183466 |
#-----------imports------------------------
import os
import boto3, uuid
import psycopg2
import datetime
#-----------main---------------------------
def aws_image_handler(bucket, suffix=''):
# s3 variables used in all three functions
# enter your own image names in the old_names list
old_names = ['image1.... | script.py | #-----------imports------------------------
import os
import boto3, uuid
import psycopg2
import datetime
#-----------main---------------------------
def aws_image_handler(bucket, suffix=''):
# s3 variables used in all three functions
# enter your own image names in the old_names list
old_names = ['image1.... | 0.2763 | 0.0771 |
import cv2
import numpy as np
from PIL import Image
def RGB2BGR(image):
image1=np.zeros_like(image)
for i in range(image.shape[0]):
for j in range(image.shape[1]):
image1[i][j][0]=image[i][j][2]
image1[i][j][1]=image[i][j][1]
image1[i][j][2]=image[i][j][0]
return... | 5.Masking/masking.py | import cv2
import numpy as np
from PIL import Image
def RGB2BGR(image):
image1=np.zeros_like(image)
for i in range(image.shape[0]):
for j in range(image.shape[1]):
image1[i][j][0]=image[i][j][2]
image1[i][j][1]=image[i][j][1]
image1[i][j][2]=image[i][j][0]
return... | 0.286868 | 0.437163 |
from pyvisdk.esxcli.executer import execute_soap
from pyvisdk.esxcli.base import Base
class IscsiAdapterTargetPortalAuthChap(Base):
'''
Operations that can be performed on iSCSI target portal CHAP authentications
'''
moid = 'ha-cli-handler-iscsi-adapter-target-portal-auth-chap'
def set(self, adapte... | pyvisdk/esxcli/handlers/ha_cli_handler_iscsi_adapter_target_portal_auth_chap.py | from pyvisdk.esxcli.executer import execute_soap
from pyvisdk.esxcli.base import Base
class IscsiAdapterTargetPortalAuthChap(Base):
'''
Operations that can be performed on iSCSI target portal CHAP authentications
'''
moid = 'ha-cli-handler-iscsi-adapter-target-portal-auth-chap'
def set(self, adapte... | 0.672009 | 0.137706 |
import tensorflow as tf
from tensorflow import keras
from sklearn.model_selection import StratifiedShuffleSplit
from keras import backend as k
import utils
import numpy as np
import matplotlib.pyplot as plt
(imageTrain, labelTrain), (imageTest, labelTest) = tf.keras.datasets.fashion_mnist.load_data()
plt.figure()
p... | train.py | import tensorflow as tf
from tensorflow import keras
from sklearn.model_selection import StratifiedShuffleSplit
from keras import backend as k
import utils
import numpy as np
import matplotlib.pyplot as plt
(imageTrain, labelTrain), (imageTest, labelTest) = tf.keras.datasets.fashion_mnist.load_data()
plt.figure()
p... | 0.836555 | 0.628208 |
import pytest
import sys
from mock import patch, call
from pathlib import Path
from textwrap import dedent
from phykit.phykit import Phykit
here = Path(__file__)
@pytest.mark.integration
class TestAlignmentLength(object):
@patch("builtins.print")
def test_alignment_length_incorrect_file_path(self, mocked_pr... | tests/integration/alignment/test_alignment_length_integration.py | import pytest
import sys
from mock import patch, call
from pathlib import Path
from textwrap import dedent
from phykit.phykit import Phykit
here = Path(__file__)
@pytest.mark.integration
class TestAlignmentLength(object):
@patch("builtins.print")
def test_alignment_length_incorrect_file_path(self, mocked_pr... | 0.404978 | 0.435781 |