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 numpy as np from .classes.block import Block from .classes.mesh import Mesh def generate_block(origin, size, n_cells): origin_x = origin[0] origin_y = origin[1] origin_z = origin[2] size_x = size[0] size_y = size[1] size_z = size[2] block_points = [ [origin_x, origin_y,...
src/blockmeshdict_generator/generation.py
import numpy as np from .classes.block import Block from .classes.mesh import Mesh def generate_block(origin, size, n_cells): origin_x = origin[0] origin_y = origin[1] origin_z = origin[2] size_x = size[0] size_y = size[1] size_z = size[2] block_points = [ [origin_x, origin_y,...
0.244814
0.473109
import numpy as np import pandas as pd from collections import Counter import re, regex, os from carnatic import cparser #np.random.seed(42) def _get_bigrams(notations_file): notes = cparser._get_notes_from_file(notations_file) n = 2 ngrams = zip(*[notes[i:] for i in range(n)]) bigrams = [" "....
carnatic/cmarkov.py
import numpy as np import pandas as pd from collections import Counter import re, regex, os from carnatic import cparser #np.random.seed(42) def _get_bigrams(notations_file): notes = cparser._get_notes_from_file(notations_file) n = 2 ngrams = zip(*[notes[i:] for i in range(n)]) bigrams = [" "....
0.284576
0.139367
from client.bcosclient import BcosClient from client.datatype_parser import DatatypeParser import uuid import json import threading from utils.encoding import FriendlyJsonSerde from client.channelpack import ChannelPack from client.channel_push_dispatcher import ChannelPushHandler class EventCallbackHandler: """事...
client/event_callback.py
from client.bcosclient import BcosClient from client.datatype_parser import DatatypeParser import uuid import json import threading from utils.encoding import FriendlyJsonSerde from client.channelpack import ChannelPack from client.channel_push_dispatcher import ChannelPushHandler class EventCallbackHandler: """事...
0.128484
0.064683
from .google_imports import namespace_manager from .google_imports import memcache from . import autobatcher from . import tasklets class MemcacheClient(object): def __init__(self, conn=None, auto_batcher_class=autobatcher.AutoBatcher, max_memcache=None): # NOTE: If conn is not None, config is only used to get ...
ndb/memcache_client.py
from .google_imports import namespace_manager from .google_imports import memcache from . import autobatcher from . import tasklets class MemcacheClient(object): def __init__(self, conn=None, auto_batcher_class=autobatcher.AutoBatcher, max_memcache=None): # NOTE: If conn is not None, config is only used to get ...
0.487551
0.068289
import sys from django.conf import settings from django.core.management import BaseCommand from df_config.utils import is_package_present class Command(BaseCommand): help = "Launch the server process" @property def listen_port(self): add, sep, port = settings.LISTEN_ADDRESS.partition(":") ...
df_config/management/commands/server.py
import sys from django.conf import settings from django.core.management import BaseCommand from df_config.utils import is_package_present class Command(BaseCommand): help = "Launch the server process" @property def listen_port(self): add, sep, port = settings.LISTEN_ADDRESS.partition(":") ...
0.436622
0.101322
import os PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # Application definition INSTALLED_APPS = [ 'box', ...
intranet/intranet/settings/base.py
import os PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # Application definition INSTALLED_APPS = [ 'box', ...
0.366136
0.07393
from __future__ import print_function import time import pandas as pd from docopt import docopt import pyper as pr import pysam def collect_set_XC(input_bam_file): bamfile = pysam.AlignmentFile(input_bam_file, "rb") set_XC = set() for read in bamfile: try: if read.get_tag('GE'):...
correct_barcode.py
from __future__ import print_function import time import pandas as pd from docopt import docopt import pyper as pr import pysam def collect_set_XC(input_bam_file): bamfile = pysam.AlignmentFile(input_bam_file, "rb") set_XC = set() for read in bamfile: try: if read.get_tag('GE'):...
0.457137
0.204401
from __future__ import unicode_literals from .compat import itervalues from .parse_utils import EMPTY_PARSED_PIECE from .pattern import Pattern from .utils import TreeNode, build_tree class PiecePatternNode(TreeNode): """Node for building raw piece tree.""" __slots__ = ('_pattern',) def __init__(self, ...
src/os_urlpattern/piece_pattern_node.py
from __future__ import unicode_literals from .compat import itervalues from .parse_utils import EMPTY_PARSED_PIECE from .pattern import Pattern from .utils import TreeNode, build_tree class PiecePatternNode(TreeNode): """Node for building raw piece tree.""" __slots__ = ('_pattern',) def __init__(self, ...
0.939996
0.296591
import pandas as pd from sklearn.feature_extraction.text import CountVectorizer import os from sklearn.naive_bayes import GaussianNB from sklearn.model_selection import train_test_split from sklearn import metrics import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical, pad_sequences from s...
Homework/2019/Task4/4/Code/dga.py
import pandas as pd from sklearn.feature_extraction.text import CountVectorizer import os from sklearn.naive_bayes import GaussianNB from sklearn.model_selection import train_test_split from sklearn import metrics import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical, pad_sequences from s...
0.396535
0.419172
import sys, time, subprocess from io import BytesIO from PySide2 import QtCore, QtWidgets, QtGui from PySide2.QtWidgets import QMainWindow, QInputDialog from PySide2.QtCore import QSize from PySide2.QtCore import QMimeData from PySide2.QtGui import QDrag, QIcon from PySide2.QtCore import Qt from PySide2.QtCore import...
snapper.py
import sys, time, subprocess from io import BytesIO from PySide2 import QtCore, QtWidgets, QtGui from PySide2.QtWidgets import QMainWindow, QInputDialog from PySide2.QtCore import QSize from PySide2.QtCore import QMimeData from PySide2.QtGui import QDrag, QIcon from PySide2.QtCore import Qt from PySide2.QtCore import...
0.23855
0.106087
import os import logging import browser_cookie3 from pytconf import Config, ParamCreator class ConfigLogging(Config): """ Parameters to control logging """ loglevel = ParamCreator.create_choice( choice_list=[ logging.getLevelName(logging.NOTSET), logging.getLevelName(l...
pyscrapers/configs.py
import os import logging import browser_cookie3 from pytconf import Config, ParamCreator class ConfigLogging(Config): """ Parameters to control logging """ loglevel = ParamCreator.create_choice( choice_list=[ logging.getLevelName(logging.NOTSET), logging.getLevelName(l...
0.555435
0.262192
r""" This module provides argument manipulation functions like pop_arg. """ import gen_print as gp import collections def pop_arg(pop_arg_default=None, *args, **kwargs): r""" Pop a named argument from the args/kwargs and return a tuple consisting of the argument value, the modified args and the modified...
lib/func_args.py
r""" This module provides argument manipulation functions like pop_arg. """ import gen_print as gp import collections def pop_arg(pop_arg_default=None, *args, **kwargs): r""" Pop a named argument from the args/kwargs and return a tuple consisting of the argument value, the modified args and the modified...
0.793186
0.607139
import abc from typing import Dict, List from uuid import uuid4 from wishlist.domain.product.adapters import ( CreateProductAdapter, DeleteProductAdapter, FindProductAdapter, UpdateProductAdapter ) from wishlist.domain.product.models import Product class CreateProductPort(metaclass=abc.ABCMeta): ...
wishlist/domain/product/ports.py
import abc from typing import Dict, List from uuid import uuid4 from wishlist.domain.product.adapters import ( CreateProductAdapter, DeleteProductAdapter, FindProductAdapter, UpdateProductAdapter ) from wishlist.domain.product.models import Product class CreateProductPort(metaclass=abc.ABCMeta): ...
0.693265
0.126812
import logging import sanic from sanic.response import HTTPResponse, json from internals.sanic import SpotilavaBlueprint, SpotilavaSanic logger = logging.getLogger("Tidal.Playlists") tidal_playlists_bp = SpotilavaBlueprint("tidal:playlists", url_prefix="/tidal/") @tidal_playlists_bp.get("/album/<album_id>") async...
routes/tidal/playlists.py
import logging import sanic from sanic.response import HTTPResponse, json from internals.sanic import SpotilavaBlueprint, SpotilavaSanic logger = logging.getLogger("Tidal.Playlists") tidal_playlists_bp = SpotilavaBlueprint("tidal:playlists", url_prefix="/tidal/") @tidal_playlists_bp.get("/album/<album_id>") async...
0.30632
0.149469
import os import re import numpy as np import SimpleITK as sitk import cv2 import torch import random from torch.utils.data import Dataset from utils.project import proj_make_3dinput_v2 def threshold_CTA_mask(cta_image, HU_window=np.array([-263.,553.])): th_cta_image = (cta_image - HU_window[0])/(HU_window[1] - H...
load_data.py
import os import re import numpy as np import SimpleITK as sitk import cv2 import torch import random from torch.utils.data import Dataset from utils.project import proj_make_3dinput_v2 def threshold_CTA_mask(cta_image, HU_window=np.array([-263.,553.])): th_cta_image = (cta_image - HU_window[0])/(HU_window[1] - H...
0.532911
0.354042
from pyimagesearch import social_distancing_config as config from pyimagesearch.detection import detect_people from scipy.spatial import distance as dist import numpy as np import argparse import imutils import cv2 import os ap = argparse.ArgumentParser() ap.add_argument("-i", "--input", type=str, default="", help="...
src/SDD.py
from pyimagesearch import social_distancing_config as config from pyimagesearch.detection import detect_people from scipy.spatial import distance as dist import numpy as np import argparse import imutils import cv2 import os ap = argparse.ArgumentParser() ap.add_argument("-i", "--input", type=str, default="", help="...
0.352982
0.181336
from collections import defaultdict import mock from searx.engines import soundcloud from searx.testing import SearxTestCase from searx.url_utils import quote_plus class TestSoundcloudEngine(SearxTestCase): def test_request(self): query = 'test_query' dicto = defaultdict(dict) dicto['page...
Toolkits/Discovery/meta/searx/tests/unit/engines/test_soundcloud.py
from collections import defaultdict import mock from searx.engines import soundcloud from searx.testing import SearxTestCase from searx.url_utils import quote_plus class TestSoundcloudEngine(SearxTestCase): def test_request(self): query = 'test_query' dicto = defaultdict(dict) dicto['page...
0.608012
0.404949
import os import pybullet as p from normalize_obj import normalize_one_obj import sys import subprocess import json from distutils.dir_util import copy_tree ori_shapenet_dir = '/juno/group/linshao/ShapeNetCore' shapenet_dir = '/scr1/yifan/shapenet_partial' shapenet_new_dir = '/scr1/yifan/geo_data' category_dict = { ...
src/scripts/process_shapenet.py
import os import pybullet as p from normalize_obj import normalize_one_obj import sys import subprocess import json from distutils.dir_util import copy_tree ori_shapenet_dir = '/juno/group/linshao/ShapeNetCore' shapenet_dir = '/scr1/yifan/shapenet_partial' shapenet_new_dir = '/scr1/yifan/geo_data' category_dict = { ...
0.069542
0.05375
import numpy as np import math import mcdc_tnt from timeit import default_timer as timer def error(sim, bench): error = np.linalg.norm(sim - bench) / np.linalg.norm(bench) return(error) if __name__ == '__main__': print() print('ATTENTION') print('Entering Hardware Test Suite') print('Ensu...
tests/integration/tests_hardware.py
import numpy as np import math import mcdc_tnt from timeit import default_timer as timer def error(sim, bench): error = np.linalg.norm(sim - bench) / np.linalg.norm(bench) return(error) if __name__ == '__main__': print() print('ATTENTION') print('Entering Hardware Test Suite') print('Ensu...
0.186947
0.197251
import sys from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QGridLayout, QLabel, QLineEdit, QToolButton, QPushButton) from PyQt5.QtCore import Qt class Login(QWidget): def __init__(self): super().__init__() self.bodyLayout = QGridLayout() # 欢迎登陆图书馆系统标题 self.titleTe...
model/login.py
import sys from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QGridLayout, QLabel, QLineEdit, QToolButton, QPushButton) from PyQt5.QtCore import Qt class Login(QWidget): def __init__(self): super().__init__() self.bodyLayout = QGridLayout() # 欢迎登陆图书馆系统标题 self.titleTe...
0.255437
0.10307
def check_args(r, c, d, i, player): if r > 2 or r < 0: raise ValueError('Unknown row: ' + str(r)) if c > 2 or c < 0: raise ValueError('Unknown column: ' + str(c)) if d > 1 or d < 0: raise ValueError('Unknown diag: ' + str(d)) if i > 8 or i < 0: raise ValueError('Unknown i...
Scripts/Utils/board.py
def check_args(r, c, d, i, player): if r > 2 or r < 0: raise ValueError('Unknown row: ' + str(r)) if c > 2 or c < 0: raise ValueError('Unknown column: ' + str(c)) if d > 1 or d < 0: raise ValueError('Unknown diag: ' + str(d)) if i > 8 or i < 0: raise ValueError('Unknown i...
0.601242
0.618809
import random class Card: """Simple deck card instance, number is 1 to 13 ( 13 being the king) kind is Heards, Spades, Diamonds, Clubs """ kinds = {1: 'Heart', 2: 'Spade', 3: 'Diamond', 4: 'Club'} numbers = {13: 'Ace', 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9, 9: 10, 10: 'Jack', 11: 'Queen...
main.py
import random class Card: """Simple deck card instance, number is 1 to 13 ( 13 being the king) kind is Heards, Spades, Diamonds, Clubs """ kinds = {1: 'Heart', 2: 'Spade', 3: 'Diamond', 4: 'Club'} numbers = {13: 'Ace', 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9, 9: 10, 10: 'Jack', 11: 'Queen...
0.235548
0.318697
from ChromeDriver import create_driver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchElementException from pyvirtualdisplay import Display import os import pickle # TODO: class Player: def __init__(se...
src/Player.py
from ChromeDriver import create_driver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchElementException from pyvirtualdisplay import Display import os import pickle # TODO: class Player: def __init__(se...
0.358915
0.145661
import argparse import ast import itertools import sys import tokenize from typing import Tuple, Iterable, Union, List, cast import flake8.options.manager ComprehensionType = Union[ ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp ] DEFAULT_SELECT = [ "C2000", "C2001", "C2002", "C2020", ...
flake8_multiline_conditionals_comprehensions/mcc_checker.py
import argparse import ast import itertools import sys import tokenize from typing import Tuple, Iterable, Union, List, cast import flake8.options.manager ComprehensionType = Union[ ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp ] DEFAULT_SELECT = [ "C2000", "C2001", "C2002", "C2020", ...
0.522689
0.246828
import argparse import requests import os import cv2 def parse_args(): parser = argparse.ArgumentParser(prog="Send Images From Folder", description="This program sends the images stored in a folder to the cloud face recognition system.") parser.add_argument('--input-folder', required=True, ...
interaction-with-framework/send-images-from-folder/send-images-from-folder.py
import argparse import requests import os import cv2 def parse_args(): parser = argparse.ArgumentParser(prog="Send Images From Folder", description="This program sends the images stored in a folder to the cloud face recognition system.") parser.add_argument('--input-folder', required=True, ...
0.369315
0.160496
from __future__ import print_function import argparse import yaml from pybh.utils import fail, argparse_bool, convert_string_to_array TYPE_STR_MAPPING = { "str": str, "int": int, "float": float, "bool": argparse_bool, } def run(args): with open(args.file, "r") as fin: content = yaml.loa...
pybh/tools/read_yaml_value.py
from __future__ import print_function import argparse import yaml from pybh.utils import fail, argparse_bool, convert_string_to_array TYPE_STR_MAPPING = { "str": str, "int": int, "float": float, "bool": argparse_bool, } def run(args): with open(args.file, "r") as fin: content = yaml.loa...
0.418459
0.20949
import glob import json import os import random import tempfile import unittest from . import train class TrainTest(unittest.TestCase): def setUp(self): self.job_dir = tempfile.mkdtemp() self.num_checkpoints = 10 self.checkpoint_files = [] self.checkpoint_steps = 100 self.test_job_dir = temp...
gce/survival-training/wrapper/train_test.py
import glob import json import os import random import tempfile import unittest from . import train class TrainTest(unittest.TestCase): def setUp(self): self.job_dir = tempfile.mkdtemp() self.num_checkpoints = 10 self.checkpoint_files = [] self.checkpoint_steps = 100 self.test_job_dir = temp...
0.411347
0.432363
import mock import unittest from common import acl from common import constants from common import exceptions class AclTest(unittest.TestCase): def testAdminIsPrivilegedUser(self): self.assertTrue(acl.IsPrivilegedUser('<EMAIL>', True)) def testGooglerIsPrivilegedUser(self): self.assertTrue(acl.IsPrivi...
appengine/findit/common/test/acl_test.py
import mock import unittest from common import acl from common import constants from common import exceptions class AclTest(unittest.TestCase): def testAdminIsPrivilegedUser(self): self.assertTrue(acl.IsPrivilegedUser('<EMAIL>', True)) def testGooglerIsPrivilegedUser(self): self.assertTrue(acl.IsPrivi...
0.546254
0.380932
from nose.tools import * from dateutil.parser import parse as time_parse import yawhois class TestWhoisAudnsNetAuStatusRegistered(object): def setUp(self): fixture_path = "spec/fixtures/responses/whois.audns.net.au/status_registered.txt" host = "whois.audns.net.au" part = ...
test/record/parser/test_response_whois_audns_net_au_status_registered.py
from nose.tools import * from dateutil.parser import parse as time_parse import yawhois class TestWhoisAudnsNetAuStatusRegistered(object): def setUp(self): fixture_path = "spec/fixtures/responses/whois.audns.net.au/status_registered.txt" host = "whois.audns.net.au" part = ...
0.549641
0.229222
import numpy as np import matplotlib.pyplot as pl from configobj import ConfigObj from astropy import units as u import copy import pymcao.wfs as wfs import pymcao.atmosphere as atmosphere import pymcao.sun as sun import logging import time from tqdm import tqdm import threading import pymcao.comm as comm import pymcao...
pymcao/simulator.py
import numpy as np import matplotlib.pyplot as pl from configobj import ConfigObj from astropy import units as u import copy import pymcao.wfs as wfs import pymcao.atmosphere as atmosphere import pymcao.sun as sun import logging import time from tqdm import tqdm import threading import pymcao.comm as comm import pymcao...
0.664867
0.175609
from igia.utils import bed2bam, SeqFile, load_seqinfo from igia.element import identify_element from igia.transcript import identify_transcript import os import unittest class TestAnnotation(unittest.TestCase): def setUp(self): self.ann_dir = "tests/data/ann.bed12" self.size = "tests/data/chrom.si...
tests/test_annotation.py
from igia.utils import bed2bam, SeqFile, load_seqinfo from igia.element import identify_element from igia.transcript import identify_transcript import os import unittest class TestAnnotation(unittest.TestCase): def setUp(self): self.ann_dir = "tests/data/ann.bed12" self.size = "tests/data/chrom.si...
0.473901
0.333496
import os import numpy as np from PIL import Image from pathlib import Path from torch.utils.data import DataLoader, Dataset from torchvision import datasets, transforms from torchvision.io import read_image from typing import Any, Callable, List, Optional, Tuple import torch import cv2 def get_dataloaders(dataset_di...
week4/dataset.py
import os import numpy as np from PIL import Image from pathlib import Path from torch.utils.data import DataLoader, Dataset from torchvision import datasets, transforms from torchvision.io import read_image from typing import Any, Callable, List, Optional, Tuple import torch import cv2 def get_dataloaders(dataset_di...
0.740362
0.533641
"""Example utils.""" import tensorflow as tf import numpy as np from tensor2tensor.data_generators import algorithmic from tensor2tensor.layers import modalities from tensor2tensor.data_generators import problem from tensor2tensor.data_generators import multi_problem_v2 from tensor2tensor.utils import registry from ...
clarify/datasets/utils/example_utils_test.py
"""Example utils.""" import tensorflow as tf import numpy as np from tensor2tensor.data_generators import algorithmic from tensor2tensor.layers import modalities from tensor2tensor.data_generators import problem from tensor2tensor.data_generators import multi_problem_v2 from tensor2tensor.utils import registry from ...
0.935324
0.486819
from dogqc.gpuio import GpuIO from dogqc.cudalang import * import dogqc.identifier as ident import dogqc.querylib as qlib from dogqc.variable import Variable from dogqc.kernel import Kernel, KernelCall from dogqc.types import Type from dogqc.relationalAlgebra import Reduction class Hash ( object ): @staticme...
dogqc/hashTableUtil.py
from dogqc.gpuio import GpuIO from dogqc.cudalang import * import dogqc.identifier as ident import dogqc.querylib as qlib from dogqc.variable import Variable from dogqc.kernel import Kernel, KernelCall from dogqc.types import Type from dogqc.relationalAlgebra import Reduction class Hash ( object ): @staticme...
0.364664
0.180143
from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Field, Div, Reset from django import forms from django.contrib.admin.widgets import FilteredSelectMultiple from django.urls import reverse from django.utils.translation import gettext as __ from django.utils.translation import ge...
booking/forms.py
from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Field, Div, Reset from django import forms from django.contrib.admin.widgets import FilteredSelectMultiple from django.urls import reverse from django.utils.translation import gettext as __ from django.utils.translation import ge...
0.653459
0.137475
import asyncio import weakref import aiohttp import sys import json import traceback import logging from urllib.parse import quote as _uriquote from ..errors import HTTPException, Forbidden, NotFound, ServerError, SentinelError log = logging.getLogger(__name__) class Route: BASE = "https://discord.com/api/v9" ...
sentinel/rest/http.py
import asyncio import weakref import aiohttp import sys import json import traceback import logging from urllib.parse import quote as _uriquote from ..errors import HTTPException, Forbidden, NotFound, ServerError, SentinelError log = logging.getLogger(__name__) class Route: BASE = "https://discord.com/api/v9" ...
0.223886
0.067026
# ## Questionário 73 (Q73) # # Orientações: # # - Registre suas respostas no questionário de mesmo nome no SIGAA. # - O tempo de registro das respostas no questionário será de 10 minutos. Portanto, resolva primeiro as questões e depois registre-as. # - Haverá apenas 1 (uma) tentativa de resposta. # - Submeta seu ar...
_build/jupyter_execute/todo/Q73-gab.py
# ## Questionário 73 (Q73) # # Orientações: # # - Registre suas respostas no questionário de mesmo nome no SIGAA. # - O tempo de registro das respostas no questionário será de 10 minutos. Portanto, resolva primeiro as questões e depois registre-as. # - Haverá apenas 1 (uma) tentativa de resposta. # - Submeta seu ar...
0.431345
0.566378
from django.contrib import admin from django.views.generic.base import TemplateView from django.urls import path, re_path, include from . import views urlpatterns = [ path('admin/', admin.site.urls), path(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), path(r'^$', TemplateView...
digifarming/digifarming/urls.py
from django.contrib import admin from django.views.generic.base import TemplateView from django.urls import path, re_path, include from . import views urlpatterns = [ path('admin/', admin.site.urls), path(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), path(r'^$', TemplateView...
0.253306
0.041579
import bs4 import logging from cryptics.text import ( is_parsable_text_type_1, parse_text_type_1, is_parsable_text_type_2, parse_text_type_2, ) from cryptics.tables import ( is_parsable_table_type_1, parse_table_type_1, is_parsable_table_type_2, parse_table_type_2, is_parsable_table...
cryptics/parse.py
import bs4 import logging from cryptics.text import ( is_parsable_text_type_1, parse_text_type_1, is_parsable_text_type_2, parse_text_type_2, ) from cryptics.tables import ( is_parsable_table_type_1, parse_table_type_1, is_parsable_table_type_2, parse_table_type_2, is_parsable_table...
0.359139
0.418222
import os import sys import json import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from model.loss import dice_loss_2d, surface_channel_loss_2d from preprocessing.dataset import AgricultureVisionDataset from testing.image import get_testing_image, create_displayable_te...
prototype.py
import os import sys import json import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from model.loss import dice_loss_2d, surface_channel_loss_2d from preprocessing.dataset import AgricultureVisionDataset from testing.image import get_testing_image, create_displayable_te...
0.736495
0.33939
class TBar(): _max = -1 length = 50 infile = None rawdata = None normdata = None vertical = False def __init__(self, _max=0, length=0, vertical=False): if _max: self._max = _max if length: self.length = length self.vertical = vertical ...
tbar/tbar.py
class TBar(): _max = -1 length = 50 infile = None rawdata = None normdata = None vertical = False def __init__(self, _max=0, length=0, vertical=False): if _max: self._max = _max if length: self.length = length self.vertical = vertical ...
0.544559
0.122891
"""Demo some features of NetCore.""" import argparse import mininet.topolib import mininet.topo import MininetDriver as md from multiprocessing import Process import subprocess as sp import time # H1 0----1 S3 2----0 H2 basic = mininet.topolib.TreeTopo(depth=1, fanout=2) def getRunner(flag, topo=basic): ctrl = sp....
examples/demo.py
"""Demo some features of NetCore.""" import argparse import mininet.topolib import mininet.topo import MininetDriver as md from multiprocessing import Process import subprocess as sp import time # H1 0----1 S3 2----0 H2 basic = mininet.topolib.TreeTopo(depth=1, fanout=2) def getRunner(flag, topo=basic): ctrl = sp....
0.514644
0.117319
import re import os import sys import importlib import os.path class Exporter(object): data = None def __init__(self, data): self.data = data def write(self, directory): with open("Out.txt", "w") as handle: # Write the header handle.write("====== Test =====...
exporters/doku.py
import re import os import sys import importlib import os.path class Exporter(object): data = None def __init__(self, data): self.data = data def write(self, directory): with open("Out.txt", "w") as handle: # Write the header handle.write("====== Test =====...
0.193795
0.145996
import argparse from pathlib import Path from jinja2 import Environment, PackageLoader, select_autoescape helm_dir = Path(__file__).resolve().parent.parent / "helm" # Map the chart names to their location. This is useful for updating # dependencies (in Chart.yaml) as well as the charts. helm_charts = [ helm_dir...
deploy/scripts/combine_charts.py
import argparse from pathlib import Path from jinja2 import Environment, PackageLoader, select_autoescape helm_dir = Path(__file__).resolve().parent.parent / "helm" # Map the chart names to their location. This is useful for updating # dependencies (in Chart.yaml) as well as the charts. helm_charts = [ helm_dir...
0.574992
0.195709
import getopt import sys from algorithms import Kruskal, Prim from utils.graph import (DisjointSet, create_graph, edges_to_graph, graph_to_edges) from utils.io import (read_input, save_clusters_csv, save_clusters_png, save_mst_csv, save_mst_png) class Config: data_f...
main.py
import getopt import sys from algorithms import Kruskal, Prim from utils.graph import (DisjointSet, create_graph, edges_to_graph, graph_to_edges) from utils.io import (read_input, save_clusters_csv, save_clusters_png, save_mst_csv, save_mst_png) class Config: data_f...
0.251556
0.123842
from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils.text import Truncator # Create your models here. class Board(models.Model): """ Class for message boards. """ name = models.CharField(max_length=30, unique=True) description...
acceptable-albatrosses/albatrosses_hub/forums/models.py
from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils.text import Truncator # Create your models here. class Board(models.Model): """ Class for message boards. """ name = models.CharField(max_length=30, unique=True) description...
0.725454
0.163512
import tensorflow as tf import numpy as np def get_shape(spec: str, spec_shape: dict): return tuple(spec_shape[dim] for dim in spec) def expand_transform(x, input_spec: str, output_spec: str, output_spec_shape: dict, numpy=False): assert len(output_spec) == len(output_spec_shape) if numpy: tile...
layers/ddcconv1d.py
import tensorflow as tf import numpy as np def get_shape(spec: str, spec_shape: dict): return tuple(spec_shape[dim] for dim in spec) def expand_transform(x, input_spec: str, output_spec: str, output_spec_shape: dict, numpy=False): assert len(output_spec) == len(output_spec_shape) if numpy: tile...
0.795142
0.629234
import netCDF4 as nc import numpy as np import os def build_url(yyyy,mm,dd,hh): return f'http://172.16.31.10:8080/opendap/opendap/wrf5/d03/archive/{yyyy}/{mm}/{dd}/wrf5_d03_{yyyy}{mm}{dd}Z{hh}00.nc' def read_netcdf4_files(wrf,scan): try: model = nc.Dataset(wrf) radar_scan = nc.Da...
tools/wrf_regridding.py
import netCDF4 as nc import numpy as np import os def build_url(yyyy,mm,dd,hh): return f'http://172.16.31.10:8080/opendap/opendap/wrf5/d03/archive/{yyyy}/{mm}/{dd}/wrf5_d03_{yyyy}{mm}{dd}Z{hh}00.nc' def read_netcdf4_files(wrf,scan): try: model = nc.Dataset(wrf) radar_scan = nc.Da...
0.153676
0.214177
import os import cv2 from tqdm import tqdm def crop(img_path, size=(720, 720), alignment='center'): """ helper function to crop an image to the given size :param img: :param size: (width, height) :param center: :return: """ img = cv2.imread(img_path) if img is None:...
datasets_utils/crop_image_of_dataset.py
import os import cv2 from tqdm import tqdm def crop(img_path, size=(720, 720), alignment='center'): """ helper function to crop an image to the given size :param img: :param size: (width, height) :param center: :return: """ img = cv2.imread(img_path) if img is None:...
0.470737
0.311833
# Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null self.prev = None # Initialize prev as null # Stack class contains a Node object c...
Profiles/stack_using_dll.py
# Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null self.prev = None # Initialize prev as null # Stack class contains a Node object c...
0.354321
0.157396
"""File for base geometry class built using the Geomdl class""" import numpy as np class Geometry2D: ''' Base class for 2D domains Input: geomData - dictionary containing the geomety information Keys: degree_u, degree_v: polynomial degree in the u and v directions ctrlpts_size_u, ctrlpts_size...
tf1/tensorflow_DEM/Phase Field/utils/BezExtr.py
"""File for base geometry class built using the Geomdl class""" import numpy as np class Geometry2D: ''' Base class for 2D domains Input: geomData - dictionary containing the geomety information Keys: degree_u, degree_v: polynomial degree in the u and v directions ctrlpts_size_u, ctrlpts_size...
0.607663
0.707482
import json import sys def s(_): return '"' + _ + '"' def i(_): return str(_) def b(_): if _: return "true" else: return "false" def enc(typ, val): if typ == "int": return i(val) elif typ == "string": return s(val) elif typ == "bool": return b(val)...
jcc_interpreter.py
import json import sys def s(_): return '"' + _ + '"' def i(_): return str(_) def b(_): if _: return "true" else: return "false" def enc(typ, val): if typ == "int": return i(val) elif typ == "string": return s(val) elif typ == "bool": return b(val)...
0.127734
0.14624
import tkinter as tk import random class Customer: def __init__(self, id, create_time): self.id = id self.create_time = create_time self.finished_time = -1 class App: """The tkinter GUI interface.""" def kill_callback(self): self.window.destroy() def __i...
algs2e_python/Chapter 05/python/multi_headed_queue.py
import tkinter as tk import random class Customer: def __init__(self, id, create_time): self.id = id self.create_time = create_time self.finished_time = -1 class App: """The tkinter GUI interface.""" def kill_callback(self): self.window.destroy() def __i...
0.507324
0.133359
import collections import json import pytest import os from typing import Set from data.src.split import _detect_best_script_name from data.src.split import _generalized_check _REPO_DIR = os.path.dirname( os.path.dirname(os.path.dirname(os.path.realpath(__file__))) ) _LANGUAGES = os.path.join(_REPO_DIR, "data/sr...
tests/test_data/test_split.py
import collections import json import pytest import os from typing import Set from data.src.split import _detect_best_script_name from data.src.split import _generalized_check _REPO_DIR = os.path.dirname( os.path.dirname(os.path.dirname(os.path.realpath(__file__))) ) _LANGUAGES = os.path.join(_REPO_DIR, "data/sr...
0.625324
0.282437
import logging from typing import Dict, List, Optional, Any, Callable, Tuple, Union from collections import OrderedDict import traceback import copy import os from qiskit.providers import ProviderV1 as Provider # type: ignore[attr-defined] from qiskit.providers.models import (QasmBackendConfiguration, ...
qiskit_ibm/ibm_provider.py
import logging from typing import Dict, List, Optional, Any, Callable, Tuple, Union from collections import OrderedDict import traceback import copy import os from qiskit.providers import ProviderV1 as Provider # type: ignore[attr-defined] from qiskit.providers.models import (QasmBackendConfiguration, ...
0.905927
0.167491
from TestHelperSuperClass import testHelperSuperClass class local_helpers(testHelperSuperClass): def deleteConsumer(self, consumer_name): resp, respCode = self.callKongService("/consumers/" + consumer_name, {}, "get", None, [200, 404]) if respCode == 404: return False resp, respCode = self.callKon...
test/test_kong_install_consumer_with_api.py
from TestHelperSuperClass import testHelperSuperClass class local_helpers(testHelperSuperClass): def deleteConsumer(self, consumer_name): resp, respCode = self.callKongService("/consumers/" + consumer_name, {}, "get", None, [200, 404]) if respCode == 404: return False resp, respCode = self.callKon...
0.458106
0.13109
import os import sys import unittest sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from neon_api_proxy.wolfram_api import WolframAPI, QueryUrl VALID_QUERY_IP = {"query": "how far away is Moscow?", "units": "metric", "ip": "172.16.17.32"} VALID_QUE...
tests/test_wolfram_api.py
import os import sys import unittest sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from neon_api_proxy.wolfram_api import WolframAPI, QueryUrl VALID_QUERY_IP = {"query": "how far away is Moscow?", "units": "metric", "ip": "172.16.17.32"} VALID_QUE...
0.405566
0.334426
import logging import os from pathlib import Path from make_prg import make_prg_from_msa, io_utils def run(options): if options.output_prefix is None: prefix = options.MSA else: if os.path.isdir(options.output_prefix): prefix = os.path.join(options.output_prefix, os.path.basename(...
make_prg/subcommands/prg_from_msa.py
import logging import os from pathlib import Path from make_prg import make_prg_from_msa, io_utils def run(options): if options.output_prefix is None: prefix = options.MSA else: if os.path.isdir(options.output_prefix): prefix = os.path.join(options.output_prefix, os.path.basename(...
0.281702
0.072735
from __future__ import print_function # Used to process batch download from plasmoDB to be input into GeneTargeter from builtins import str from py.utils.GenBankToolbox import * from py.utils.BioUtils import * from copy import deepcopy # use to process plasmoDB fasta download (no introns, use gff_to_genbank now # ins...
py/auxiliary/Multiseq.py
from __future__ import print_function # Used to process batch download from plasmoDB to be input into GeneTargeter from builtins import str from py.utils.GenBankToolbox import * from py.utils.BioUtils import * from copy import deepcopy # use to process plasmoDB fasta download (no introns, use gff_to_genbank now # ins...
0.3295
0.266113
import os import pytest import numpy as np import pandas as pd from pandas.testing import assert_frame_equal import nyaggle.feature_store as fs from nyaggle.testing import get_temp_directory def test_save_feature(): df = pd.DataFrame() df['a'] = np.arange(100) with get_temp_directory() as tmp: ...
tests/feature_store/test_feature_store.py
import os import pytest import numpy as np import pandas as pd from pandas.testing import assert_frame_equal import nyaggle.feature_store as fs from nyaggle.testing import get_temp_directory def test_save_feature(): df = pd.DataFrame() df['a'] = np.arange(100) with get_temp_directory() as tmp: ...
0.267313
0.516108
from GUI.LoginWindow import * from PyQt5.QtCore import QThread, pyqtSignal from PyQt5 import QtWidgets, QtGui from PyQt5.QtWidgets import * import random import win32com.client import threading from GUI.ProprietorWindow import Design_ProprietorWindow from Controllers import ProprietorControl import time class Propri...
src/GUI/LProprietorWindow.py
from GUI.LoginWindow import * from PyQt5.QtCore import QThread, pyqtSignal from PyQt5 import QtWidgets, QtGui from PyQt5.QtWidgets import * import random import win32com.client import threading from GUI.ProprietorWindow import Design_ProprietorWindow from Controllers import ProprietorControl import time class Propri...
0.303732
0.101189
import argparse import logging import os import subprocess from .log import logger def set_up_command_line_arguments(): """ Sets up command line arguments that can be used to modify how scripts are run. Returns ======= command_line_args, command_line_parser: tuple The command_line_args is a ...
bilby/core/utils/cmd.py
import argparse import logging import os import subprocess from .log import logger def set_up_command_line_arguments(): """ Sets up command line arguments that can be used to modify how scripts are run. Returns ======= command_line_args, command_line_parser: tuple The command_line_args is a ...
0.766206
0.289836
import json import sys import requests import time import os from bs4 import BeautifulSoup DIR = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(DIR, "trajectory-albatross.gpx")) as f: xml_str = f.read() defs = [] results = [] obj = BeautifulSoup(xml_str, 'xml') trks = obj.find_all('trk') for...
demo_data/animals/analyse.py
import json import sys import requests import time import os from bs4 import BeautifulSoup DIR = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(DIR, "trajectory-albatross.gpx")) as f: xml_str = f.read() defs = [] results = [] obj = BeautifulSoup(xml_str, 'xml') trks = obj.find_all('trk') for...
0.101679
0.095645
from ruffus import follows, transform, regex, mkdir,\ pipeline_printout, pipeline_printout_graph,\ pipeline_run, files, merge,\ touch_file, posttask, jobs_limit import os import sys from subprocess import check_call from pipeline_config import POINTS_H5_DIR,\ PCD_DIR, PCD_DOWNSAMPLED_DIR...
mapping/pipeline/pipeline.py
from ruffus import follows, transform, regex, mkdir,\ pipeline_printout, pipeline_printout_graph,\ pipeline_run, files, merge,\ touch_file, posttask, jobs_limit import os import sys from subprocess import check_call from pipeline_config import POINTS_H5_DIR,\ PCD_DIR, PCD_DOWNSAMPLED_DIR...
0.147524
0.071526
import re import requests import json from selenium import webdriver from selenium.webdriver import FirefoxOptions import os country_by_code_dict = {} domains_dict = {} path = '/home/kami/workspace/software/geckodriver' country_regex = re.compile(r'<a href="countries/([A-Z]+)">([A-Za-z]+)</a>') countries_list_url = ...
backend/server/init_db/get_top_sites_by_country.py
import re import requests import json from selenium import webdriver from selenium.webdriver import FirefoxOptions import os country_by_code_dict = {} domains_dict = {} path = '/home/kami/workspace/software/geckodriver' country_regex = re.compile(r'<a href="countries/([A-Z]+)">([A-Za-z]+)</a>') countries_list_url = ...
0.130535
0.109658
import getopt import os import sys import argparse import getpass import subprocess import logging from paramiko import SSHClient, AutoAddPolicy from scp import SCPClient from zipfile import ZipFile SANDBOX_USERNAME = "sandbox" SANDBOX_PORT = 22 SCRIPT = os.path.realpath(__file__) SCRIPT_ROOT = os.path.dirname(SCRIP...
{{cookiecutter.project_name}}/upload.py
import getopt import os import sys import argparse import getpass import subprocess import logging from paramiko import SSHClient, AutoAddPolicy from scp import SCPClient from zipfile import ZipFile SANDBOX_USERNAME = "sandbox" SANDBOX_PORT = 22 SCRIPT = os.path.realpath(__file__) SCRIPT_ROOT = os.path.dirname(SCRIP...
0.216923
0.056862
import functools import math def load_input_file(file_name: str): with open(file_name) as file: yield from (line.strip() for line in file) def parse(task_input): for line in task_input: yield eval(line) def get_elements(a, level): for s in a: if s.__class__ == list: ...
day-18/sol-18.py
import functools import math def load_input_file(file_name: str): with open(file_name) as file: yield from (line.strip() for line in file) def parse(task_input): for line in task_input: yield eval(line) def get_elements(a, level): for s in a: if s.__class__ == list: ...
0.314893
0.552178
import random # My libraries from backprop2 import Network, sigmoid_vec # Third-party libraries import numpy as np def plot_helper(x): import matplotlib import matplotlib.pyplot as plt x = np.reshape(x, (-1, 28)) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.matshow(x, cmap = matplotli...
code/deep_autoencoder.py
import random # My libraries from backprop2 import Network, sigmoid_vec # Third-party libraries import numpy as np def plot_helper(x): import matplotlib import matplotlib.pyplot as plt x = np.reshape(x, (-1, 28)) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.matshow(x, cmap = matplotli...
0.845751
0.685871
import numpy as np import math import glob from benchpress import prof ppn = prof.max_ppn files = glob.glob("%s/mult_pong.*.out"%(prof.folder)) class TimeList(): ppn_times = "" def __init__(self, np): self.ppn_times = list() for i in range(np): self.ppn_times.append(list()) ...
plots/benchpress/ping_pong/mult_pong.py
import numpy as np import math import glob from benchpress import prof ppn = prof.max_ppn files = glob.glob("%s/mult_pong.*.out"%(prof.folder)) class TimeList(): ppn_times = "" def __init__(self, np): self.ppn_times = list() for i in range(np): self.ppn_times.append(list()) ...
0.165796
0.190347
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import re import sys import yaml import copy import pandas as pd import logging import tensorflow as tf from collections import Counter, namedtuple from tensorflow.python.platform import gfile from s...
utils/io_utils.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import re import sys import yaml import copy import pandas as pd import logging import tensorflow as tf from collections import Counter, namedtuple from tensorflow.python.platform import gfile from s...
0.643217
0.135833
__all__ = ['open_geotiff', 'calc_normalized_spectral_index', 'calc_avi', 'calc_savi', 'calc_gci', 'mask_plot_from_image', 'image_metrics', 'glcm_xplusy', 'glcm_xminusy', 'textural_features', 'process_image_features'] # Cell import rasterio as rio import numpy as np import matplotlib.pyplot as pl...
enveco/data/image.py
__all__ = ['open_geotiff', 'calc_normalized_spectral_index', 'calc_avi', 'calc_savi', 'calc_gci', 'mask_plot_from_image', 'image_metrics', 'glcm_xplusy', 'glcm_xminusy', 'textural_features', 'process_image_features'] # Cell import rasterio as rio import numpy as np import matplotlib.pyplot as pl...
0.765856
0.612657
from . import db, login_manager from flask_login import UserMixin from werkzeug.security import generate_password_hash,check_password_hash @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class User(UserMixin,db.Model): __tablename__ = 'users' id = db.Column(db.Intege...
app/models.py
from . import db, login_manager from flask_login import UserMixin from werkzeug.security import generate_password_hash,check_password_hash @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class User(UserMixin,db.Model): __tablename__ = 'users' id = db.Column(db.Intege...
0.408159
0.057361
import io import unittest from advisor.makefile_scanner import MakefileScanner from advisor.report import Report class TestMakefileScanner(unittest.TestCase): def test_accepts_file(self): makefile_scanner = MakefileScanner() self.assertFalse(makefile_scanner.accepts_file('test')) self.asse...
unittest/test_makefile_scanner.py
import io import unittest from advisor.makefile_scanner import MakefileScanner from advisor.report import Report class TestMakefileScanner(unittest.TestCase): def test_accepts_file(self): makefile_scanner = MakefileScanner() self.assertFalse(makefile_scanner.accepts_file('test')) self.asse...
0.307254
0.309148
from django.utils import timezone from django import forms from django.contrib.auth.models import User from datetimewidget.widgets import DateWidget from .models import Patient, Hospital, Doctor, Nurse class UserRegForm(forms.ModelForm): """ Form for user registration """ password = forms.CharField(...
HealthNet/core/forms.py
from django.utils import timezone from django import forms from django.contrib.auth.models import User from datetimewidget.widgets import DateWidget from .models import Patient, Hospital, Doctor, Nurse class UserRegForm(forms.ModelForm): """ Form for user registration """ password = forms.CharField(...
0.632503
0.116915
from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.messages.views import SuccessMessageMixin from django.contrib.sites.models import Site from django.urls import reverse from django.utils.translation import gettext_lazy as _ from django.views.generic import...
one/contrib/sites/settings/views.py
from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.messages.views import SuccessMessageMixin from django.contrib.sites.models import Site from django.urls import reverse from django.utils.translation import gettext_lazy as _ from django.views.generic import...
0.492432
0.079246
from geopy.distance import distance import os import gdal import osr import re from reader.gdal_reader import GdalReader import numpy as np def rename_files(files, name=None): """ Given a list of file paths for elevation files, this function will rename those files to the format required by the pyDEM pac...
pydem/utils.py
from geopy.distance import distance import os import gdal import osr import re from reader.gdal_reader import GdalReader import numpy as np def rename_files(files, name=None): """ Given a list of file paths for elevation files, this function will rename those files to the format required by the pyDEM pac...
0.819713
0.496948
import numpy as np import numpy.linalg as linalg class HomogeneousCoordinate(np.ndarray): def __new__(cls, *args, **kwargs): # creates an array with the homogeneous coordinates obj = np.zeros(4, dtype=float).view(cls) return obj def __init__(self, x=0, y=0, z=0, w=0): # assign...
pycg/pycg.py
import numpy as np import numpy.linalg as linalg class HomogeneousCoordinate(np.ndarray): def __new__(cls, *args, **kwargs): # creates an array with the homogeneous coordinates obj = np.zeros(4, dtype=float).view(cls) return obj def __init__(self, x=0, y=0, z=0, w=0): # assign...
0.892393
0.621053
import SimpleITK as sitk import numpy as np from disptools import * def create_target_volume(image: sitk.Image, atrophy_rate: float): r""" Create a target volume map for the PREDICT tool. Given an input segmentation map, create mask target volume map for the PREDICT tool, with the given atrophy rate. The ...
disptools/predict.py
import SimpleITK as sitk import numpy as np from disptools import * def create_target_volume(image: sitk.Image, atrophy_rate: float): r""" Create a target volume map for the PREDICT tool. Given an input segmentation map, create mask target volume map for the PREDICT tool, with the given atrophy rate. The ...
0.94379
0.793466
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np def init_weights(m, gain): if (type(m) == nn.Linear) | (type(m) == nn.Conv2d): nn.init.orthogonal_(m.weight, gain) nn.init.zeros_(m.bias) class CNNDeepmind(nn.Module): def __init__(self, observation_space, ...
Archive/appendix/Atari/baseline-QR-DQN/cnn_deepmind.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np def init_weights(m, gain): if (type(m) == nn.Linear) | (type(m) == nn.Conv2d): nn.init.orthogonal_(m.weight, gain) nn.init.zeros_(m.bias) class CNNDeepmind(nn.Module): def __init__(self, observation_space, ...
0.941594
0.555797
import json import os import sqlite3 import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_cytoscape as cyto import dash_html_components as html import dash_table import networkx as nx import pandas as pd from OmicsIntegrator import Graph from dash.dash import no_update from dash.depen...
dash_app/pages/vis.py
import json import os import sqlite3 import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_cytoscape as cyto import dash_html_components as html import dash_table import networkx as nx import pandas as pd from OmicsIntegrator import Graph from dash.dash import no_update from dash.depen...
0.586641
0.157979
import __builtin__ import sys from __mimic.util import patch import unittest class BuiltinPatchTest(unittest.TestCase): """Unit tests for Patch.""" def setUp(self): self._patch = None def tearDown(self): if self._patch: self._patch.Remove() def testPatch(self): self._patch = patch.Built...
__mimic/util/tests/patch_test.py
import __builtin__ import sys from __mimic.util import patch import unittest class BuiltinPatchTest(unittest.TestCase): """Unit tests for Patch.""" def setUp(self): self._patch = None def tearDown(self): if self._patch: self._patch.Remove() def testPatch(self): self._patch = patch.Built...
0.527803
0.444444
# Copyright: (c) 2018, <NAME> <<EMAIL>> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = ''' --- module: tetration_software_agent short_descrip...
library/tetration_software_agent.py
# Copyright: (c) 2018, <NAME> <<EMAIL>> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = ''' --- module: tetration_software_agent short_descrip...
0.819244
0.23699
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 RepositoryApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. ...
swagger_client/api/repository_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 RepositoryApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. ...
0.704668
0.048047
import numpy as np def binary_repr(x): return list(reversed([int(e) for e in np.binary_repr(x)])) class Reduction1: def __init__(self, modulus): self.p = modulus # Next power of 2 self.k = p.bit_length() self.table = {} for l in range(self.k, self.k*2): sel...
rust/crypto-primitives/mod_mul.py
import numpy as np def binary_repr(x): return list(reversed([int(e) for e in np.binary_repr(x)])) class Reduction1: def __init__(self, modulus): self.p = modulus # Next power of 2 self.k = p.bit_length() self.table = {} for l in range(self.k, self.k*2): sel...
0.23793
0.52409
from lib.canvas import Canvas from lib.figure import Figure import pickle def _offset_rounding_error(figure): """ """ fig = [] pre_part = [] for line in figure: if not pre_part == []: fig.append((pre_part[3], line[1], line[2], line[3])) else: fig.append(line) ...
example.py
from lib.canvas import Canvas from lib.figure import Figure import pickle def _offset_rounding_error(figure): """ """ fig = [] pre_part = [] for line in figure: if not pre_part == []: fig.append((pre_part[3], line[1], line[2], line[3])) else: fig.append(line) ...
0.609989
0.455622
import os import time as t import numpy as np if os.name == 'nt': import msvcrt def getch(): return msvcrt.getch().decode() else: import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) def getch(): try: tty.setraw(sys.stdin.fileno()) ...
R1-M2/src/lofaro_ventilator.py
import os import time as t import numpy as np if os.name == 'nt': import msvcrt def getch(): return msvcrt.getch().decode() else: import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) def getch(): try: tty.setraw(sys.stdin.fileno()) ...
0.289874
0.108519
from keras.models import Sequential, Model from keras.layers import Embedding, LSTM, Flatten, Dense, BatchNormalization, \ Activation, Dropout, concatenate, Lambda, Reshape, Conv2D, MaxPooling2D, TimeDistributed from keras.constraints import maxnorm from keras.optimizers import rmsprop, TFOptimizer, Adam, Adadelta ...
models.py
from keras.models import Sequential, Model from keras.layers import Embedding, LSTM, Flatten, Dense, BatchNormalization, \ Activation, Dropout, concatenate, Lambda, Reshape, Conv2D, MaxPooling2D, TimeDistributed from keras.constraints import maxnorm from keras.optimizers import rmsprop, TFOptimizer, Adam, Adadelta ...
0.675765
0.251912
import getpass import sys import cryptography.hazmat.backends as backends import cryptography.hazmat.primitives.asymmetric.rsa as rsa import cryptography.hazmat.primitives.serialization as serial import cryptography.hazmat.primitives.hashes as hashes import cryptography.hazmat.primitives as primitives import cryptograp...
Testing/cryptographic/crypto.py
import getpass import sys import cryptography.hazmat.backends as backends import cryptography.hazmat.primitives.asymmetric.rsa as rsa import cryptography.hazmat.primitives.serialization as serial import cryptography.hazmat.primitives.hashes as hashes import cryptography.hazmat.primitives as primitives import cryptograp...
0.297776
0.118947
import json import sys import Pyro4 import subscriber import publisher def subscriber_dict_to_class(classname, d): print('deserializing {}'.format(d)) return subscriber.Subscriber(d['name']) def publisher_dict_to_class(classname, d): p = publisher.Publisher(d['name'], d['event']) p.intermediary = d['i...
Python/intermediary.py
import json import sys import Pyro4 import subscriber import publisher def subscriber_dict_to_class(classname, d): print('deserializing {}'.format(d)) return subscriber.Subscriber(d['name']) def publisher_dict_to_class(classname, d): p = publisher.Publisher(d['name'], d['event']) p.intermediary = d['i...
0.455925
0.130285
import math import operator import pytest from capacity import MiB, byte, GiB, KiB, Capacity, bit, from_string, MB, GB, PiB, __version__ from numbers import Integral from operator import truediv from .utils import assert_value_error def test_version(): assert isinstance(__version__.__version__, str) def test_0...
tests/test_capacity.py
import math import operator import pytest from capacity import MiB, byte, GiB, KiB, Capacity, bit, from_string, MB, GB, PiB, __version__ from numbers import Integral from operator import truediv from .utils import assert_value_error def test_version(): assert isinstance(__version__.__version__, str) def test_0...
0.710126
0.80038
import argparse from collections import defaultdict from os import remove from random import randrange import genanki from pycasia import CASIA from hsk import HSK from models import get_model EXAMPLE_COUNT = 50 def create_deck(name, character_list=None, example_count=30): """ Create a deck with the given ...
main.py
import argparse from collections import defaultdict from os import remove from random import randrange import genanki from pycasia import CASIA from hsk import HSK from models import get_model EXAMPLE_COUNT = 50 def create_deck(name, character_list=None, example_count=30): """ Create a deck with the given ...
0.610802
0.322366
import base64 from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError class AccountPaymentOrder(models.Model): _name = "account.payment.order" _description = "Payment Order" _inherit = ["mail.thread"] _order = "id desc" _check_company_auto = True name ...
addons14/account_payment_order/models/account_payment_order.py
import base64 from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError class AccountPaymentOrder(models.Model): _name = "account.payment.order" _description = "Payment Order" _inherit = ["mail.thread"] _order = "id desc" _check_company_auto = True name ...
0.578091
0.225715
import sys from oslo_config import cfg from oslo_log import log as logging from kuryr_kubernetes.cmd.sanity import checks from kuryr_kubernetes import config from kuryr_kubernetes.controller.drivers import vif_pool # noqa LOG = logging.getLogger(__name__) class BoolOptCallback(cfg.BoolOpt): def __init__(self,...
kuryr_kubernetes/cmd/sanity_checks.py
import sys from oslo_config import cfg from oslo_log import log as logging from kuryr_kubernetes.cmd.sanity import checks from kuryr_kubernetes import config from kuryr_kubernetes.controller.drivers import vif_pool # noqa LOG = logging.getLogger(__name__) class BoolOptCallback(cfg.BoolOpt): def __init__(self,...
0.372277
0.066478
from crummycm.validation.types.values.base import BaseValue import operator class Numeric(BaseValue): def __init__( self, default_value=None, is_type=None, required=None, description=None, fn=None, fn_kwargs=None, # specific bounds=None, ...
src/crummycm/validation/types/values/element/numeric.py
from crummycm.validation.types.values.base import BaseValue import operator class Numeric(BaseValue): def __init__( self, default_value=None, is_type=None, required=None, description=None, fn=None, fn_kwargs=None, # specific bounds=None, ...
0.755907
0.199503
# Importamos la librería import pygame import sys import random from math import sqrt,exp # Importamos constantes locales de pygame from pygame.locals import * from aux import * sprites_serp = pygame.sprite.Group() manzanas = pygame.sprite.Group() # Establecemos el largo y alto de cada segmento de la serpiente ...
snake.py
# Importamos la librería import pygame import sys import random from math import sqrt,exp # Importamos constantes locales de pygame from pygame.locals import * from aux import * sprites_serp = pygame.sprite.Group() manzanas = pygame.sprite.Group() # Establecemos el largo y alto de cada segmento de la serpiente ...
0.14777
0.38341
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files from typing import List, Any, Union class Dcc(Base): """The Layer 1 Configuration is being configured for a POS port and DCC is selected as the Payload Type. The Dcc class encapsulates a required dcc resource which will be retriev...
ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/l1config/pos/dcc/dcc.py
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files from typing import List, Any, Union class Dcc(Base): """The Layer 1 Configuration is being configured for a POS port and DCC is selected as the Payload Type. The Dcc class encapsulates a required dcc resource which will be retriev...
0.89654
0.372163
# ================================================== # Import import pytest import random import math # ================================================== # Phase 1 def phase1(X, k, d): # Initiation n = len(X) random.shuffle(X) S = X[:k] XS = X[k:] S.sort() # Keeping the list entri...
tests/phase2_test.py
# ================================================== # Import import pytest import random import math # ================================================== # Phase 1 def phase1(X, k, d): # Initiation n = len(X) random.shuffle(X) S = X[:k] XS = X[k:] S.sort() # Keeping the list entri...
0.128225
0.46035
import numpy as np import pandas as pd import os import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import seaborn as sns sns.set() from sklearn.ensemble import ExtraTreesRegressor from sklearn.linear_model import Ridge, LinearRegression from sklearn.model_selection import train_test_split from skl...
BayOptPy/freesurfer_preprocess/original_dataset/UKBIO/tpot_model_analysis_4614144.py
import numpy as np import pandas as pd import os import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import seaborn as sns sns.set() from sklearn.ensemble import ExtraTreesRegressor from sklearn.linear_model import Ridge, LinearRegression from sklearn.model_selection import train_test_split from skl...
0.733261
0.508666
import numpy as np import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin class FeatureSelector(BaseEstimator, TransformerMixin): """This transformer select features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For us...
mlearner/preprocessing/feature_selector.py
import numpy as np import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin class FeatureSelector(BaseEstimator, TransformerMixin): """This transformer select features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For us...
0.884139
0.506958
import uuid import re import base64 class Streamlit_elements(): def mymarkdown(object, number, text): form = """<style type="text/css"> .low { color: #585858; position: relative; bottom: 1ex; font-size: 60%; ...
elements/elements.py
import uuid import re import base64 class Streamlit_elements(): def mymarkdown(object, number, text): form = """<style type="text/css"> .low { color: #585858; position: relative; bottom: 1ex; font-size: 60%; ...
0.287268
0.091301