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 os
import re
class TravelPhylogeny(object):
"""
Python Class for Making DNA-Sensors by Creating Phylogeny of life includes Searching, Traversing,
Making Graphs, Downloading Genomic Data using ftp and Creating K-mers manually to accelerate
development project of Biosensors in Bi... | src/phylogeny_travel.py | import os
import re
class TravelPhylogeny(object):
"""
Python Class for Making DNA-Sensors by Creating Phylogeny of life includes Searching, Traversing,
Making Graphs, Downloading Genomic Data using ftp and Creating K-mers manually to accelerate
development project of Biosensors in Bi... | 0.177847 | 0.226131 |
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import logging
import os
from gamelogic import Controller
from multienv import MultiEnv
from malmopy.agents import QLearnerAgent, RewardMetrics, ExploreExploit
from malmopy.backends.chainer import ChainerQFunction
from malmopy import Explorer, Driver,... | PlatformerGame/train.py |
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import logging
import os
from gamelogic import Controller
from multienv import MultiEnv
from malmopy.agents import QLearnerAgent, RewardMetrics, ExploreExploit
from malmopy.backends.chainer import ChainerQFunction
from malmopy import Explorer, Driver,... | 0.516352 | 0.153042 |
import errno
__author__ = "Ricky"
from pack import *
import wx
import platform
import os
import subprocess
class Application(wx.Frame):
def __init__(self, parent, title):
super(Application, self).__init__(parent, title=title, size=(600, 500))
self.init_menu()
self.init_panel()
sel... | wxrun.py | import errno
__author__ = "Ricky"
from pack import *
import wx
import platform
import os
import subprocess
class Application(wx.Frame):
def __init__(self, parent, title):
super(Application, self).__init__(parent, title=title, size=(600, 500))
self.init_menu()
self.init_panel()
sel... | 0.217338 | 0.058723 |
import unittest
from unittest.mock import Mock
# ATS
from pyats.topology import Device, loader
# Metaparser
from genie.metaparser.util.exceptions import SchemaEmptyParserError
from genie.libs.parser.junos.show_mpls import (
ShowMPLSLSPNameDetail, ShowMPLSLSPNameExtensive)
class TestShowMPLSLSPNameDetail(unitte... | src/genie/libs/parser/junos/tests/test_show_mpls.py | import unittest
from unittest.mock import Mock
# ATS
from pyats.topology import Device, loader
# Metaparser
from genie.metaparser.util.exceptions import SchemaEmptyParserError
from genie.libs.parser.junos.show_mpls import (
ShowMPLSLSPNameDetail, ShowMPLSLSPNameExtensive)
class TestShowMPLSLSPNameDetail(unitte... | 0.661376 | 0.352174 |
SAMPLE_PATH = "../../input/2020-18-sample.txt"
INPUT_PATH = "../../input/2020-18-input.txt"
def get_data(filename):
with open(filename) as file:
data = file.read().split("\n\n")
return [parse_data(line.splitlines()) for line in data]
def parse_data(data):
parsed_data = []
for line in data:... | python/2020/day18.py |
SAMPLE_PATH = "../../input/2020-18-sample.txt"
INPUT_PATH = "../../input/2020-18-input.txt"
def get_data(filename):
with open(filename) as file:
data = file.read().split("\n\n")
return [parse_data(line.splitlines()) for line in data]
def parse_data(data):
parsed_data = []
for line in data:... | 0.556882 | 0.506164 |
import os
from pathlib import Path
from typing import MutableMapping, Any, Mapping
import toml
from utils import get_downloads_dir
class Configurator:
def __init__(self, path: str, config: str):
"""
Interfaz que permite crear, leer o guardar un archivo de configuración.
:param path: ru... | reto-05/lesclaz/configurator.py |
import os
from pathlib import Path
from typing import MutableMapping, Any, Mapping
import toml
from utils import get_downloads_dir
class Configurator:
def __init__(self, path: str, config: str):
"""
Interfaz que permite crear, leer o guardar un archivo de configuración.
:param path: ru... | 0.53777 | 0.1873 |
import random
from geometry2d import Line, LineSegment, Intersection
def uniq_rand_int(lowest, highest, used_values, max_retries):
result = random.randint(lowest, highest)
loop_count = 0
while result in used_values:
result = random.randint(lowest, highest)
loop_count += 1
if loo... | level_generator.py | import random
from geometry2d import Line, LineSegment, Intersection
def uniq_rand_int(lowest, highest, used_values, max_retries):
result = random.randint(lowest, highest)
loop_count = 0
while result in used_values:
result = random.randint(lowest, highest)
loop_count += 1
if loo... | 0.448426 | 0.444143 |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import * # NOQA
from future.utils import native_str
import sys
from argparse import ArgumentParser
from collections import OrderedDict
from copy import deepcopy
from struct import unpack
... | IRIS_data_download/IRIS_download_support/obspy/io/mseed/scripts/recordanalyzer.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import * # NOQA
from future.utils import native_str
import sys
from argparse import ArgumentParser
from collections import OrderedDict
from copy import deepcopy
from struct import unpack
... | 0.475118 | 0.206074 |
__author__ = '<NAME> (<EMAIL>)'
import json
import urllib
from xml.etree import cElementTree
import argparse
import html5lib
import logging
from tests.integration.load_test import TaskThread, WebSession
import random
import time
import uuid
# command line arguments parser
PARSER = argparse.ArgumentParser()
PARSER.a... | tests/load_tests.py | __author__ = '<NAME> (<EMAIL>)'
import json
import urllib
from xml.etree import cElementTree
import argparse
import html5lib
import logging
from tests.integration.load_test import TaskThread, WebSession
import random
import time
import uuid
# command line arguments parser
PARSER = argparse.ArgumentParser()
PARSER.a... | 0.506103 | 0.181789 |
import unittest
import numpy as np
from lava.lib.optimization.problems.constraints import (
DiscreteConstraints,
EqualityConstraints,
InequalityConstraints,
ArithmeticConstraints,
Constraints,
)
from lava.lib.optimization.problems.coefficients import (
CoefficientTensorsMixin,
)
class TestD... | tests/lava/lib/optimization/problems/test_constraints.py |
import unittest
import numpy as np
from lava.lib.optimization.problems.constraints import (
DiscreteConstraints,
EqualityConstraints,
InequalityConstraints,
ArithmeticConstraints,
Constraints,
)
from lava.lib.optimization.problems.coefficients import (
CoefficientTensorsMixin,
)
class TestD... | 0.750553 | 0.693629 |
import pytest
import cogctl.cli.bundle.versions as bundle # TODO: Eww, this import
pytestmark = pytest.mark.usefixtures("mocks")
def test_versions_with_no_args_lists_everything(cogctl):
result = cogctl(bundle.versions, [])
assert result.exit_code == 0
assert result.output == """\
BUNDLE ... | tests/cogctl/cli/bundle/test_versions.py | import pytest
import cogctl.cli.bundle.versions as bundle # TODO: Eww, this import
pytestmark = pytest.mark.usefixtures("mocks")
def test_versions_with_no_args_lists_everything(cogctl):
result = cogctl(bundle.versions, [])
assert result.exit_code == 0
assert result.output == """\
BUNDLE ... | 0.196672 | 0.493226 |
import matplotlib.pyplot as plt
import pandas as pd
# Data Analysis
# -----------------------------------------------------------------------------
# dataframes for fresh sand (fsand) and used sand (usand)
fsand = pd.read_csv('../data/microtrac_fsand.csv', skiprows=[1])
usand = pd.read_csv('../data/microtrac_usand.cs... | code/microtrac_sand.py | import matplotlib.pyplot as plt
import pandas as pd
# Data Analysis
# -----------------------------------------------------------------------------
# dataframes for fresh sand (fsand) and used sand (usand)
fsand = pd.read_csv('../data/microtrac_fsand.csv', skiprows=[1])
usand = pd.read_csv('../data/microtrac_usand.cs... | 0.540439 | 0.586404 |
from fastapi import APIRouter, Depends, HTTPException
from .auth.authentication import get_current_user
from app.config import server
from tracardi.service.storage.driver import storage
from pydantic import BaseModel, validator
from typing import List, Optional
from uuid import UUID
from elasticsearch import Elasticsea... | app/api/user_endpoint.py | from fastapi import APIRouter, Depends, HTTPException
from .auth.authentication import get_current_user
from app.config import server
from tracardi.service.storage.driver import storage
from pydantic import BaseModel, validator
from typing import List, Optional
from uuid import UUID
from elasticsearch import Elasticsea... | 0.641535 | 0.07989 |
from mgr_admintask import views
from django.urls import path
app_name = 'admintask'
urlpatterns = [
path('', views.AdminIndex.as_view(),name = 'Admin_Home'),
path('demand/',views.RequestListView.as_view(),name='demand'),
path('success/',views.successView.as_view(),name='success_admin'),
path('create_r... | Code/bin_manager/mgr_admintask/urls.py | from mgr_admintask import views
from django.urls import path
app_name = 'admintask'
urlpatterns = [
path('', views.AdminIndex.as_view(),name = 'Admin_Home'),
path('demand/',views.RequestListView.as_view(),name='demand'),
path('success/',views.successView.as_view(),name='success_admin'),
path('create_r... | 0.324663 | 0.076996 |
from enum import Enum
import inspect
import json
import logging
import os
import time
class RecordTypes(Enum):
log = 0
json = 1
RECORD_TYPES = RecordTypes
def func_io_monitor(func, record_type=RECORD_TYPES.log, record_fp=None, recorder=None, input_log_formatter=None, output_log_formatter=None):
""... | junkdrawer/func_io_monitor.py | from enum import Enum
import inspect
import json
import logging
import os
import time
class RecordTypes(Enum):
log = 0
json = 1
RECORD_TYPES = RecordTypes
def func_io_monitor(func, record_type=RECORD_TYPES.log, record_fp=None, recorder=None, input_log_formatter=None, output_log_formatter=None):
""... | 0.682256 | 0.10325 |
from typing import Sequence
import bcrypt
import enum
import sqlalchemy as sa
from sqlalchemy import and_
from sqlalchemy.orm.query import Query
from neo4japp.database import db, ma
from .common import RDBMSBase, TimestampMixin, HashIdMixin
user_role = db.Table(
'app_user_role',
db.Column(... | appserver/neo4japp/models/auth.py | from typing import Sequence
import bcrypt
import enum
import sqlalchemy as sa
from sqlalchemy import and_
from sqlalchemy.orm.query import Query
from neo4japp.database import db, ma
from .common import RDBMSBase, TimestampMixin, HashIdMixin
user_role = db.Table(
'app_user_role',
db.Column(... | 0.68056 | 0.059976 |
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.patches import Patch
import matplotlib as mpl
import numpy as np
import pandas as pd
def get_meta(number):
"""
Retrieve the level 3 classname and official RGB value for each clc class.
Parameters
----------
number: int
... | RanForCorine/visualization.py | import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.patches import Patch
import matplotlib as mpl
import numpy as np
import pandas as pd
def get_meta(number):
"""
Retrieve the level 3 classname and official RGB value for each clc class.
Parameters
----------
number: int
... | 0.853211 | 0.585871 |
from dataclasses import dataclass
import nox
from nox_helpers.tooling import Ctx, Tool
@dataclass
class Linter(Tool):
"""A tool which is used for linting source code.
This class provides a loose interface for tools which fall under the
category of linters.
"""
def lint(self, session: nox.Sessi... | nox_helpers/linting.py | from dataclasses import dataclass
import nox
from nox_helpers.tooling import Ctx, Tool
@dataclass
class Linter(Tool):
"""A tool which is used for linting source code.
This class provides a loose interface for tools which fall under the
category of linters.
"""
def lint(self, session: nox.Sessi... | 0.826292 | 0.262529 |
from .utils.codeparsers import code_tree
from .utils.objecthashers import complex_hasher
def determine_metadata(func, args, kwargs,
exclusion_list, globals_list,
old_version=False):
metadata = dict()
metadata['func'] = func
metadata['args'] = args
metadata... | src/tributaries/metadata.py | from .utils.codeparsers import code_tree
from .utils.objecthashers import complex_hasher
def determine_metadata(func, args, kwargs,
exclusion_list, globals_list,
old_version=False):
metadata = dict()
metadata['func'] = func
metadata['args'] = args
metadata... | 0.428951 | 0.190385 |
from quotes import quotes
from utils import get_auth, txgvg_dt
import requests
from datetime import datetime
import time
class Tweeter:
def __init__(self):
self.auth = get_auth()
self.start_date = datetime.strptime('2020-11-27', '%Y-%m-%d')
def send_tweet(self):
# Get quote ID based on... | bot.py | from quotes import quotes
from utils import get_auth, txgvg_dt
import requests
from datetime import datetime
import time
class Tweeter:
def __init__(self):
self.auth = get_auth()
self.start_date = datetime.strptime('2020-11-27', '%Y-%m-%d')
def send_tweet(self):
# Get quote ID based on... | 0.343672 | 0.110904 |
from flask import Flask, session, request, render_template, redirect
import time
import order_def
import holding_def
import init
import math
import func_def
myWeb = Flask(__name__)
trade_board_length = 60 # 交易面板容纳的最大订单数量
price_queue_length = 4 # 价格队列的长度
order_limit = 6 # 单个用户订单上限
# 运行中
admin_pwd, user_pwd, buy_order, ... | backend.py | from flask import Flask, session, request, render_template, redirect
import time
import order_def
import holding_def
import init
import math
import func_def
myWeb = Flask(__name__)
trade_board_length = 60 # 交易面板容纳的最大订单数量
price_queue_length = 4 # 价格队列的长度
order_limit = 6 # 单个用户订单上限
# 运行中
admin_pwd, user_pwd, buy_order, ... | 0.167729 | 0.101056 |
import numpy as np
import torch
import torch.nn as nn
import hyper_parameters as parameters
import parameter_calculator as calculator
from torch.utils.data import DataLoader, Dataset
# The path to save the trained generator model.
GEN_PATH = 'saved_models/generator_net.pt'
# The element compositions of the 278 existin... | cardiGAN.py | import numpy as np
import torch
import torch.nn as nn
import hyper_parameters as parameters
import parameter_calculator as calculator
from torch.utils.data import DataLoader, Dataset
# The path to save the trained generator model.
GEN_PATH = 'saved_models/generator_net.pt'
# The element compositions of the 278 existin... | 0.942175 | 0.697184 |
import unittest
import random
import string
import _import_local_thrift # noqa
from thrift.transport import TTransport
from thrift.transport import TZlibTransport
def generate_random_buff():
data = []
buf_len = 1024 * 32
index = 0
while index < buf_len:
run_len = random.randint(1, 64)
... | lib/py/test/thrift_TZlibTransport.py |
import unittest
import random
import string
import _import_local_thrift # noqa
from thrift.transport import TTransport
from thrift.transport import TZlibTransport
def generate_random_buff():
data = []
buf_len = 1024 * 32
index = 0
while index < buf_len:
run_len = random.randint(1, 64)
... | 0.2763 | 0.144994 |
import base64
import pytz
import binascii
from datetime import datetime
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.Hash import SHA256
import hashlib
import jwt
from ratelimiter import RateLimiter
import emailtemplater
from fakedb imp... | api/main.py | import base64
import pytz
import binascii
from datetime import datetime
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.Hash import SHA256
import hashlib
import jwt
from ratelimiter import RateLimiter
import emailtemplater
from fakedb imp... | 0.450601 | 0.087642 |
import uuid
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('s3file', '0001_initial'),
('org', '0001_initial'),
migrations.swappable_dependency(setting... | server/apps/devicescript/migrations/0001_initial.py |
import uuid
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('s3file', '0001_initial'),
('org', '0001_initial'),
migrations.swappable_dependency(setting... | 0.486088 | 0.117623 |
import os
os.system('apt install git')
os.system('apt install libgl1-mesa-glx -y')
os.system('pip install -q git+https://github.com/tensorflow/examples.git')
os.system('pip install opencv-python')
from azureml.core import Run
from azureml.core import Dataset
import glob
import cv2
import random
import matplotlib.pyplot... | Entrainements azure/Unet_training_script.py | import os
os.system('apt install git')
os.system('apt install libgl1-mesa-glx -y')
os.system('pip install -q git+https://github.com/tensorflow/examples.git')
os.system('pip install opencv-python')
from azureml.core import Run
from azureml.core import Dataset
import glob
import cv2
import random
import matplotlib.pyplot... | 0.637595 | 0.263688 |
from requests import Session
from .objects import RateLimit, NationAPI, RegionAPI, WorldAPI, WorldAssemblyAPI, TelegramAPI
from .exceptions import RateLimitReached
from .info import max_safe_requests, ratelimit_max, ratelimit_within, ratelimit_maxsleeps, ratelimit_sleep_time
from .objects import RateLimit, NationAPI, P... | nsapiwrapper/main.py | from requests import Session
from .objects import RateLimit, NationAPI, RegionAPI, WorldAPI, WorldAssemblyAPI, TelegramAPI
from .exceptions import RateLimitReached
from .info import max_safe_requests, ratelimit_max, ratelimit_within, ratelimit_maxsleeps, ratelimit_sleep_time
from .objects import RateLimit, NationAPI, P... | 0.572603 | 0.066025 |
class PlacementData:
def __init__(self, placement, board):
self.placement = placement
self.board = board
self.curr_x = None
self.curr_y = None
self.next_x = None
self.next_y = None
self.obj_number = None
self.placement_type = None
self.set_p... | CORE/util/placement_data.py | class PlacementData:
def __init__(self, placement, board):
self.placement = placement
self.board = board
self.curr_x = None
self.curr_y = None
self.next_x = None
self.next_y = None
self.obj_number = None
self.placement_type = None
self.set_p... | 0.503418 | 0.230638 |
import pytest
from asociate.dto.association import AddMemberRequestObject
from asociate.interactors.association import AssociationAddMember
from asociate.repository.exceptions import (
AssociationNotFoundError,
InvalidMemberDataError,
)
pytestmark = [
pytest.mark.interactors,
]
def test_association_add_... | tests/interactors/association/test_add_member.py | import pytest
from asociate.dto.association import AddMemberRequestObject
from asociate.interactors.association import AssociationAddMember
from asociate.repository.exceptions import (
AssociationNotFoundError,
InvalidMemberDataError,
)
pytestmark = [
pytest.mark.interactors,
]
def test_association_add_... | 0.655115 | 0.37359 |
from .lib import AssignPoints, CreateStatus
from .forms import User_Registration
from django.contrib import messages
from django.shortcuts import render, redirect
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, log... | Gamify/User/views.py | from .lib import AssignPoints, CreateStatus
from .forms import User_Registration
from django.contrib import messages
from django.shortcuts import render, redirect
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, log... | 0.326164 | 0.076926 |
import numpy as np
import tensorflow as tf
from keras import backend as K
from keras import activations
from keras import initializers
from keras import regularizers
from keras import constraints
from keras.engine.base_layer import Layer
from keras.engine.base_layer import InputSpec
from keras.utils import conv_utils
... | models/layers/interleave_convolutional.py | import numpy as np
import tensorflow as tf
from keras import backend as K
from keras import activations
from keras import initializers
from keras import regularizers
from keras import constraints
from keras.engine.base_layer import Layer
from keras.engine.base_layer import InputSpec
from keras.utils import conv_utils
... | 0.934073 | 0.595934 |
import matplotlib
import matplotlib.pyplot as plt
import textwrap
import requests
import pandas as pd
from bs4 import BeautifulSoup
# Import Matplotlib radio button widget
from matplotlib.widgets import RadioButtons
url = "https://www.bls.gov/emp/ep_table_001.htm"
response = requests.get(url)
bs = Beautif... | Chapter06/chapter6_tkinter.py | import matplotlib
import matplotlib.pyplot as plt
import textwrap
import requests
import pandas as pd
from bs4 import BeautifulSoup
# Import Matplotlib radio button widget
from matplotlib.widgets import RadioButtons
url = "https://www.bls.gov/emp/ep_table_001.htm"
response = requests.get(url)
bs = Beautif... | 0.356559 | 0.22547 |
from dataHandler import dataHandler
from settingsHandler import SettingsHandler
from mcd_interface import MCDInterface
import dataHandler
import constants
import modules_helpers
from tqdm import tqdm
import os
from tkinter import *
import tkinter.filedialog
settings_handler = SettingsHandler()
mcd_interface = MCDIn... | project/modules/modules.py | from dataHandler import dataHandler
from settingsHandler import SettingsHandler
from mcd_interface import MCDInterface
import dataHandler
import constants
import modules_helpers
from tqdm import tqdm
import os
from tkinter import *
import tkinter.filedialog
settings_handler = SettingsHandler()
mcd_interface = MCDIn... | 0.38168 | 0.378373 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class AbstractFusion(nn.Module):
def __init__(self, opt={}):
super(AbstractFusion, self).__init__()
self.opt = opt
def forward(self, input_v, input_q):
raise NotImpleme... | models/multiatt/Mutan.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class AbstractFusion(nn.Module):
def __init__(self, opt={}):
super(AbstractFusion, self).__init__()
self.opt = opt
def forward(self, input_v, input_q):
raise NotImpleme... | 0.885136 | 0.296463 |
import pytest
from polyline import ClosedPolyline
def test_polygon_init_empty():
path = ClosedPolyline()
assert not len(path)
def test_polygon_init_nonempty():
"""You can give any number of points to a path at instantiation"""
points = [(0, 0), (5, 0), (5, 5), (5, 10), (10, 10)]
path = ClosedPo... | test_closed_polyline.py | import pytest
from polyline import ClosedPolyline
def test_polygon_init_empty():
path = ClosedPolyline()
assert not len(path)
def test_polygon_init_nonempty():
"""You can give any number of points to a path at instantiation"""
points = [(0, 0), (5, 0), (5, 5), (5, 10), (10, 10)]
path = ClosedPo... | 0.836454 | 0.820685 |
import numpy as np
import random
class Game():
def __init__(self):
self.labels = [["FREE",
"'I played that so well'",
"Unintelligible moaning",
"Has incorrect runes"],
["Initiates an FF vote",
... | bingo.py | import numpy as np
import random
class Game():
def __init__(self):
self.labels = [["FREE",
"'I played that so well'",
"Unintelligible moaning",
"Has incorrect runes"],
["Initiates an FF vote",
... | 0.234231 | 0.52756 |
import os
import cv2
import imutils
from deepstar.filesystem.transform_file import TransformFile
from deepstar.filesystem.transform_set_sub_dir import TransformSetSubDir
from deepstar.models.transform_model import TransformModel
from deepstar.models.transform_set_model import TransformSetModel
from deepstar.util.debu... | deepstar/plugins/resize_transform_set_select_extract_plugin.py | import os
import cv2
import imutils
from deepstar.filesystem.transform_file import TransformFile
from deepstar.filesystem.transform_set_sub_dir import TransformSetSubDir
from deepstar.models.transform_model import TransformModel
from deepstar.models.transform_set_model import TransformSetModel
from deepstar.util.debu... | 0.461259 | 0.222912 |
from __future__ import print_function, division
import os
import sys
import timeit
import argparse
import numpy as np
import core
import torch
from core.NeuralEssentials import DataSets, MakeModel, VisPlots, SaveModel,\
MakeGIF
from torch.optim import Adam
def parse_args():
parser = argparse.ArgumentParser(d... | pggan_cifar10.py |
from __future__ import print_function, division
import os
import sys
import timeit
import argparse
import numpy as np
import core
import torch
from core.NeuralEssentials import DataSets, MakeModel, VisPlots, SaveModel,\
MakeGIF
from torch.optim import Adam
def parse_args():
parser = argparse.ArgumentParser(d... | 0.681197 | 0.194942 |
import torch
import tqdm
from utils.metrics import evaluate
from torch.utils.data import DataLoader
from utils.metrics import Metrics
from dataset.Dataset import TestDataset
from config.config import DefaultConfig
import torch.nn.functional as F
import os
import numpy as np
import imageio
from PIL import Image
from m... | test.py | import torch
import tqdm
from utils.metrics import evaluate
from torch.utils.data import DataLoader
from utils.metrics import Metrics
from dataset.Dataset import TestDataset
from config.config import DefaultConfig
import torch.nn.functional as F
import os
import numpy as np
import imageio
from PIL import Image
from m... | 0.507812 | 0.264314 |
import typing
import tensorflow as tf
from utils import DotDict
from .DefaultMuZero import DefaultMuZero
from utils.loss_utils import scale_gradient, safe_l2norm, scalar_loss
class DecoderMuZero(DefaultMuZero):
"""
Class to override the loss functions for MuZero to jointly train a latent-to-real-state neura... | MuZero/implementations/AEMuZero.py | import typing
import tensorflow as tf
from utils import DotDict
from .DefaultMuZero import DefaultMuZero
from utils.loss_utils import scale_gradient, safe_l2norm, scalar_loss
class DecoderMuZero(DefaultMuZero):
"""
Class to override the loss functions for MuZero to jointly train a latent-to-real-state neura... | 0.908617 | 0.747132 |
from typing import Dict, List, Union
from datetime import datetime
import psycopg2
from sqlalchemy.sql.expression import true
from db.config_database import ConfigDatabase
from sqlalchemy import create_engine, engine
from sqlalchemy.engine.url import URL
from sqlalchemy import text
# TODO: THIS file is slowly being d... | backend/db/access_database.py | from typing import Dict, List, Union
from datetime import datetime
import psycopg2
from sqlalchemy.sql.expression import true
from db.config_database import ConfigDatabase
from sqlalchemy import create_engine, engine
from sqlalchemy.engine.url import URL
from sqlalchemy import text
# TODO: THIS file is slowly being d... | 0.257205 | 0.072407 |
from copy import deepcopy
class Declensor:
"""Declensor class take declension model and give you functions to
for declension.
"""
def __init__(self, rules):
"""Initialize Declensor with the given rules.
Args:
rules (iterable)
"""
self.setModel(rules)
... | dclua/dclua.py | from copy import deepcopy
class Declensor:
"""Declensor class take declension model and give you functions to
for declension.
"""
def __init__(self, rules):
"""Initialize Declensor with the given rules.
Args:
rules (iterable)
"""
self.setModel(rules)
... | 0.877437 | 0.525491 |
import torch
from torch import nn
from torchvision import models, ops
__backbones = {
'vgg16': models.vgg16
}
class DiscoveryModule(nn.Module):
def __init__(self, in_features, out_features):
super().__init__()
self.lin = nn.Linear(in_features, out_features)
def forward(self, x, rois, ta... | wsod/models/.ipynb_checkpoints/melm-checkpoint.py | import torch
from torch import nn
from torchvision import models, ops
__backbones = {
'vgg16': models.vgg16
}
class DiscoveryModule(nn.Module):
def __init__(self, in_features, out_features):
super().__init__()
self.lin = nn.Linear(in_features, out_features)
def forward(self, x, rois, ta... | 0.935265 | 0.431405 |
import collections
import copy
import numbers
import sys
import yaml
SCIONLAB_FUN_THROUGHPUT = 50e6 # Mbps
PLAYER_TIME = 30 # seconds
BW_FACTOR_RANGE = 10
def bytes_for_dest(bw_factor):
return int(SCIONLAB_FUN_THROUGHPUT * PLAYER_TIME * bw_factor / (8 * BW_FACTOR_RANGE))
SINK_SERVER_PORT = 12345
SSH_USER = '... | master/ansible-inv-to-infrastructure.py |
import collections
import copy
import numbers
import sys
import yaml
SCIONLAB_FUN_THROUGHPUT = 50e6 # Mbps
PLAYER_TIME = 30 # seconds
BW_FACTOR_RANGE = 10
def bytes_for_dest(bw_factor):
return int(SCIONLAB_FUN_THROUGHPUT * PLAYER_TIME * bw_factor / (8 * BW_FACTOR_RANGE))
SINK_SERVER_PORT = 12345
SSH_USER = '... | 0.322419 | 0.128963 |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('query', '0023_auto_20181026_1010'),
]
operations = [
migrations.CreateModel(
name='LabeledCommercial',
... | app/query/migrations/0024_labeledcommercial_labeledinterview_labeledpanel.py | from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('query', '0023_auto_20181026_1010'),
]
operations = [
migrations.CreateModel(
name='LabeledCommercial',
... | 0.636014 | 0.156878 |
from django.contrib.auth.models import User
from django.test import TestCase
class AccountTestCase(TestCase):
"""Shared methods for account tests."""
def _create_new_account(
self, username='test', email='<EMAIL>', password='<PASSWORD>'):
"""Creates a new author account."""
respons... | accounts/tests.py | from django.contrib.auth.models import User
from django.test import TestCase
class AccountTestCase(TestCase):
"""Shared methods for account tests."""
def _create_new_account(
self, username='test', email='<EMAIL>', password='<PASSWORD>'):
"""Creates a new author account."""
respons... | 0.647241 | 0.292886 |
import numpy as np
import matplotlib.pyplot as plt
import gpflow
def dbtime(X):
p1 = X[:,0]
p2 = X[:,1]
p3 = X[:,2]
p4 = X[:,3]
p5 = X[:,4]
p6 = X[:,5]
p7 = X[:,6]
p8 = X[:,7]
p9 = X[:,8]
p10 = X[:,9]
return np.sin(p1)*10+np.sin(p2)*5+np.sin(p3)+np.si... | exemple7/run7b.py | import numpy as np
import matplotlib.pyplot as plt
import gpflow
def dbtime(X):
p1 = X[:,0]
p2 = X[:,1]
p3 = X[:,2]
p4 = X[:,3]
p5 = X[:,4]
p6 = X[:,5]
p7 = X[:,6]
p8 = X[:,7]
p9 = X[:,8]
p10 = X[:,9]
return np.sin(p1)*10+np.sin(p2)*5+np.sin(p3)+np.si... | 0.139924 | 0.339034 |
# <NAME> 2019
from math import atan2, cos, pi, sin
import rospy
import tf2_ros
import yaml
from geometry_msgs.msg import (PoseWithCovarianceStamped, Quaternion,
Transform, TransformStamped)
from mech_ros_msgs.msg import Marker, MarkerList
from numpy import dot, linalg, where, zeros, one... | src/Estimated_pose_markers.py |
# <NAME> 2019
from math import atan2, cos, pi, sin
import rospy
import tf2_ros
import yaml
from geometry_msgs.msg import (PoseWithCovarianceStamped, Quaternion,
Transform, TransformStamped)
from mech_ros_msgs.msg import Marker, MarkerList
from numpy import dot, linalg, where, zeros, one... | 0.6488 | 0.322473 |
import random
import string
class Type:
def __init__(self, return_statement, return_type):
self.return_statement = return_statement
self.return_type = return_type
def __str__(self):
return self.return_type
class RandomizedType(Type):
def __init__(self, return_statement, return_t... | generator/type.py | import random
import string
class Type:
def __init__(self, return_statement, return_type):
self.return_statement = return_statement
self.return_type = return_type
def __str__(self):
return self.return_type
class RandomizedType(Type):
def __init__(self, return_statement, return_t... | 0.577853 | 0.218544 |
from .base_trustful import *
debug = False
class BayesianTrustful2(BasePlayer, BaseTrustful):
def __init__(self, *args):
super(BayesianTrustful2, self).__init__(*args)
self.name = 'BayesianTrustful2'
self.card_hint_type = {}
self.discard_tip = [3.1157470722431895, -5.870410617419... | players/bayesian_trustful2.py |
from .base_trustful import *
debug = False
class BayesianTrustful2(BasePlayer, BaseTrustful):
def __init__(self, *args):
super(BayesianTrustful2, self).__init__(*args)
self.name = 'BayesianTrustful2'
self.card_hint_type = {}
self.discard_tip = [3.1157470722431895, -5.870410617419... | 0.445891 | 0.21034 |
import maya.cmds as mc
from prmaya.plugins import prScalarMath
reload(prScalarMath)
SETTINGS = {'plugin_name': 'prScalarMath.py',
'plugin_path': 'C:\Users\paz\Documents\git\prmaya\prmaya\plugins\prScalarMath.py',
'file': 'C:\Users\paz\Documents\git\prmaya\test\plugins\test_prScalarMath.ma',
... | test/plugins/test_prScalarMath.py | import maya.cmds as mc
from prmaya.plugins import prScalarMath
reload(prScalarMath)
SETTINGS = {'plugin_name': 'prScalarMath.py',
'plugin_path': 'C:\Users\paz\Documents\git\prmaya\prmaya\plugins\prScalarMath.py',
'file': 'C:\Users\paz\Documents\git\prmaya\test\plugins\test_prScalarMath.ma',
... | 0.155463 | 0.206314 |
if __name__ == '__main__':
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from carl.utils.doc_building.plotting import radar_factory
env_context_feature_names = {
'CARLMountainCarEnv': ['force',
'goal_position',
'goal_ve... | carl/utils/doc_building/plot_radar.py | if __name__ == '__main__':
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from carl.utils.doc_building.plotting import radar_factory
env_context_feature_names = {
'CARLMountainCarEnv': ['force',
'goal_position',
'goal_ve... | 0.292494 | 0.17774 |
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import permission_required
from django.core.urlresolvers import reverse
from django.views.generic import ListView
from modules.share_module.formater import *
from modules.share_module.permissionMixin import class_view_decorat... | modules/social_security/social_security_detail/code/social_security_detail_list_views.py | from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import permission_required
from django.core.urlresolvers import reverse
from django.views.generic import ListView
from modules.share_module.formater import *
from modules.share_module.permissionMixin import class_view_decorat... | 0.176991 | 0.067117 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | tests/test_unit/test_flux_analysis.py |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | 0.934835 | 0.576005 |
import argparse
from core.imitation_learning import RunModel
import numpy as np
from core.model import RLModel
from core.config import config
def get_arguments_dict():
parser = argparse.ArgumentParser()
parser.add_argument("--folder_name",
help="Where you would like to save the experim... | code/pytorch/LAMPO/visualize_behavior.py | import argparse
from core.imitation_learning import RunModel
import numpy as np
from core.model import RLModel
from core.config import config
def get_arguments_dict():
parser = argparse.ArgumentParser()
parser.add_argument("--folder_name",
help="Where you would like to save the experim... | 0.491212 | 0.095518 |
import os, sys, re, json, time, socket
import threading,subprocess
import random
'''
用于找到所有的可能远端树莓派连进来的端口,逐个去socket读几个字节,确保一个活着状态
避免远端树莓派等autossh连接被ISP给把session杀掉了
'''
#由于配置文件,可能是xxx_config.py,为了便于移植,这里动态载入下
import glob,importlib
app_path = os.path.dirname(os.path.abspath(sys.argv[0]))
sys.path.append(app_path)
cfg_fil... | Google_stonehead/readPorts.py | import os, sys, re, json, time, socket
import threading,subprocess
import random
'''
用于找到所有的可能远端树莓派连进来的端口,逐个去socket读几个字节,确保一个活着状态
避免远端树莓派等autossh连接被ISP给把session杀掉了
'''
#由于配置文件,可能是xxx_config.py,为了便于移植,这里动态载入下
import glob,importlib
app_path = os.path.dirname(os.path.abspath(sys.argv[0]))
sys.path.append(app_path)
cfg_fil... | 0.118742 | 0.098036 |
import functools
import json
from typing import Sequence, Dict, Optional
from pyspark.sql import DataFrame
from pyspark.sql.types import StructType
from spark3.ethereum.type_factory import TypeFactory
from spark3.exceptions import (
ContractABINotConfigured,
ABIFunctionNotFound,
ABIEventNotFound
)
from sp... | spark3/ethereum/contract.py | import functools
import json
from typing import Sequence, Dict, Optional
from pyspark.sql import DataFrame
from pyspark.sql.types import StructType
from spark3.ethereum.type_factory import TypeFactory
from spark3.exceptions import (
ContractABINotConfigured,
ABIFunctionNotFound,
ABIEventNotFound
)
from sp... | 0.807043 | 0.179782 |
import random
# Two dictionaries containing data to draw every side of 6-sided dice.
# For example side '3' is represented by segments 0, 4, 2, 3, 7 from
# DICE_SEGMENTS printed one below another.
DICE_SEGMENTS = {
0: ' .-------.',
1: ' | |',
2: ' | O |',
3: ' | O |',
4: ' ... | example.py |
import random
# Two dictionaries containing data to draw every side of 6-sided dice.
# For example side '3' is represented by segments 0, 4, 2, 3, 7 from
# DICE_SEGMENTS printed one below another.
DICE_SEGMENTS = {
0: ' .-------.',
1: ' | |',
2: ' | O |',
3: ' | O |',
4: ' ... | 0.639736 | 0.596492 |
from instaclient.client import *
if TYPE_CHECKING:
from instaclient.client.instaclient import InstaClient
from instaclient.client.checker import Checker
class Navigator(Checker):
# NAVIGATION PROCEDURES
def _show_nav_bar(self:'InstaClient'):
if self.driver.current_url != ClientUrls.HOME_URL:
... | instaclient/client/navigator.py | from instaclient.client import *
if TYPE_CHECKING:
from instaclient.client.instaclient import InstaClient
from instaclient.client.checker import Checker
class Navigator(Checker):
# NAVIGATION PROCEDURES
def _show_nav_bar(self:'InstaClient'):
if self.driver.current_url != ClientUrls.HOME_URL:
... | 0.414543 | 0.075075 |
from django.db import models
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
# Utilities
from root.utils.models import RootBaseModel
# Models
from root.users.models.users import User
class Category(models.Model):
"""Category model"""
name = models.CharField(
... | root/Acme/models.py |
from django.db import models
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
# Utilities
from root.utils.models import RootBaseModel
# Models
from root.users.models.users import User
class Category(models.Model):
"""Category model"""
name = models.CharField(
... | 0.699562 | 0.10307 |
import matplotlib.pyplot as plt
import os
import subprocess
import numpy as np
from PIL import Image, ImageChops
from PIL import ImageFont
from PIL import ImageDraw
from meld_classifier.dataset import load_combined_hemisphere_data
from meld_classifier.meld_cohort import MeldCohort, MeldSubject
import matplotlib_surface... | meld_classifier/meld_plotting.py | import matplotlib.pyplot as plt
import os
import subprocess
import numpy as np
from PIL import Image, ImageChops
from PIL import ImageFont
from PIL import ImageDraw
from meld_classifier.dataset import load_combined_hemisphere_data
from meld_classifier.meld_cohort import MeldCohort, MeldSubject
import matplotlib_surface... | 0.323166 | 0.37912 |
begin_unit
comment|'# Copyright 2011-2014 IBM'
nl|'\n'
comment|'# All Rights Reserved.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'# ... | nova/tests/unit/scheduler/weights/test_weights_hosts.py | begin_unit
comment|'# Copyright 2011-2014 IBM'
nl|'\n'
comment|'# All Rights Reserved.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'# ... | 0.751922 | 0.086942 |
import logging
from application_properties.application_properties import ApplicationProperties
LOGGER = logging.getLogger(__name__)
class ApplicationPropertiesFacade:
"""
Class to provide for a facade in front of an ApplicationProperties instance that
only exposes part of the properties tree.
"""
... | application_properties/application_properties_facade.py | import logging
from application_properties.application_properties import ApplicationProperties
LOGGER = logging.getLogger(__name__)
class ApplicationPropertiesFacade:
"""
Class to provide for a facade in front of an ApplicationProperties instance that
only exposes part of the properties tree.
"""
... | 0.852061 | 0.135261 |
import argparse, sys, os, shutil, subprocess, time
test_case_base = os.path.join(os.getcwd(),'test-cases')
def test_generic(args,num_inputs):
if (args.random_input):
print('%s does not support random testing'%(args.task))
return
td = os.path.join(test_case_base,args.task)
success = 0
... | data-structures/assignments/lab2/test.py | import argparse, sys, os, shutil, subprocess, time
test_case_base = os.path.join(os.getcwd(),'test-cases')
def test_generic(args,num_inputs):
if (args.random_input):
print('%s does not support random testing'%(args.task))
return
td = os.path.join(test_case_base,args.task)
success = 0
... | 0.075853 | 0.121009 |
from data.tasks import MDS_task_generator, WebisCLS10_task_generator
from os.path import abspath, exists
from time import time
from experiments.common import DCIinduction
from model.dci import DCI
from model.pivotselection import pivot_selection
import numpy as np
from util.results import Result
optimize = True
mds_h... | src/experiments/varying_pivots_sentiment.py | from data.tasks import MDS_task_generator, WebisCLS10_task_generator
from os.path import abspath, exists
from time import time
from experiments.common import DCIinduction
from model.dci import DCI
from model.pivotselection import pivot_selection
import numpy as np
from util.results import Result
optimize = True
mds_h... | 0.382833 | 0.285244 |
"""Provides functionality for interacting with shell calls and arguments."""
# pylint: disable=wildcard-import,redefined-builtin,unused-wildcard-import
from __future__ import absolute_import, division, print_function
from builtins import *
# pylint: enable=wildcard-import,redefined-builtin,unused-wildcard-import
impo... | src/imfusion/external/util.py | """Provides functionality for interacting with shell calls and arguments."""
# pylint: disable=wildcard-import,redefined-builtin,unused-wildcard-import
from __future__ import absolute_import, division, print_function
from builtins import *
# pylint: enable=wildcard-import,redefined-builtin,unused-wildcard-import
impo... | 0.887131 | 0.128689 |
from sd3.cfa.dominator import dominates
class Loop:
def __init__(self):
self._nodes = []
def add_node(self, node):
self._nodes.append(node)
def get_node_list(self):
return self._nodes
def has_node(self, node):
return node in self._nodes
def display(self):
... | sd3/cfa/loop.py | from sd3.cfa.dominator import dominates
class Loop:
def __init__(self):
self._nodes = []
def add_node(self, node):
self._nodes.append(node)
def get_node_list(self):
return self._nodes
def has_node(self, node):
return node in self._nodes
def display(self):
... | 0.44083 | 0.154951 |
import unittest
import networkx as nx
import os
import numpy as np
import sys
import math
'''
This class allows for testing of graph generation using unit tests and saves them to a log file so it can be ran from the command line
efficiently
'''
class TestGraph(unittest.TestCase):
'''
Cons... | testing/graph_tests.py | import unittest
import networkx as nx
import os
import numpy as np
import sys
import math
'''
This class allows for testing of graph generation using unit tests and saves them to a log file so it can be ran from the command line
efficiently
'''
class TestGraph(unittest.TestCase):
'''
Cons... | 0.361954 | 0.595669 |
from app import mongo
from flask import jsonify, request
from . import api
from ..backend.search_v2 import search_laws
from ..backend.search import build_main_network_connection
import numpy as np
from flask import make_response
from app import csrf
@api.route('/api/keywords_edge_count', methods=['POST'])
@c... | app/api/routes_v2.py | from app import mongo
from flask import jsonify, request
from . import api
from ..backend.search_v2 import search_laws
from ..backend.search import build_main_network_connection
import numpy as np
from flask import make_response
from app import csrf
@api.route('/api/keywords_edge_count', methods=['POST'])
@c... | 0.350199 | 0.129595 |
class TDIVariable(object):
''' TDIVariable is a place-holder for TDI bits that are supplied
later (allowing us to make reusable templates).
The index is used to determine which data stream to use
to supply the variable data. It defaults to stream 0.
For example, the LEON client's ... | playtag/iotemplate/__init__.py | class TDIVariable(object):
''' TDIVariable is a place-holder for TDI bits that are supplied
later (allowing us to make reusable templates).
The index is used to determine which data stream to use
to supply the variable data. It defaults to stream 0.
For example, the LEON client's ... | 0.741674 | 0.565479 |
import scipy
import numpy as np
from qiskit.circuit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info.synthesis import two_qubit_decompose, one_qubit_decompose
from qiskit.circuit.library.standard_gates import CXGate
from qiskit.quantum_info.operators.predicates import is_hermitian_matrix
from qiskit.exte... | qiskit/quantum_info/synthesis/qsd.py | import scipy
import numpy as np
from qiskit.circuit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info.synthesis import two_qubit_decompose, one_qubit_decompose
from qiskit.circuit.library.standard_gates import CXGate
from qiskit.quantum_info.operators.predicates import is_hermitian_matrix
from qiskit.exte... | 0.869908 | 0.811676 |
from __future__ import print_function
import sys
import time
import serial
import rtmidi
# Defined constants
YM_MAX_NUM_USER_PRESETS = 8
YM_MAX_NUM_DEFAULT_PRESETS = 8
# Num voices
YM_MAX_VOICES = 6
# Num operators
YM_MAX_OPERATORS = 4
# Defined SYSEX CMD
YM_SYSEX_CMD_SET_REG = 0
YM_SYSEX_CMD_SAVE_PRESET = 1
YM_SYS... | Tools/py_tools/YM2612.py | from __future__ import print_function
import sys
import time
import serial
import rtmidi
# Defined constants
YM_MAX_NUM_USER_PRESETS = 8
YM_MAX_NUM_DEFAULT_PRESETS = 8
# Num voices
YM_MAX_VOICES = 6
# Num operators
YM_MAX_OPERATORS = 4
# Defined SYSEX CMD
YM_SYSEX_CMD_SET_REG = 0
YM_SYSEX_CMD_SAVE_PRESET = 1
YM_SYS... | 0.313525 | 0.07627 |
from pathlib import Path
from tqdm import tqdm
import tensorflow as tf
from modules.esrgan import rrdb_net
from modules.lr_scheduler import MultiStepLR
from modules.data import load_dataset
from modules.losses import get_pixel_loss
HAS_WANDB_ACCOUNT = True
PROJECT = 'esrgan-tf2'
import wandb
if not HAS_WAND... | train_psnr.py | from pathlib import Path
from tqdm import tqdm
import tensorflow as tf
from modules.esrgan import rrdb_net
from modules.lr_scheduler import MultiStepLR
from modules.data import load_dataset
from modules.losses import get_pixel_loss
HAS_WANDB_ACCOUNT = True
PROJECT = 'esrgan-tf2'
import wandb
if not HAS_WAND... | 0.649245 | 0.204978 |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='packet_tf',
fields=[
('id', models.AutoField(auto_c... | toolgui/display/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='packet_tf',
fields=[
('id', models.AutoField(auto_c... | 0.662032 | 0.308363 |
from bson import ObjectId, DBRef
import pytest
from datetime import datetime
from dateutil.tz.tz import tzutc, tzoffset
from marshmallow import ValidationError
from uuid import UUID
from umongo.data_proxy import data_proxy_factory
from umongo import Document, EmbeddedDocument, Schema, EmbeddedSchema, fields, Reference... | tests/test_fields.py | from bson import ObjectId, DBRef
import pytest
from datetime import datetime
from dateutil.tz.tz import tzutc, tzoffset
from marshmallow import ValidationError
from uuid import UUID
from umongo.data_proxy import data_proxy_factory
from umongo import Document, EmbeddedDocument, Schema, EmbeddedSchema, fields, Reference... | 0.656878 | 0.343053 |
import json
import logging
import urllib.request
import http.cookiejar
from datetime import datetime, timedelta
from pysmoothstreams import Service
from pysmoothstreams.exceptions import InvalidService
from json import JSONDecodeError
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
class AuthSig... | pysmoothstreams/auth.py | import json
import logging
import urllib.request
import http.cookiejar
from datetime import datetime, timedelta
from pysmoothstreams import Service
from pysmoothstreams.exceptions import InvalidService
from json import JSONDecodeError
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
class AuthSig... | 0.387343 | 0.096748 |
import errno
import glob
import os
import subprocess
import shutil
import tempfile
import time as time1
from astropy.io import fits
from astropy.table import Table
import argparse
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy import time, wcs
import numpy as np
from gmadet.utils i... | gmadet/stacking.py | import errno
import glob
import os
import subprocess
import shutil
import tempfile
import time as time1
from astropy.io import fits
from astropy.table import Table
import argparse
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy import time, wcs
import numpy as np
from gmadet.utils i... | 0.28877 | 0.265836 |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('info', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ServiceInfo',
fields=[
('id', models.... | iservice/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('info', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ServiceInfo',
fields=[
('id', models.... | 0.592195 | 0.162546 |
from gym import spaces
from gym.utils import seeding
import gym
import numpy as np
class Trivial (gym.Env):
metadata = {"render.modes": ["human"]}
reward_range = (-100.0, 100.0)
def __init__ (self):
self.reset()
self.action_space = spaces.Discrete(2)
self.observation_space = spac... | gym-trivial/gym_trivial/envs/trivial_env.py | from gym import spaces
from gym.utils import seeding
import gym
import numpy as np
class Trivial (gym.Env):
metadata = {"render.modes": ["human"]}
reward_range = (-100.0, 100.0)
def __init__ (self):
self.reset()
self.action_space = spaces.Discrete(2)
self.observation_space = spac... | 0.835618 | 0.599778 |
import unittest.mock
import unittest
import os
import pathlib
from ons_csv_to_ctb_json_load import Loader
from helper_funcs import conditional_mock_open, build_test_file
HEADERS = ['Classification_Mnemonic', 'Dataset_Mnemonic', 'Id', 'Processing_Priority',
'Variable_Mnemonic', 'Lowest_Geog_Variable_Flag']
... | test/test_dataset_classifications.py | import unittest.mock
import unittest
import os
import pathlib
from ons_csv_to_ctb_json_load import Loader
from helper_funcs import conditional_mock_open, build_test_file
HEADERS = ['Classification_Mnemonic', 'Dataset_Mnemonic', 'Id', 'Processing_Priority',
'Variable_Mnemonic', 'Lowest_Geog_Variable_Flag']
... | 0.460532 | 0.524395 |
from MVNScrapper import MVNScrapper
from Addons import Addons
import os
import time
import threading
import configparser
import tkinter as tk
import tkinter.filedialog
class Home:
def __init__(self, root):
self._root = root
self._root.title("Deps Ahoy")
description_frame = tk.Frame(self._r... | src/UI.py | from MVNScrapper import MVNScrapper
from Addons import Addons
import os
import time
import threading
import configparser
import tkinter as tk
import tkinter.filedialog
class Home:
def __init__(self, root):
self._root = root
self._root.title("Deps Ahoy")
description_frame = tk.Frame(self._r... | 0.539711 | 0.260055 |
import rospy
import numpy
from duckietown_msgs.msg import FSMState, AprilTagsWithInfos, BoolStamped
from std_msgs.msg import String, Int16 #Imports msg
import urllib2
class RandomAprilTagTurnsNode(object):
def __init__(self):
# Save the name of the node
self.node_name = rospy.get_name()
self... | catkin_ws/src/20-indefinite-navigation/navigation/src/random_april_tag_turns_node.py | import rospy
import numpy
from duckietown_msgs.msg import FSMState, AprilTagsWithInfos, BoolStamped
from std_msgs.msg import String, Int16 #Imports msg
import urllib2
class RandomAprilTagTurnsNode(object):
def __init__(self):
# Save the name of the node
self.node_name = rospy.get_name()
self... | 0.216508 | 0.098642 |
import paddle
from paddle.fluid.layers.nn import embedding, pad
import paddle.nn
from paddle.nn import Embedding
import paddle.nn.functional as F
import paddle.optimizer
import numpy as np
import load
class CBOW(paddle.nn.Layer):
def __init__(self, vocab_size, embedding_size, init_scale=0.5):
super(CBOW,... | CBOW.py | import paddle
from paddle.fluid.layers.nn import embedding, pad
import paddle.nn
from paddle.nn import Embedding
import paddle.nn.functional as F
import paddle.optimizer
import numpy as np
import load
class CBOW(paddle.nn.Layer):
def __init__(self, vocab_size, embedding_size, init_scale=0.5):
super(CBOW,... | 0.872116 | 0.16807 |
from __future__ import absolute_import
import re
import string
class LTemplate(string.Formatter):
"""Formatter class which enables a custom string format for use with product
descriptions.
Both keys/values for specifications are most often capitalized and it better to
leave them in their natural for... | lib/string_util.py | from __future__ import absolute_import
import re
import string
class LTemplate(string.Formatter):
"""Formatter class which enables a custom string format for use with product
descriptions.
Both keys/values for specifications are most often capitalized and it better to
leave them in their natural for... | 0.776581 | 0.374448 |
import uuid
from datetime import datetime
import boto3
from cloud_governance.common.aws.s3.s3_operations import S3Operations
from cloud_governance.zombie_cluster.zombie_cluster_resouces import ZombieClusterResources
short_random_id = str(uuid.uuid1())[0:4]
BUCKET_NAME = f'integration-test-ocp-{short_random_id}-image... | tests/integration/cloud_governance/common/zombie_cluster/test_s3_zombie_delete.py | import uuid
from datetime import datetime
import boto3
from cloud_governance.common.aws.s3.s3_operations import S3Operations
from cloud_governance.zombie_cluster.zombie_cluster_resouces import ZombieClusterResources
short_random_id = str(uuid.uuid1())[0:4]
BUCKET_NAME = f'integration-test-ocp-{short_random_id}-image... | 0.493897 | 0.130147 |
import os
import shutil
import math
from PIL import Image
from beets.plugins import BeetsPlugin
import beetsplug
from beets.ui import Subcommand
from beets import config
from beets import ui
from beets import art
from beets import util
from beets.util import normpath, bytestring_path
from beetsplug.fetchart import F... | beetsplug/arttools/__init__.py |
import os
import shutil
import math
from PIL import Image
from beets.plugins import BeetsPlugin
import beetsplug
from beets.ui import Subcommand
from beets import config
from beets import ui
from beets import art
from beets import util
from beets.util import normpath, bytestring_path
from beetsplug.fetchart import F... | 0.453746 | 0.096323 |
show_device_metadata_localhost="""\
HWSKU DEFAULT BGP STATUS DOCKER ROUTING CONFIG MODE HOSTNAME PLATFORM MAC DEFAULT PFCWD STATUS BGP ASN DEPLOYMENT ID TYPE BUFFER MODEL FRR MGMT FRAMEWORK CONFIG
----------- -------------------- ------------------------... | tests/cli_autogen_input/autogen_test/show_cmd_output.py | show_device_metadata_localhost="""\
HWSKU DEFAULT BGP STATUS DOCKER ROUTING CONFIG MODE HOSTNAME PLATFORM MAC DEFAULT PFCWD STATUS BGP ASN DEPLOYMENT ID TYPE BUFFER MODEL FRR MGMT FRAMEWORK CONFIG
----------- -------------------- ------------------------... | 0.423935 | 0.182863 |
from clyde2.server import PackageServer, GerritPackageServer, TestServer
from clyde2.package import ClydePackage, TestPackage
from clyde2.resolver import resolve_package_dependencies, create_build_tree, get_frozen_packages
from clyde2.generators.ninja_build import generate_file
from clyde2.common import pprint_color, ... | clyde2/package_builder.py | from clyde2.server import PackageServer, GerritPackageServer, TestServer
from clyde2.package import ClydePackage, TestPackage
from clyde2.resolver import resolve_package_dependencies, create_build_tree, get_frozen_packages
from clyde2.generators.ninja_build import generate_file
from clyde2.common import pprint_color, ... | 0.221351 | 0.083666 |
import json
import pytest
import pathlib
from unittest.mock import patch
from o3de import engine_properties
TEST_ENGINE_JSON_PAYLOAD = '''
{
"engine_name": "o3de",
"restricted_name": "o3de",
"FileVersion": 1,
"O3DEVersion": "0.0.0.0",
"O3DECopyrightYear": 2021,
"O3DEBuildNumber": 0,
"ext... | scripts/o3de/tests/unit_test_engine_properties.py |
import json
import pytest
import pathlib
from unittest.mock import patch
from o3de import engine_properties
TEST_ENGINE_JSON_PAYLOAD = '''
{
"engine_name": "o3de",
"restricted_name": "o3de",
"FileVersion": 1,
"O3DEVersion": "0.0.0.0",
"O3DECopyrightYear": 2021,
"O3DEBuildNumber": 0,
"ext... | 0.364891 | 0.302436 |
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.mail import EmailMessage
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.template.context_pro... | accounts/views.py |
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.mail import EmailMessage
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.template.context_pro... | 0.270866 | 0.054879 |
import re
import pickle
import nltk
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
from def_text_summ import ROOT_DIR
def explore_text_and_summaries(text_path, summaries_path,
text_word_tok=False, text_word_tok_path=None):
print("-"*10)
print('Basic p... | src/helpers/text_explorer.py | import re
import pickle
import nltk
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
from def_text_summ import ROOT_DIR
def explore_text_and_summaries(text_path, summaries_path,
text_word_tok=False, text_word_tok_path=None):
print("-"*10)
print('Basic p... | 0.472197 | 0.390418 |
import csv
import json
from django.views import generic
from django.http import HttpResponse
from django.utils.encoding import smart_text
class DataPrepMixin(object):
"""
Provides a method for preping a context object
for serialization as JSON or CSV.
"""
def prep_context_for_serialization(self, c... | calaccess_campaign_browser/views/base.py | import csv
import json
from django.views import generic
from django.http import HttpResponse
from django.utils.encoding import smart_text
class DataPrepMixin(object):
"""
Provides a method for preping a context object
for serialization as JSON or CSV.
"""
def prep_context_for_serialization(self, c... | 0.518546 | 0.143608 |
import boto3
from botocore.exceptions import ClientError
class Storage:
def __init__(self):
self.s3_client = boto3.client("s3")
def login(self,is_lambda=False):#Todo: Find a way to check access to S3 is corect
if is_lambda==True:
self.s3_client = boto3.client("s3")
else:
... | storage.py | import boto3
from botocore.exceptions import ClientError
class Storage:
def __init__(self):
self.s3_client = boto3.client("s3")
def login(self,is_lambda=False):#Todo: Find a way to check access to S3 is corect
if is_lambda==True:
self.s3_client = boto3.client("s3")
else:
... | 0.303835 | 0.06663 |
from enum import Enum
from typing import Union
class MARKER_STYLE(Enum):
nothing = 0
point = 1
pixel = 2
circle = 3
triangle_down = 4
triangle_up = 5
triangle_left = 6
triangle_right = 7
octagon = 8
square = 9
pentagon = 10
star = 11
hexagon_1 = 12
hexagon_2 = ... | mpl_format/enums/marker_style.py | from enum import Enum
from typing import Union
class MARKER_STYLE(Enum):
nothing = 0
point = 1
pixel = 2
circle = 3
triangle_down = 4
triangle_up = 5
triangle_left = 6
triangle_right = 7
octagon = 8
square = 9
pentagon = 10
star = 11
hexagon_1 = 12
hexagon_2 = ... | 0.844858 | 0.273241 |
import graphene
from graphene_django import DjangoObjectType
from graphql import GraphQLError
from django.db.models import Q
from core.models import Category, Account, Transaction, User
from user.schema import UserType
class CategoryType(DjangoObjectType):
class Meta:
model = Category
class AccountType(... | app/account/schema.py | import graphene
from graphene_django import DjangoObjectType
from graphql import GraphQLError
from django.db.models import Q
from core.models import Category, Account, Transaction, User
from user.schema import UserType
class CategoryType(DjangoObjectType):
class Meta:
model = Category
class AccountType(... | 0.490968 | 0.161023 |
from tkinter import *
import backend
class Saviour(object):
def __init__(self):
window.mainloop()
def get_selected_row(self):
global selected_tuple
index = self.list1.curselection()[0]
selected_tuple = self.list1.get(index)
self.e1.delete(0, END)
self.e1.inser... | help_message/original/save_contacts.py | from tkinter import *
import backend
class Saviour(object):
def __init__(self):
window.mainloop()
def get_selected_row(self):
global selected_tuple
index = self.list1.curselection()[0]
selected_tuple = self.list1.get(index)
self.e1.delete(0, END)
self.e1.inser... | 0.257672 | 0.165829 |
import random
from telethon.errors.rpcbaseerrors import ForbiddenError
from telethon.errors.rpcerrorlist import PollOptionInvalidError
from telethon.tl.types import InputMediaPoll, Poll
from audynesia import udy
from ..core.managers import edit_or_reply
from . import Build_Poll, reply_id
plugin_category = "extra"
... | audynesia/plugins/poll.py | import random
from telethon.errors.rpcbaseerrors import ForbiddenError
from telethon.errors.rpcerrorlist import PollOptionInvalidError
from telethon.tl.types import InputMediaPoll, Poll
from audynesia import udy
from ..core.managers import edit_or_reply
from . import Build_Poll, reply_id
plugin_category = "extra"
... | 0.262747 | 0.1139 |
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect
from django.http.response import JsonResponse
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import ListView, DetailView, View
from djang... | posts/views.py | from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect
from django.http.response import JsonResponse
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import ListView, DetailView, View
from djang... | 0.480479 | 0.077413 |
import logging
from argparse import ArgumentParser
from functools import partial
from telegram.ext import Updater, CommandHandler, InlineQueryHandler, CallbackQueryHandler, ConversationHandler
from coinmarketcap import CoinMarketCapAPI
from commands import get_help, set_notifications, clear_notifications, inline_quer... | coin_ticker.py | import logging
from argparse import ArgumentParser
from functools import partial
from telegram.ext import Updater, CommandHandler, InlineQueryHandler, CallbackQueryHandler, ConversationHandler
from coinmarketcap import CoinMarketCapAPI
from commands import get_help, set_notifications, clear_notifications, inline_quer... | 0.52074 | 0.082217 |
import graphene
from gtmcore.workflows.gitlab import GitLabManager
from gtmcore.inventory.inventory import InventoryManager
from gtmcore.inventory.branching import BranchManager
from lmsrvcore.auth.identity import parse_token
from lmsrvcore.auth.user import get_logged_in_username
from lmsrvcore.api.interfaces import ... | packages/gtmapi/lmsrvlabbook/api/objects/commit.py | import graphene
from gtmcore.workflows.gitlab import GitLabManager
from gtmcore.inventory.inventory import InventoryManager
from gtmcore.inventory.branching import BranchManager
from lmsrvcore.auth.identity import parse_token
from lmsrvcore.auth.user import get_logged_in_username
from lmsrvcore.api.interfaces import ... | 0.368065 | 0.158826 |