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 cPickle as pickle import numpy as np import rospy import tf2_geometry_msgs import tf2_ros import geometry_msgs.msg as geometry_msgs import nav_msgs.msg as nav_msgs import std_msgs.msg as std_msgs import abstract_map_lib.visual as visual import abstract_map_lib.tools as tools _SAVE_ABSTRACT_MAP_ON_EXIT = True ...
src/abstract_map_visualiser.py
import cPickle as pickle import numpy as np import rospy import tf2_geometry_msgs import tf2_ros import geometry_msgs.msg as geometry_msgs import nav_msgs.msg as nav_msgs import std_msgs.msg as std_msgs import abstract_map_lib.visual as visual import abstract_map_lib.tools as tools _SAVE_ABSTRACT_MAP_ON_EXIT = True ...
0.551936
0.132936
"""autogenerated by genpy from pioneer2dx_ros/myGPSMessage.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class myGPSMessage(genpy.Message): _md5sum = "6cb97d1e605900e785858ea58cd96c67" _type = "pioneer2dx_ros/myGPSMessage" _has_header = False...
catkin_workspace/devel/lib/python2.7/dist-packages/pioneer2dx_ros/msg/_myGPSMessage.py
"""autogenerated by genpy from pioneer2dx_ros/myGPSMessage.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class myGPSMessage(genpy.Message): _md5sum = "6cb97d1e605900e785858ea58cd96c67" _type = "pioneer2dx_ros/myGPSMessage" _has_header = False...
0.431225
0.300425
import seaborn as sns import visualization.visualize as visualize import transporters.optical_functions_factory as optical_functions_factory def plot_optical_functions(datasets, x_axis_parameter, optical_function_name, **kwargs): return visualize.plot_datasets(x_axis_parameter, optical_function_name, "transporter...
src/visualization/optics_parameter_visualisation.py
import seaborn as sns import visualization.visualize as visualize import transporters.optical_functions_factory as optical_functions_factory def plot_optical_functions(datasets, x_axis_parameter, optical_function_name, **kwargs): return visualize.plot_datasets(x_axis_parameter, optical_function_name, "transporter...
0.756178
0.53443
import logging import pytest import responses from flash_services.core import Service from flash_services.github import GitHubEnterpriseIssues, GitHubIssues @pytest.fixture def service(): return GitHubIssues(username='user', password='<PASSWORD>', account='foo', repo='bar') def test_tracker_service_type(): ...
tests/test_github_issues_service.py
import logging import pytest import responses from flash_services.core import Service from flash_services.github import GitHubEnterpriseIssues, GitHubIssues @pytest.fixture def service(): return GitHubIssues(username='user', password='<PASSWORD>', account='foo', repo='bar') def test_tracker_service_type(): ...
0.452778
0.336168
import torch import torch_mlir import typing # RUN: %PYTHON %s | npcomp-opt | FileCheck %s mb = torch_mlir.ModuleBuilder() # CHECK-LABEL: func @__torch__.prim_Loop_forlike( # CHECK-SAME: %[[MAX_ITERATIONS:.*]]: i64) -> f64 { # CHECK: %[[BOOL_TRUE:.*]] = basicpy.bool_constant ...
frontends/pytorch/test/node_import/loop.py
import torch import torch_mlir import typing # RUN: %PYTHON %s | npcomp-opt | FileCheck %s mb = torch_mlir.ModuleBuilder() # CHECK-LABEL: func @__torch__.prim_Loop_forlike( # CHECK-SAME: %[[MAX_ITERATIONS:.*]]: i64) -> f64 { # CHECK: %[[BOOL_TRUE:.*]] = basicpy.bool_constant ...
0.503174
0.274807
import requests import sys import argparse import logging import json import time import string import datetime import anticrlf from veracode_api_py import VeracodeAPI as vapi log = logging.getLogger(__name__) def setup_logger(): handler = logging.FileHandler('vcworkspace.log', encoding='utf8') handler.setFo...
vcworkspace.py
import requests import sys import argparse import logging import json import time import string import datetime import anticrlf from veracode_api_py import VeracodeAPI as vapi log = logging.getLogger(__name__) def setup_logger(): handler = logging.FileHandler('vcworkspace.log', encoding='utf8') handler.setFo...
0.207375
0.080719
import bpy import ast import os import sys import re import math from mathutils import Matrix, Vector, Euler from .dynlist_utils import tokenize_list D_MATERIAL = bpy.types.Material D_LIGHT = bpy.types.Light id_database = {} current_mat = None current_object = None current_context = None vertex_count = 0 def selec...
goddard_addon/import_goddard.py
import bpy import ast import os import sys import re import math from mathutils import Matrix, Vector, Euler from .dynlist_utils import tokenize_list D_MATERIAL = bpy.types.Material D_LIGHT = bpy.types.Light id_database = {} current_mat = None current_object = None current_context = None vertex_count = 0 def selec...
0.322739
0.158142
import random import pyglet import logging import os import glob import math from functions import * from actor import Actor, Hand from stats import StatSystem from animations import HandAnimAttack, HeadBobbing, Pulse from load_config import ConfigSectionMap as load_cfg import abilities ROOT = os.path.dirname(__file__)...
player.py
import random import pyglet import logging import os import glob import math from functions import * from actor import Actor, Hand from stats import StatSystem from animations import HandAnimAttack, HeadBobbing, Pulse from load_config import ConfigSectionMap as load_cfg import abilities ROOT = os.path.dirname(__file__)...
0.376738
0.106598
import torch from . import dwt3d, utils __all__ = ["HyRes"] class HyRes(torch.nn.Module): """ HyRes -- Automatic Hyperspectral Restoration Using low-rank and sparse modeling. The model used is :math:`Y=D_2XV'+N` and penalized least squares with :math:`\ell_1` penalty. The formula to restore the sig...
src/hyde/hyres.py
import torch from . import dwt3d, utils __all__ = ["HyRes"] class HyRes(torch.nn.Module): """ HyRes -- Automatic Hyperspectral Restoration Using low-rank and sparse modeling. The model used is :math:`Y=D_2XV'+N` and penalized least squares with :math:`\ell_1` penalty. The formula to restore the sig...
0.868199
0.567248
import re import sys from nose.plugins.attrib import attr from nose.tools import assert_equal, assert_set_equal, assert_true from Bio import SeqIO from Bio.SeqRecord import SeqRecord from plastid.test.ref_files import REF_FILES from plastid.genomics.seqtools import seq_to_regex, mutate_seqs, random_seq,\ ...
plastid/test/unit/genomics/test_seqtools.py
import re import sys from nose.plugins.attrib import attr from nose.tools import assert_equal, assert_set_equal, assert_true from Bio import SeqIO from Bio.SeqRecord import SeqRecord from plastid.test.ref_files import REF_FILES from plastid.genomics.seqtools import seq_to_regex, mutate_seqs, random_seq,\ ...
0.352982
0.428383
from flask import request from sqlalchemy_filters.models import get_model_from_spec, Field, get_default_model, auto_join from sqlalchemy_filters.sorting import Sort as BaseSort from api_utils.constants import ORDERING_PARAM, ORDER_PATTERN SORT_ASCENDING = 'asc' SORT_DESCENDING = 'desc' def sort_query(query, view): ...
api_utils/data_layers/sorting.py
from flask import request from sqlalchemy_filters.models import get_model_from_spec, Field, get_default_model, auto_join from sqlalchemy_filters.sorting import Sort as BaseSort from api_utils.constants import ORDERING_PARAM, ORDER_PATTERN SORT_ASCENDING = 'asc' SORT_DESCENDING = 'desc' def sort_query(query, view): ...
0.72662
0.277666
import os from flask import Flask, render_template, request, redirect from models import site_user, get_restaurant, get_review, suggestion_from_friend, get_category, get_business, get_photo, get_city from py2neo import Graph import requests from hours import split_times from datetime import datetime from random import ...
Webapp/venv/app/views.py
import os from flask import Flask, render_template, request, redirect from models import site_user, get_restaurant, get_review, suggestion_from_friend, get_category, get_business, get_photo, get_city from py2neo import Graph import requests from hours import split_times from datetime import datetime from random import ...
0.206974
0.086323
from django import forms from django.conf import settings from django.core.urlresolvers import reverse from simplepay import HOST, PATH, ACCESS_KEY, SECRET_KEY from urllib import quote import base64 import hashlib import hmac import uuid EXCLUDE_FROM_SIGNATURE = ('signature',) class SignatureField(forms.CharField): ...
simplepay/forms.py
from django import forms from django.conf import settings from django.core.urlresolvers import reverse from simplepay import HOST, PATH, ACCESS_KEY, SECRET_KEY from urllib import quote import base64 import hashlib import hmac import uuid EXCLUDE_FROM_SIGNATURE = ('signature',) class SignatureField(forms.CharField): ...
0.485356
0.071851
from collections import OrderedDict from odoo import http, _ from odoo.addons.website_portal.controllers.main import website_account from odoo.http import request class WebsiteAccount(website_account): def _prepare_portal_layout_values(self): values = super(WebsiteAccount, self)._prepare_portal_layout_...
apps/odoo/lib/odoo-10.0.post20170615-py2.7.egg/odoo/addons/website_project_issue/controllers/main.py
from collections import OrderedDict from odoo import http, _ from odoo.addons.website_portal.controllers.main import website_account from odoo.http import request class WebsiteAccount(website_account): def _prepare_portal_layout_values(self): values = super(WebsiteAccount, self)._prepare_portal_layout_...
0.41834
0.093802
from random import choice from os import system from platform import system as OperationSystem from time import sleep class Vars(object): '''Variables class for Tic Tac Toe game\n''' game_rules = '-= RULES =-\n1. The game is played on a grid that\'s 3 squares by 3 squares.\n2. You choice your sign (X or O), a...
tic_tac_toe.py
from random import choice from os import system from platform import system as OperationSystem from time import sleep class Vars(object): '''Variables class for Tic Tac Toe game\n''' game_rules = '-= RULES =-\n1. The game is played on a grid that\'s 3 squares by 3 squares.\n2. You choice your sign (X or O), a...
0.402744
0.334073
import numpy as np __all__ = [ 'x3_toy', 'x3_gap_toy', 'sin_toy', ] class toy_dataset(object): def __init__(self, name=''): self.name = name def train_samples(self): raise NotImplementedError def test_samples(self): raise NotImplementedError class x3_toy(toy_datas...
data/toy.py
import numpy as np __all__ = [ 'x3_toy', 'x3_gap_toy', 'sin_toy', ] class toy_dataset(object): def __init__(self, name=''): self.name = name def train_samples(self): raise NotImplementedError def test_samples(self): raise NotImplementedError class x3_toy(toy_datas...
0.747155
0.463566
try: import urllib.request as urllib2 except ImportError: import urllib2 import json from dateutil import parser from datetime import date import time from Classes import Play import pickle class Sports_API(object): """Does the interface with the """ def __init__(self, access, version): super...
AnalysisSite/API_IFace.py
try: import urllib.request as urllib2 except ImportError: import urllib2 import json from dateutil import parser from datetime import date import time from Classes import Play import pickle class Sports_API(object): """Does the interface with the """ def __init__(self, access, version): super...
0.348756
0.110615
from __future__ import unicode_literals import json from django import template from django.template.defaultfilters import stringfilter, mark_safe register = template.Library() @register.filter(name="json") def to_json(values): return mark_safe(json.dumps(values)) @register.filter(name="int_list") def to_int_l...
redis_metrics/templatetags/redis_metrics_filters.py
from __future__ import unicode_literals import json from django import template from django.template.defaultfilters import stringfilter, mark_safe register = template.Library() @register.filter(name="json") def to_json(values): return mark_safe(json.dumps(values)) @register.filter(name="int_list") def to_int_l...
0.756537
0.300441
from lyricsprocessor.utils import start_genius_api, load_df, save_text_file from os import path, mkdir from pathlib import Path from typing import Dict, Tuple from pandas import read_hdf from argparse import ArgumentParser from collections import OrderedDict ##################################################...
lyricsprocessor/write_lyrics_to_file/write_lyrics_to_file.py
from lyricsprocessor.utils import start_genius_api, load_df, save_text_file from os import path, mkdir from pathlib import Path from typing import Dict, Tuple from pandas import read_hdf from argparse import ArgumentParser from collections import OrderedDict ##################################################...
0.374219
0.059866
import os import glob import numpy as np import matplotlib.pyplot as plt import random import sys sys.path.append('../../config') from config import Config config = Config() root = config.root sub = '/result/process/new' all_file = os.listdir(root + sub + '/group_velocity') for file in os.listdir(root + sub + '/phase_...
result/process/plot_res.py
import os import glob import numpy as np import matplotlib.pyplot as plt import random import sys sys.path.append('../../config') from config import Config config = Config() root = config.root sub = '/result/process/new' all_file = os.listdir(root + sub + '/group_velocity') for file in os.listdir(root + sub + '/phase_...
0.140042
0.178222
import unittest from autoopt.distributions import Choice from autoopt.pipelines import Pipeline from utils import create_node class TestEmptyPipeline(unittest.TestCase): def setUp(self): self.pipeline = Pipeline() def test_parameter_space(self): self.assertDictEqual(self.pipeline.parameter_s...
tests/pipelines/test_pipeline.py
import unittest from autoopt.distributions import Choice from autoopt.pipelines import Pipeline from utils import create_node class TestEmptyPipeline(unittest.TestCase): def setUp(self): self.pipeline = Pipeline() def test_parameter_space(self): self.assertDictEqual(self.pipeline.parameter_s...
0.544801
0.631481
from unittest import TestCase from unittest.mock import patch from plugins import timetable_plugin from faker import fake_creds, FakeClient, FakeMessage from common.utils import render class TestTimetableFunction(TestCase): client = FakeClient() correct_msg = { 'channel': fake_creds['FAKE_CHANNEL']...
tests/test_timetable_response.py
from unittest import TestCase from unittest.mock import patch from plugins import timetable_plugin from faker import fake_creds, FakeClient, FakeMessage from common.utils import render class TestTimetableFunction(TestCase): client = FakeClient() correct_msg = { 'channel': fake_creds['FAKE_CHANNEL']...
0.737536
0.299041
from ryu.base import app_manager from ryu.controller import ofp_event from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER, DEAD_DISPATCHER from ryu.controller.handler import set_ev_cls from ryu.ofproto import ofproto_v1_3 from ryu.lib import hub import time import os #Datapath ID of each wireless node...
Design of medium-range outdoor wireless mesh network with open-flow enabled raspberry Pi/Rerouting by RYU controller/sdwmn_rerouting.py
from ryu.base import app_manager from ryu.controller import ofp_event from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER, DEAD_DISPATCHER from ryu.controller.handler import set_ev_cls from ryu.ofproto import ofproto_v1_3 from ryu.lib import hub import time import os #Datapath ID of each wireless node...
0.455199
0.22007
from datetime import datetime, timedelta import pytest from manager_core.CurbTheScreen import DataManager, TrackedProgram # Tests to be added # TODO test to_objs many @pytest.fixture(scope="function") def store_example(create_db): with DataManager.StoreData(DataManager) as db: name = "test" sta...
manager_core/tests/test_data_manager.py
from datetime import datetime, timedelta import pytest from manager_core.CurbTheScreen import DataManager, TrackedProgram # Tests to be added # TODO test to_objs many @pytest.fixture(scope="function") def store_example(create_db): with DataManager.StoreData(DataManager) as db: name = "test" sta...
0.5083
0.521593
from flask import render_template, request from app import app import MySQLdb from models import tweet_features, get_tweet_html, validate_tweet @app.route('/') @app.route('/input') def landing(): return render_template("input.html", img_count=0) # input template -> score. Carries image info. @app.route('/sc...
app/views.py
from flask import render_template, request from app import app import MySQLdb from models import tweet_features, get_tweet_html, validate_tweet @app.route('/') @app.route('/input') def landing(): return render_template("input.html", img_count=0) # input template -> score. Carries image info. @app.route('/sc...
0.405802
0.075892
import time from acts.test_utils.tel.TelephonyBaseTest import TelephonyBaseTest from acts.test_utils.tel.tel_defines import CALL_CAPABILITY_MANAGE_CONFERENCE from acts.test_utils.tel.tel_defines import CALL_CAPABILITY_MERGE_CONFERENCE from acts.test_utils.tel.tel_defines import CALL_CAPABILITY_SWAP_CONFERENCE from acts...
test/connectivity/acts/tests/google/tel/live/TelLiveVoiceConfTest.py
import time from acts.test_utils.tel.TelephonyBaseTest import TelephonyBaseTest from acts.test_utils.tel.tel_defines import CALL_CAPABILITY_MANAGE_CONFERENCE from acts.test_utils.tel.tel_defines import CALL_CAPABILITY_MERGE_CONFERENCE from acts.test_utils.tel.tel_defines import CALL_CAPABILITY_SWAP_CONFERENCE from acts...
0.28877
0.361785
import os import sys import struct import hashlib import filecmp import logging import argparse import time CHUNK_SIZE = 4096 SMART_LIMIT = 2**10 def get_info(path): return { 'path': path, 'stat': os.stat(path) } def relpath(info): return info['relpath'] def fileid(info): return info['stat'].st_dev, in...
rdfind.py
import os import sys import struct import hashlib import filecmp import logging import argparse import time CHUNK_SIZE = 4096 SMART_LIMIT = 2**10 def get_info(path): return { 'path': path, 'stat': os.stat(path) } def relpath(info): return info['relpath'] def fileid(info): return info['stat'].st_dev, in...
0.14624
0.130701
from .base_lutman import Base_LutMan, get_redundant_codewords import numpy as np from collections import Iterable, OrderedDict from qcodes.instrument.parameter import ManualParameter from qcodes.utils import validators as vals from pycqed.measurement.waveform_control_CC import waveform as wf class Base_MW_LutMan(Base...
pycqed/instrument_drivers/meta_instrument/LutMans/mw_lutman.py
from .base_lutman import Base_LutMan, get_redundant_codewords import numpy as np from collections import Iterable, OrderedDict from qcodes.instrument.parameter import ManualParameter from qcodes.utils import validators as vals from pycqed.measurement.waveform_control_CC import waveform as wf class Base_MW_LutMan(Base...
0.696165
0.263324
import os import numpy as np import torch from .chexpert.data_loader import load_partition_data_chexpert import logging def load(args): return load_synthetic_data(args) def combine_batches(batches): full_x = torch.from_numpy(np.asarray([])).float() full_y = torch.from_numpy(np.asarray([])).long() ...
app/fedcv/medical_chest_xray_image_clf/data/data_loader.py
import os import numpy as np import torch from .chexpert.data_loader import load_partition_data_chexpert import logging def load(args): return load_synthetic_data(args) def combine_batches(batches): full_x = torch.from_numpy(np.asarray([])).float() full_y = torch.from_numpy(np.asarray([])).long() ...
0.540681
0.361982
# ----------------------------- MAIN ----------------------------- from astropy.table import Table import numpy as np import time # My modules from vsh_fit import vsh_fit from pmt_convert import st_to_rotgldquad from generate_test_data import generate_test_sample # Read the simulated data rot_vec = np.array([20, 30...
tune_para.py
# ----------------------------- MAIN ----------------------------- from astropy.table import Table import numpy as np import time # My modules from vsh_fit import vsh_fit from pmt_convert import st_to_rotgldquad from generate_test_data import generate_test_sample # Read the simulated data rot_vec = np.array([20, 30...
0.436982
0.478773
import logging import telnetlib import unicodedata import urllib.parse import select from .screen import Screen logger = logging.getLogger(__name__) class Server(object): """ LCDproc Server Object """ def __init__(self, hostname="localhost", port=13666, debug=False, charset='utf-8'): """ Construc...
mpdlcd/vendor/lcdproc/server.py
import logging import telnetlib import unicodedata import urllib.parse import select from .screen import Screen logger = logging.getLogger(__name__) class Server(object): """ LCDproc Server Object """ def __init__(self, hostname="localhost", port=13666, debug=False, charset='utf-8'): """ Construc...
0.329068
0.085366
def enum(**enums): return type('Enum', (), enums) EActivitiesErrorTypes = enum(HTTP=1, SQL=2, GENERAL=3, FILE=4, VALIDATION=5, LADDER=7) EActivitiesHttpErrors = enum( FILE_TOO_LARGE=1, NO_FILES=4, FILE_PERMISSIONS_ERROR=5, FILE_UPLOAD_TIMEOUT=8, FILE_COLLISION=60001, FILE_MAX_COUNT=60002 ...
eactivities/exceptions.py
def enum(**enums): return type('Enum', (), enums) EActivitiesErrorTypes = enum(HTTP=1, SQL=2, GENERAL=3, FILE=4, VALIDATION=5, LADDER=7) EActivitiesHttpErrors = enum( FILE_TOO_LARGE=1, NO_FILES=4, FILE_PERMISSIONS_ERROR=5, FILE_UPLOAD_TIMEOUT=8, FILE_COLLISION=60001, FILE_MAX_COUNT=60002 ...
0.422862
0.057467
import terrascript class elasticsearch_component_template(terrascript.Resource): pass class elasticsearch_composable_index_template(terrascript.Resource): pass class elasticsearch_index(terrascript.Resource): pass class elasticsearch_index_template(terrascript.Resource): pass class elasticsear...
terrascript/resource/phillbaker/elasticsearch.py
import terrascript class elasticsearch_component_template(terrascript.Resource): pass class elasticsearch_composable_index_template(terrascript.Resource): pass class elasticsearch_index(terrascript.Resource): pass class elasticsearch_index_template(terrascript.Resource): pass class elasticsear...
0.488283
0.143008
import dataclasses import enum import typing from typing import Dict, List, Mapping, Optional import attr from ventserver.protocols import events from ventserver.protocols.application import clocks, lists from ventserver.protocols.protobuf import mcu_pb from ventserver.sansio import channels, protocols # Events ...
backend/ventserver/protocols/backend/log.py
import dataclasses import enum import typing from typing import Dict, List, Mapping, Optional import attr from ventserver.protocols import events from ventserver.protocols.application import clocks, lists from ventserver.protocols.protobuf import mcu_pb from ventserver.sansio import channels, protocols # Events ...
0.910339
0.162115
import flask medalDict = { "games-played-1" : { "name" : "Tourist", "text" : "Played {} games on this server", "color" : "white", "text-color" : "black" }, "games-played-2" : { "...
medals.py
import flask medalDict = { "games-played-1" : { "name" : "Tourist", "text" : "Played {} games on this server", "color" : "white", "text-color" : "black" }, "games-played-2" : { "...
0.264358
0.226014
import math import srwlib import numpy as np from srwlib import * def createGsnSrcSRW(sigrW,propLen,pulseE,poltype,phE=10e3,sampFact=15,mx=0,my=0): """ #sigrW: beam size at waist [m] #propLen: propagation length [m] required by SRW to create numerical Gaussian #pulseE: energy per pulse [J] #poltyp...
rslaser/rsoptics/wavefront.py
import math import srwlib import numpy as np from srwlib import * def createGsnSrcSRW(sigrW,propLen,pulseE,poltype,phE=10e3,sampFact=15,mx=0,my=0): """ #sigrW: beam size at waist [m] #propLen: propagation length [m] required by SRW to create numerical Gaussian #pulseE: energy per pulse [J] #poltyp...
0.513668
0.579103
import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'o6hk&s9ffvgn5g3k$))i=@7k16g#ai@oom4m#...
sampleproject/sampleproject/settings.py
import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'o6hk&s9ffvgn5g3k$))i=@7k16g#ai@oom4m#...
0.389198
0.060142
from tdp_core.dbview import DBViewBuilder, DBConnector, add_common_queries, inject_where, DBMapping # idtype of our rows idtype = 'MyIDType' # columns of our mytable, it is used to verify dynamic parameters columns = ['name', 'cat', 'value'] mappings = [ DBMapping('MyIDType', 'IDTypeB', """SELECT my_id as f, b_id as...
myserverplugin/mydb.py
from tdp_core.dbview import DBViewBuilder, DBConnector, add_common_queries, inject_where, DBMapping # idtype of our rows idtype = 'MyIDType' # columns of our mytable, it is used to verify dynamic parameters columns = ['name', 'cat', 'value'] mappings = [ DBMapping('MyIDType', 'IDTypeB', """SELECT my_id as f, b_id as...
0.569134
0.255657
import torch import torch.nn as nn import rlutils.pytorch as rlu class EnsembleMinQNet(nn.Module): def __init__(self, ob_dim, ac_dim, mlp_hidden, num_ensembles=2, num_layers=3): super(EnsembleMinQNet, self).__init__() self.ob_dim = ob_dim self.ac_dim = ac_dim self.mlp_hidden = mlp...
rlutils/pytorch/nn/values.py
import torch import torch.nn as nn import rlutils.pytorch as rlu class EnsembleMinQNet(nn.Module): def __init__(self, ob_dim, ac_dim, mlp_hidden, num_ensembles=2, num_layers=3): super(EnsembleMinQNet, self).__init__() self.ob_dim = ob_dim self.ac_dim = ac_dim self.mlp_hidden = mlp...
0.931688
0.502197
from abc import ABC, abstractmethod from typing import Sequence from pysavime.savime.datatype import SavimeSupportedTypes class ReprMixIn: """ Adds generic functionality for printing string representations. """ def __repr__(self): if len(self.__slots__) > 0: attrs_str = ', '.join...
pysavime/schema/schema.py
from abc import ABC, abstractmethod from typing import Sequence from pysavime.savime.datatype import SavimeSupportedTypes class ReprMixIn: """ Adds generic functionality for printing string representations. """ def __repr__(self): if len(self.__slots__) > 0: attrs_str = ', '.join...
0.944702
0.536374
import xarray as xr from ..utils import wraparound from . import FiniteDiff, BwdDiff, FwdDiff class CenDiff(FiniteDiff): """Centered finite differencing.""" _MIN_SPACING_FACTOR = 2 _DIFF_BWD_CLS = BwdDiff _DIFF_FWD_CLS = FwdDiff def __init__(self, arr, dim, spacing=1, fill_edge=False, wrap=False...
indiff/diff/centered.py
import xarray as xr from ..utils import wraparound from . import FiniteDiff, BwdDiff, FwdDiff class CenDiff(FiniteDiff): """Centered finite differencing.""" _MIN_SPACING_FACTOR = 2 _DIFF_BWD_CLS = BwdDiff _DIFF_FWD_CLS = FwdDiff def __init__(self, arr, dim, spacing=1, fill_edge=False, wrap=False...
0.872755
0.46794
r""" --- Day 7: The Sum of Its Parts --- You find yourself standing on a snow-covered coastline; apparently, you landed a little off course. The region is too hilly to see the North Pole from here, but you do spot some Elves that seem to be trying to unpack something that washed ashore. It's quite cold out, so you dec...
2018/07_the_sum_of_its_parts.py
r""" --- Day 7: The Sum of Its Parts --- You find yourself standing on a snow-covered coastline; apparently, you landed a little off course. The region is too hilly to see the North Pole from here, but you do spot some Elves that seem to be trying to unpack something that washed ashore. It's quite cold out, so you dec...
0.719679
0.640861
import os import glob import subprocess as sp heads = """ VERSION: 1 EXPID: GEOSldas_expid EXPDSC: GEOSldas_output EXPSRC: GEOSldas COLLECTIONS: """ label = """ :: GRID_LABELS: PC720x361-DC :: PC720x361-DC.GRID_TYPE: LatLon PC720x361-DC.IM_WORLD: 720 PC720x361-DC.JM_WORLD: 361 PC720x361-DC.POLE: PC PC720x361-DC.DAT...
src/Applications/LDAS_App/util/generate_catchincr_hist.py
import os import glob import subprocess as sp heads = """ VERSION: 1 EXPID: GEOSldas_expid EXPDSC: GEOSldas_output EXPSRC: GEOSldas COLLECTIONS: """ label = """ :: GRID_LABELS: PC720x361-DC :: PC720x361-DC.GRID_TYPE: LatLon PC720x361-DC.IM_WORLD: 720 PC720x361-DC.JM_WORLD: 361 PC720x361-DC.POLE: PC PC720x361-DC.DAT...
0.247623
0.048294
import numpy as np from sklearn.datasets import fetch_mldata class LabeledSet: def __init__(self,x,y,input_dim,output_dim): self.x = x self.y = y self.input_dim = input_dim self.output_dim = output_dim #Renvoie la dimension de l'espace d'entrée def getInputDime...
DataClass.py
import numpy as np from sklearn.datasets import fetch_mldata class LabeledSet: def __init__(self,x,y,input_dim,output_dim): self.x = x self.y = y self.input_dim = input_dim self.output_dim = output_dim #Renvoie la dimension de l'espace d'entrée def getInputDime...
0.398055
0.464173
import numpy as np import matplotlib.pyplot as plt #coiefficient calculation def regress(x, x_s, t_s, M, N,lamda = 0): order_list = np.arange((M + 1)) order_list = order_list[ :, np.newaxis] exponent = np.tile(order_list,[1,N]) h = np.power(x_s,exponent) a = np.matmul(h, np.transpose(h)) + lamda...
polynomial-curve-fitting.py
import numpy as np import matplotlib.pyplot as plt #coiefficient calculation def regress(x, x_s, t_s, M, N,lamda = 0): order_list = np.arange((M + 1)) order_list = order_list[ :, np.newaxis] exponent = np.tile(order_list,[1,N]) h = np.power(x_s,exponent) a = np.matmul(h, np.transpose(h)) + lamda...
0.364778
0.645316
from __future__ import unicode_literals from .common import InfoExtractor from ..compat import compat_urllib_parse_urlparse from ..utils import remove_end class IwaraIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.|ecchi\.)?iwara\.tv/videos/(?P<id>[a-zA-Z0-9]+)' _TESTS = [{ 'url': 'http://iwara.tv...
youtube_dl/extractor/iwara.py
from __future__ import unicode_literals from .common import InfoExtractor from ..compat import compat_urllib_parse_urlparse from ..utils import remove_end class IwaraIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.|ecchi\.)?iwara\.tv/videos/(?P<id>[a-zA-Z0-9]+)' _TESTS = [{ 'url': 'http://iwara.tv...
0.471467
0.146148
from __future__ import unicode_literals ,print_function import serial from time import sleep import numpy as np import matplotlib.pyplot as plt import io import csv import time import datetime import struct import math # Variable to get real value MPU9250A_2g = 0.000061035156 # 0.000061035156 g/LSB MP...
extract/calc_calibration_1_1.py
from __future__ import unicode_literals ,print_function import serial from time import sleep import numpy as np import matplotlib.pyplot as plt import io import csv import time import datetime import struct import math # Variable to get real value MPU9250A_2g = 0.000061035156 # 0.000061035156 g/LSB MP...
0.248899
0.150372
# Copyright 2020 AntiCompositeNumber # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writ...
tests/test_sigprobs.py
# Copyright 2020 AntiCompositeNumber # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writ...
0.709523
0.425963
from matplotlib.pyplot import subplots, figure, Subplot, Axes # , figure, plot, show import numpy as np from collections import OrderedDict # defaultdict def plot_chains(chains, lnprobability, l_param_name=None, l_walker=None, l_burnin=None, suppress_burnin=False, plot_height=2, plot_width=8, truths...
CaRM_HD189733/scripts/plot_chains.py
from matplotlib.pyplot import subplots, figure, Subplot, Axes # , figure, plot, show import numpy as np from collections import OrderedDict # defaultdict def plot_chains(chains, lnprobability, l_param_name=None, l_walker=None, l_burnin=None, suppress_burnin=False, plot_height=2, plot_width=8, truths...
0.466603
0.270989
import pandas as pd from audl.stats.library.data import teams from audl.stats.library.data import teams_columns_name from audl.stats.library.data import team_col_id, team_col_abr, team_col_full_name, team_col_team_name , team_col_city, team_col_state, team_col_year_founded from audl.stats.library.data import team_index...
audl/stats/static/teams.py
import pandas as pd from audl.stats.library.data import teams from audl.stats.library.data import teams_columns_name from audl.stats.library.data import team_col_id, team_col_abr, team_col_full_name, team_col_team_name , team_col_city, team_col_state, team_col_year_founded from audl.stats.library.data import team_index...
0.352982
0.200675
from uuid import UUID from myapp.application.domain.model.article_vote import ArticleVote from myapp.application.domain.model.cast_article_vote_result import VoteAlreadyCast, \ InsufficientKarma from myapp.application.domain.model.vote import Vote from myapp.application.domain.model.voting_user import VotingUser f...
tests/test_myapp/application/service/test_post_rating_service.py
from uuid import UUID from myapp.application.domain.model.article_vote import ArticleVote from myapp.application.domain.model.cast_article_vote_result import VoteAlreadyCast, \ InsufficientKarma from myapp.application.domain.model.vote import Vote from myapp.application.domain.model.voting_user import VotingUser f...
0.587233
0.092319
import re from ctdpy.core import utils from ctdpy.core.data_handlers import DataFrameHandler from ctdpy.core.data_handlers import SeriesHandler from ctdpy.core.data_handlers import BaseReader from ctdpy.core.readers.cnv_reader import CNVreader class SeaBird(BaseReader, CNVreader, SeriesHandler): """Base for all s...
ctdpy/core/readers/seabird.py
import re from ctdpy.core import utils from ctdpy.core.data_handlers import DataFrameHandler from ctdpy.core.data_handlers import SeriesHandler from ctdpy.core.data_handlers import BaseReader from ctdpy.core.readers.cnv_reader import CNVreader class SeaBird(BaseReader, CNVreader, SeriesHandler): """Base for all s...
0.754373
0.242688
import os import hashlib import pickle import threading import logging from socketserver import BaseRequestHandler import typing import paramiko class RequestsManager(): """A class for creating requests for the client and manage control messages protocol""" # ----------Constants---------- READY = "ready" ...
Anylink-server/requests_manager.py
import os import hashlib import pickle import threading import logging from socketserver import BaseRequestHandler import typing import paramiko class RequestsManager(): """A class for creating requests for the client and manage control messages protocol""" # ----------Constants---------- READY = "ready" ...
0.671686
0.087798
from collections import deque, OrderedDict from rlkit.core.eval_util import create_stats_ordered_dict from rlkit.samplers.rollout_functions import rollout, multitask_rollout from rlkit.samplers.data_collector.base import PathCollector class MdpPathCollector(PathCollector): def __init__( self, ...
rlkit/rlkit/samplers/data_collector/path_collector.py
from collections import deque, OrderedDict from rlkit.core.eval_util import create_stats_ordered_dict from rlkit.samplers.rollout_functions import rollout, multitask_rollout from rlkit.samplers.data_collector.base import PathCollector class MdpPathCollector(PathCollector): def __init__( self, ...
0.779448
0.249619
import os.path import codecs import markdown import re html_template = u"""<!DOCTYPE html> <html> <head> <title>%(title)s</title> <link rel="stylesheet" type="text/css" href="css/styles.css"> </head> <body> <div id="wikid-content"> <aside id="wikid-sidebar"> ...
wikid/convert.py
import os.path import codecs import markdown import re html_template = u"""<!DOCTYPE html> <html> <head> <title>%(title)s</title> <link rel="stylesheet" type="text/css" href="css/styles.css"> </head> <body> <div id="wikid-content"> <aside id="wikid-sidebar"> ...
0.270769
0.042206
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('category', '0001_initial'), ] operations = ...
saffrun/profile/migrations/0001_initial.py
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('category', '0001_initial'), ] operations = ...
0.566978
0.187802
import os import silence_detector import shutil from helperutils.stemloader import StemLoader stem_loader = StemLoader() def find_contiguous_silences(sound, silence_threshold=-50.0, chunk_size=1000): trim_ms = 0 silences = [] current_silence_start = None while trim_ms < len(sound): if sound[...
silencio/silence_cutter.py
import os import silence_detector import shutil from helperutils.stemloader import StemLoader stem_loader = StemLoader() def find_contiguous_silences(sound, silence_threshold=-50.0, chunk_size=1000): trim_ms = 0 silences = [] current_silence_start = None while trim_ms < len(sound): if sound[...
0.303835
0.110856
import time from handover.libs.mininet.log import setLogLevel, info from handover.libs.mininet.net import Containernet from handover.conf import * from handover.libs.mininet.node import OVSSwitch from handover.libs.mininet.node import RemoteController CAPTURE_PACKETS = 0 def build_topology(state_transfer_duration=...
handover/containernet_setup.py
import time from handover.libs.mininet.log import setLogLevel, info from handover.libs.mininet.net import Containernet from handover.conf import * from handover.libs.mininet.node import OVSSwitch from handover.libs.mininet.node import RemoteController CAPTURE_PACKETS = 0 def build_topology(state_transfer_duration=...
0.337531
0.061876
import time import json class DummyVolatileStore(object): """ This is a dummy volatile store that makes use of a local json file """ _path = '/tmp/dummyvolatile.json' _storage = {} _timeout = {} @staticmethod def clean(): """ Empties the store """ impor...
ovs/extensions/storage/volatile/dummystore.py
import time import json class DummyVolatileStore(object): """ This is a dummy volatile store that makes use of a local json file """ _path = '/tmp/dummyvolatile.json' _storage = {} _timeout = {} @staticmethod def clean(): """ Empties the store """ impor...
0.399577
0.26789
import os import requests from datetime import datetime, timedelta from time import sleep from api.mongo import get_database DISCORD_TOKEN = os.getenv('DISCORD_TOKEN') DISCORD_CHANNEL_ID = os.getenv('DISCORD_CHANNEL_ID') DISCORD_API_BASE_URL = os.getenv('DISCORD_API_BASE_URL') or 'https://discord.com/api' DISCORD_MESS...
api/discord.py
import os import requests from datetime import datetime, timedelta from time import sleep from api.mongo import get_database DISCORD_TOKEN = os.getenv('DISCORD_TOKEN') DISCORD_CHANNEL_ID = os.getenv('DISCORD_CHANNEL_ID') DISCORD_API_BASE_URL = os.getenv('DISCORD_API_BASE_URL') or 'https://discord.com/api' DISCORD_MESS...
0.27914
0.145025
import json import os from datetime import datetime, time, timedelta from typing import List, Optional, Union import yaml from pydantic import BaseModel, root_validator, validator from pacsanini.convert import datetime2str, str2datetime from pacsanini.models import DicomNode, QueryLevel, StorageSortKey from pacsani...
src/pacsanini/config.py
import json import os from datetime import datetime, time, timedelta from typing import List, Optional, Union import yaml from pydantic import BaseModel, root_validator, validator from pacsanini.convert import datetime2str, str2datetime from pacsanini.models import DicomNode, QueryLevel, StorageSortKey from pacsani...
0.872116
0.369343
from nflows import transforms, distributions, flows class SphereCEFlow(flows.InjectiveFlow): def __init__(self): n = 3 m = 2 conf_embedding = transforms.CompositeTransform([ transforms.ConformalScaleShift(n, m), transforms.Orthogonal(n), transforms.Spec...
nflows/cef_models.py
from nflows import transforms, distributions, flows class SphereCEFlow(flows.InjectiveFlow): def __init__(self): n = 3 m = 2 conf_embedding = transforms.CompositeTransform([ transforms.ConformalScaleShift(n, m), transforms.Orthogonal(n), transforms.Spec...
0.939345
0.582877
import argparse import os from os.path import abspath, dirname, exists, join from shutil import rmtree from subprocess import call from tempfile import mkdtemp REPO_ROOT = dirname(dirname(abspath(__file__))) TEMPLATE_PATH = join(REPO_ROOT, 'project_template') DEV_SITE_NAME = 'dev_site' DEV_SITE_PATH = join(REPO_ROOT,...
scripts/dev_site.py
import argparse import os from os.path import abspath, dirname, exists, join from shutil import rmtree from subprocess import call from tempfile import mkdtemp REPO_ROOT = dirname(dirname(abspath(__file__))) TEMPLATE_PATH = join(REPO_ROOT, 'project_template') DEV_SITE_NAME = 'dev_site' DEV_SITE_PATH = join(REPO_ROOT,...
0.117167
0.071884
from __future__ import print_function import sys # Uses GNU readline on UNIX-like operating systems, pyreadline on Windows. import readline import pinject class SimplePrompt(object): @pinject.copy_args_to_internal_fields def __init__(self, prompt_for_line, set_completions): pass def __call__(sel...
lsf_ibutils/ibsub/input.py
from __future__ import print_function import sys # Uses GNU readline on UNIX-like operating systems, pyreadline on Windows. import readline import pinject class SimplePrompt(object): @pinject.copy_args_to_internal_fields def __init__(self, prompt_for_line, set_completions): pass def __call__(sel...
0.498047
0.221983
from pyspark.sql import SparkSession from pyspark import SparkConf from pyspark.sql.types import * from pyspark.sql.functions import count, when from pyspark.ml.feature import RegexTokenizer, CountVectorizer, IDF ################################################# # spark config #############################...
preproc_in_Spark/NYT_prepare_corpus.py
from pyspark.sql import SparkSession from pyspark import SparkConf from pyspark.sql.types import * from pyspark.sql.functions import count, when from pyspark.ml.feature import RegexTokenizer, CountVectorizer, IDF ################################################# # spark config #############################...
0.47171
0.240084
from unittest import TestCase from ddt import ddt, data from pyleecan.Classes.Arc1 import Arc1 from pyleecan.Methods.Geometry.Arc1.check import PointArc1Error, RadiusArc1Error from pyleecan.Methods.Geometry.Arc1.discretize import NbPointArc1DError from numpy import pi, exp, sqrt, array # For AlmostEqual DELTA = 1e...
Tests/Methods/Geometry/test_Arc1_meth.py
from unittest import TestCase from ddt import ddt, data from pyleecan.Classes.Arc1 import Arc1 from pyleecan.Methods.Geometry.Arc1.check import PointArc1Error, RadiusArc1Error from pyleecan.Methods.Geometry.Arc1.discretize import NbPointArc1DError from numpy import pi, exp, sqrt, array # For AlmostEqual DELTA = 1e...
0.419648
0.557544
from datetime import datetime, timedelta import pandas as pd import numpy as np import src.variables as var pd.set_option('display.max_rows', 1000) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) class CalculateStrengthsTime: def __init__(self, year): self.year = year ...
src/d_create_strengths_on_time.py
from datetime import datetime, timedelta import pandas as pd import numpy as np import src.variables as var pd.set_option('display.max_rows', 1000) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) class CalculateStrengthsTime: def __init__(self, year): self.year = year ...
0.681515
0.252398
__all__ = ['SEED', 'auto_assign', 'HypsterBase', 'HpExpression', 'HYPSTER_TYPES', 'SubExpression', 'AddExpression', 'MulExpression', 'DivExpression', 'PowExpression', 'set_init_name', 'HpInt', 'HpFloat', 'HpFunc', 'HpCategorical', 'HpBool', 'HpToggle', 'HpVarLenList', 'HpIterable', 'list_to_tuple...
hypster/oo_hp.py
__all__ = ['SEED', 'auto_assign', 'HypsterBase', 'HpExpression', 'HYPSTER_TYPES', 'SubExpression', 'AddExpression', 'MulExpression', 'DivExpression', 'PowExpression', 'set_init_name', 'HpInt', 'HpFloat', 'HpFunc', 'HpCategorical', 'HpBool', 'HpToggle', 'HpVarLenList', 'HpIterable', 'list_to_tuple...
0.325735
0.24389
import random import unittest import os import pprint import requests from serpapi import GoogleSearch class TestSearchApi(unittest.TestCase): def setUp(self): GoogleSearch.SERP_API_KEY = os.getenv("API_KEY", "demo") @unittest.skipIf((os.getenv("API_KEY") == None), "no api_key provided") def test_paginate(...
tests/test_google_search.py
import random import unittest import os import pprint import requests from serpapi import GoogleSearch class TestSearchApi(unittest.TestCase): def setUp(self): GoogleSearch.SERP_API_KEY = os.getenv("API_KEY", "demo") @unittest.skipIf((os.getenv("API_KEY") == None), "no api_key provided") def test_paginate(...
0.216012
0.203826
import os import numpy as np from tqdm import tqdm import torch import librosa import warnings warnings.filterwarnings("ignore") def audio_to_mel_and_temp(audio): y, sr = librosa.load(audio, sr=22050) S = librosa.feature.melspectrogram(y=y, sr=22050) oenv = librosa.onset.onset_s...
feature_extraction.py
import os import numpy as np from tqdm import tqdm import torch import librosa import warnings warnings.filterwarnings("ignore") def audio_to_mel_and_temp(audio): y, sr = librosa.load(audio, sr=22050) S = librosa.feature.melspectrogram(y=y, sr=22050) oenv = librosa.onset.onset_s...
0.2359
0.312069
from typing import List, Optional import torch class AddFeatsByKeys(object): """This transform takes a list of attributes names and if allowed, add them to x Example: Before calling "AddFeatsByKeys", if data.x was empty - transform: AddFeatsByKeys params: list_add_to_x:...
src/core/transforms.py
from typing import List, Optional import torch class AddFeatsByKeys(object): """This transform takes a list of attributes names and if allowed, add them to x Example: Before calling "AddFeatsByKeys", if data.x was empty - transform: AddFeatsByKeys params: list_add_to_x:...
0.910015
0.658143
import os from pathlib import Path import pandas as pd from autogluon.tabular import TabularPredictor from pytorch_widedeep.utils import LabelEncoder from sklearn.model_selection import train_test_split SEED = 42 if __name__ == '__main__': ROOTDIR = Path('/home/wenqi-ao/userdata/workdirs/automl_benchmark') P...
examples/automlbechmark/run_experiments/adult/adult_groupby.py
import os from pathlib import Path import pandas as pd from autogluon.tabular import TabularPredictor from pytorch_widedeep.utils import LabelEncoder from sklearn.model_selection import train_test_split SEED = 42 if __name__ == '__main__': ROOTDIR = Path('/home/wenqi-ao/userdata/workdirs/automl_benchmark') P...
0.357343
0.300079
import re import os import sys import logging from pathlib import Path from functools import wraps from tempfile import TemporaryDirectory, TemporaryFile import unittest import asyncio import numpy as np from numpy.testing import assert_equal from aiohttp.web import ( Application, AppRunner, TCPSite, ...
aaclient/test/test_aa.py
import re import os import sys import logging from pathlib import Path from functools import wraps from tempfile import TemporaryDirectory, TemporaryFile import unittest import asyncio import numpy as np from numpy.testing import assert_equal from aiohttp.web import ( Application, AppRunner, TCPSite, ...
0.250638
0.138958
import os import h5py import numpy as np from BackEnd.CNN_retrieval.extract_cnn_vgg16_keras import VGGNet ''' ap = argparse.ArgumentParser() ap.add_argument("-database", required=True, help="Path to database which contains images to be indexed") ap.add_argument("-index", required=True, help="Name of index file") arg...
Serveur_CNN/BackEnd/CNN_retrieval/index.py
import os import h5py import numpy as np from BackEnd.CNN_retrieval.extract_cnn_vgg16_keras import VGGNet ''' ap = argparse.ArgumentParser() ap.add_argument("-database", required=True, help="Path to database which contains images to be indexed") ap.add_argument("-index", required=True, help="Name of index file") arg...
0.375134
0.14685
import numpy as np import matplotlib import matplotlib.pyplot as plt plt.style.use('seaborn-darkgrid') import argparse import csv import os import json import sys import pickle import numpy as np import pandas as pd from os.path import join def plot_compare_runs(log_dir='log/random/train', run_ids=[0,1], keys=['eprew1...
train_procgen/plotting/plot_utils.py
import numpy as np import matplotlib import matplotlib.pyplot as plt plt.style.use('seaborn-darkgrid') import argparse import csv import os import json import sys import pickle import numpy as np import pandas as pd from os.path import join def plot_compare_runs(log_dir='log/random/train', run_ids=[0,1], keys=['eprew1...
0.217836
0.413181
import os import numpy as np import pandas as pd import csv from pydub import AudioSegment import scipy.io.wavfile as wav def opensmile_executable(data, baby_id, classes, args): """ Generate a text file executable on shell to compute multiple times opensmile features. If option labels_creation == True, it ...
vocSpace_utils.py
import os import numpy as np import pandas as pd import csv from pydub import AudioSegment import scipy.io.wavfile as wav def opensmile_executable(data, baby_id, classes, args): """ Generate a text file executable on shell to compute multiple times opensmile features. If option labels_creation == True, it ...
0.195902
0.15428
from django import forms from rekruter.models import RotationPlan, RotationStep, RotationSubStep from core.snippets import flare import datetime class RotationPlanForm(forms.ModelForm): title = forms.CharField(max_length=150, required=True) class Meta: model = RotationPlan fields = ("title", ...
crop_rotator/rotator/forms.py
from django import forms from rekruter.models import RotationPlan, RotationStep, RotationSubStep from core.snippets import flare import datetime class RotationPlanForm(forms.ModelForm): title = forms.CharField(max_length=150, required=True) class Meta: model = RotationPlan fields = ("title", ...
0.617513
0.21215
angular_quanta = { "S": (0, 0, 0), "Px": (1, 0, 0), "Py": (0, 1, 0), "Pz": (0, 0, 1), "Dx2": (2, 0, 0), "Dy2": (0, 2, 0), "Dz2": (0, 0, 2), "Dxy": (1, 1, 0), "Dyz": (0, 1, 1), "Dzx": (1, 0, 1), } elements = { "H": (1, "Hydrogen"), "He": (2, "Helium"), ...
playground/utils.py
angular_quanta = { "S": (0, 0, 0), "Px": (1, 0, 0), "Py": (0, 1, 0), "Pz": (0, 0, 1), "Dx2": (2, 0, 0), "Dy2": (0, 2, 0), "Dz2": (0, 0, 2), "Dxy": (1, 1, 0), "Dyz": (0, 1, 1), "Dzx": (1, 0, 1), } elements = { "H": (1, "Hydrogen"), "He": (2, "Helium"), ...
0.498535
0.51379
from typing import Tuple import torch from torch import nn from torch.distributions.categorical import Categorical from torch.nn import functional as F from networks.layers import CNNEncoder class PPONet(nn.Module): def __init__( self, width: int, height: int, num_frames: int, ...
networks/ppo_networks.py
from typing import Tuple import torch from torch import nn from torch.distributions.categorical import Categorical from torch.nn import functional as F from networks.layers import CNNEncoder class PPONet(nn.Module): def __init__( self, width: int, height: int, num_frames: int, ...
0.970937
0.489259
from dataclasses import dataclass @dataclass class State: a: int b: int offset: int def half(self, register, *_): if register == "a": self.a //= 2 elif register == "b": self.b //= 2 self.offset += 1 def tripple(self, register, *_): if regis...
aoc_cas/aoc2015/day23.py
from dataclasses import dataclass @dataclass class State: a: int b: int offset: int def half(self, register, *_): if register == "a": self.a //= 2 elif register == "b": self.b //= 2 self.offset += 1 def tripple(self, register, *_): if regis...
0.578924
0.42919
from typing import TYPE_CHECKING, Dict, Any, Set from bag.layout.routing.base import TrackManager, TrackID from abs_templates_ec.laygo.core import LaygoBase if TYPE_CHECKING: from bag.layout.template import TemplateDB class LaygoDummy(LaygoBase): """A dummy laygo cell to test AnalogBase-LaygoBase pitch mat...
serdes_ec/layout/laygo/misc.py
from typing import TYPE_CHECKING, Dict, Any, Set from bag.layout.routing.base import TrackManager, TrackID from abs_templates_ec.laygo.core import LaygoBase if TYPE_CHECKING: from bag.layout.template import TemplateDB class LaygoDummy(LaygoBase): """A dummy laygo cell to test AnalogBase-LaygoBase pitch mat...
0.803444
0.228964
from tkinter import * def click(arg): text = display.get() + str(arg) display.delete(0,END) display.insert(0,text) def evaluate(): ans = eval(display.get()) display.delete(0,END) display.insert(0,ans) def clear(): display.delete(0,END) # * Creating the root root = Tk() root.title('Calcul...
calculator.py
from tkinter import * def click(arg): text = display.get() + str(arg) display.delete(0,END) display.insert(0,text) def evaluate(): ans = eval(display.get()) display.delete(0,END) display.insert(0,ans) def clear(): display.delete(0,END) # * Creating the root root = Tk() root.title('Calcul...
0.336876
0.074064
import yfinance as yf import datetime as dt import pandas as pd import numpy as np from pandas.plotting import table import matplotlib.pyplot as plt from scipy.stats import levene # Download historical data for S&P 500 ticker = "^GSPC" SnP = yf.download(ticker, start="1991-02-01", end="2018-06-01") SnP = SnP.drop(['Op...
Sess3_Project.py
import yfinance as yf import datetime as dt import pandas as pd import numpy as np from pandas.plotting import table import matplotlib.pyplot as plt from scipy.stats import levene # Download historical data for S&P 500 ticker = "^GSPC" SnP = yf.download(ticker, start="1991-02-01", end="2018-06-01") SnP = SnP.drop(['Op...
0.612194
0.763263
from collections import defaultdict def parse_line(line: str) -> str: state = True if line.startswith("on") else False coords = line[3 if state else 4:].split(",") return [state] + [(int(p[0]), int(p[1])) for p in (pos[2:].split("..") for pos in coords)] def read_file(filename: str = "input.txt") -> defa...
2021/22/code.py
from collections import defaultdict def parse_line(line: str) -> str: state = True if line.startswith("on") else False coords = line[3 if state else 4:].split(",") return [state] + [(int(p[0]), int(p[1])) for p in (pos[2:].split("..") for pos in coords)] def read_file(filename: str = "input.txt") -> defa...
0.582966
0.519582
# DRF from rest_framework import serializers from rest_framework.validators import UniqueValidator # Models from root.Acme.models import Product, Category class ProductModelSerializer(serializers.ModelSerializer): """Acme products model serializer.""" class Meta: """Meta class""" model = P...
root/Acme/api/serializers/Product.py
# DRF from rest_framework import serializers from rest_framework.validators import UniqueValidator # Models from root.Acme.models import Product, Category class ProductModelSerializer(serializers.ModelSerializer): """Acme products model serializer.""" class Meta: """Meta class""" model = P...
0.772101
0.210097
import os import yaml import arxiv import smtplib, ssl from pathlib import Path from datetime import date today = date.today() def build_query(domains, keyword): query = '(' for i, domain in enumerate(domains): query += f'cat:{domain}' if i != len(domains) - 1: query += ' OR ' ...
run.py
import os import yaml import arxiv import smtplib, ssl from pathlib import Path from datetime import date today = date.today() def build_query(domains, keyword): query = '(' for i, domain in enumerate(domains): query += f'cat:{domain}' if i != len(domains) - 1: query += ' OR ' ...
0.259826
0.09645
import unicodedata import json import string import tensorflow as tf import tflearn from keras.utils import to_categorical import glob import os from encode import * import numpy as np import json all_letters = string.ascii_letters + " .,;'" n_letters = len(all_letters) n_class = 9 def findFiles(path): return glob.glo...
intentionClassifier/data.py
import unicodedata import json import string import tensorflow as tf import tflearn from keras.utils import to_categorical import glob import os from encode import * import numpy as np import json all_letters = string.ascii_letters + " .,;'" n_letters = len(all_letters) n_class = 9 def findFiles(path): return glob.glo...
0.339061
0.360067
import uuid from openstack import resource2 from openstack.tests.functional import base def auto_create_private_zone(conn, name, router_id, router_region): _zone = { "name": name, "description": "SDK unittest", "zone_type": "private", "email": "<EMAIL>", "ttl": 500, ...
openstack/tests/functional/dns/v2/test_zone.py
import uuid from openstack import resource2 from openstack.tests.functional import base def auto_create_private_zone(conn, name, router_id, router_region): _zone = { "name": name, "description": "SDK unittest", "zone_type": "private", "email": "<EMAIL>", "ttl": 500, ...
0.489992
0.266483
# Form implementation generated from reading ui file 'main2.ui' # # Created by: PyQt5 UI code generator 5.9.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName...
.archive/main2.py
# Form implementation generated from reading ui file 'main2.ui' # # Created by: PyQt5 UI code generator 5.9.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName...
0.410993
0.042226
import uuid import os import tempfile import decimal import datetime from multiprocessing import Process from ScannerResult import ScannerResult from CSVFileUtils import CSVFileUtil from MailSender import MailHelper from SynScannerUtil import SyncScannerUtil from loguru import logger from ConfigReader import...
src/Processor.py
import uuid import os import tempfile import decimal import datetime from multiprocessing import Process from ScannerResult import ScannerResult from CSVFileUtils import CSVFileUtil from MailSender import MailHelper from SynScannerUtil import SyncScannerUtil from loguru import logger from ConfigReader import...
0.099317
0.030329
from django.db import models from django.contrib.auth.models import User class AbstractPost(models.Model): """ The abstract model that defines the common fields for all subclasses """ text = models.TextField() created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(au...
web/models.py
from django.db import models from django.contrib.auth.models import User class AbstractPost(models.Model): """ The abstract model that defines the common fields for all subclasses """ text = models.TextField() created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(au...
0.5144
0.34065
import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import interp1d from podostemaceous.constants import u from podostemaceous.molecule import VSSMolecule from podostemaceous.fit_dsmc_vss import VSS_model_from_eta_and_D11 # borrowed from my lithium data package def eta1_Bouledroua_Table_I(TK): ...
examples/fit_VSS_model.py
import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import interp1d from podostemaceous.constants import u from podostemaceous.molecule import VSSMolecule from podostemaceous.fit_dsmc_vss import VSS_model_from_eta_and_D11 # borrowed from my lithium data package def eta1_Bouledroua_Table_I(TK): ...
0.83104
0.667866
from datetime import datetime from typing import Tuple, Optional, List import gssutils import pandas import re import requests from gssutils import Excel DATASET_URL = 'https://www.ons.gov.uk/businessindustryandtrade/internationaltrade/datasets/uktradeinservicesservicetypebypartnercountrynonseasonallyadjusted' def...
dataflow/ons_scripts/uk_trade_in_services_service_type_by_partner_country_non_seasonally_adjusted/main.py
from datetime import datetime from typing import Tuple, Optional, List import gssutils import pandas import re import requests from gssutils import Excel DATASET_URL = 'https://www.ons.gov.uk/businessindustryandtrade/internationaltrade/datasets/uktradeinservicesservicetypebypartnercountrynonseasonallyadjusted' def...
0.756807
0.372905
from tornado.escape import json_encode from .socket import SocketServer from .event import (SocketConnectEvent, SocketDisconnectEvent, SocketDataEvent) class EventServer(SocketServer): """Threaded WebSocket server for handling socket requests. Takes socket requests and queues SocketEvents...
__init__.py
from tornado.escape import json_encode from .socket import SocketServer from .event import (SocketConnectEvent, SocketDisconnectEvent, SocketDataEvent) class EventServer(SocketServer): """Threaded WebSocket server for handling socket requests. Takes socket requests and queues SocketEvents...
0.568056
0.059784
import csv import re import subprocess import urllib.parse as urllib import editdistance as levenshtein import numpy as np import tldextract as tld def hamming_distance(s1, s2): return len(list(filter(lambda x: ord(x[0]) ^ ord(x[1]), zip(s1, s2)))) def min_distances(url, N): """ Calculates the minimum ...
artefact/classifier/features_extractor.py
import csv import re import subprocess import urllib.parse as urllib import editdistance as levenshtein import numpy as np import tldextract as tld def hamming_distance(s1, s2): return len(list(filter(lambda x: ord(x[0]) ^ ord(x[1]), zip(s1, s2)))) def min_distances(url, N): """ Calculates the minimum ...
0.535098
0.478773
import numpy as np import matplotlib.pyplot as plt from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.patches import Rectangle def pixelated_text(dpi=100): fig = Figure(figsize=(1, 1), dpi=dpi) canvas, ax = FigureCanvasAgg(fig), fig.gca() ax.te...
code/anatomy/raster-vector.py
import numpy as np import matplotlib.pyplot as plt from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.patches import Rectangle def pixelated_text(dpi=100): fig = Figure(figsize=(1, 1), dpi=dpi) canvas, ax = FigureCanvasAgg(fig), fig.gca() ax.te...
0.719581
0.657387
import argparse import os import magic from pycti import OpenCTIApiClient API_URL = "API_URL_HERE" API_TOKEN = "API_TOKEN_HERE" # OpenCTI instantiation OPENCTI_API_CLIENT = OpenCTIApiClient(API_URL, API_TOKEN) def main(): parser = argparse.ArgumentParser() parser.add_argument( "-f", "--file", req...
examples/upload_artifacts.py
import argparse import os import magic from pycti import OpenCTIApiClient API_URL = "API_URL_HERE" API_TOKEN = "API_TOKEN_HERE" # OpenCTI instantiation OPENCTI_API_CLIENT = OpenCTIApiClient(API_URL, API_TOKEN) def main(): parser = argparse.ArgumentParser() parser.add_argument( "-f", "--file", req...
0.447219
0.103794
import os, shutil, json, time, datetime, thread, copy, atexit, collections, fcntl import logging, logging.config, logstash import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT from io import BlockingIOError from functools import wraps from flask import Flask, request, Response from flask_restful i...
scripts/globusmonitor/globus_monitor_service.py
import os, shutil, json, time, datetime, thread, copy, atexit, collections, fcntl import logging, logging.config, logstash import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT from io import BlockingIOError from functools import wraps from flask import Flask, request, Response from flask_restful i...
0.448185
0.09947
import argparse import json import textwrap import os import sys import shlex from botocore.exceptions import UnauthorizedSSOTokenError from botocore.session import Session __version__ = '0.5.0' DESCRIPTION ="""\ Get AWS credentials from a profile to inject into other programs. If you need credentials from AWS SSO...
aws_export_credentials/aws_export_credentials.py
import argparse import json import textwrap import os import sys import shlex from botocore.exceptions import UnauthorizedSSOTokenError from botocore.session import Session __version__ = '0.5.0' DESCRIPTION ="""\ Get AWS credentials from a profile to inject into other programs. If you need credentials from AWS SSO...
0.211498
0.076064
from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Explanation', fields=[ ('id', models.AutoField...
api/migrations/0001_initial.py
from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Explanation', fields=[ ('id', models.AutoField...
0.587115
0.205515