code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import os import time import requests from tweepy.parsers import JSONParser from tweepy.error import TweepError, RateLimitError, is_rate_limit_error_message from tweepy.models import Status MEDIA_ENDPOINT_URL = 'https://upload.twitter.com/1.1/media/upload.json' POST_TWEET_URL = 'https://api.twitter.com/1.1/statuses/...
docker/cpdpbot/cpdpbot/video_tweet.py
import os import time import requests from tweepy.parsers import JSONParser from tweepy.error import TweepError, RateLimitError, is_rate_limit_error_message from tweepy.models import Status MEDIA_ENDPOINT_URL = 'https://upload.twitter.com/1.1/media/upload.json' POST_TWEET_URL = 'https://api.twitter.com/1.1/statuses/...
0.282988
0.086787
from pyfiglet import Figlet f = Figlet(font='slant') print('Script Created by : ') print(f.renderText('gaurav')) sound = int(input("Do you want sound : 1 for yes , 2 for no : ")) sound = 0 if sound == 2 else 1 print('****************************************************') if sound : print("Sound is set to on ! \nOn...
script.py
from pyfiglet import Figlet f = Figlet(font='slant') print('Script Created by : ') print(f.renderText('gaurav')) sound = int(input("Do you want sound : 1 for yes , 2 for no : ")) sound = 0 if sound == 2 else 1 print('****************************************************') if sound : print("Sound is set to on ! \nOn...
0.257205
0.219118
from abc import ABC, abstractmethod import tensorflow as tf from cvnn import logger import sys from typing import Union from cvnn.layers import t_layers_shape class Optimizer(ABC): def __init__(self): pass def compile(self, shape: t_layers_shape) -> None: pass def optimize(self, variable...
cvnn/optimizers.py
from abc import ABC, abstractmethod import tensorflow as tf from cvnn import logger import sys from typing import Union from cvnn.layers import t_layers_shape class Optimizer(ABC): def __init__(self): pass def compile(self, shape: t_layers_shape) -> None: pass def optimize(self, variable...
0.834171
0.468243
from smbus2 import SMBus, i2c_msg _ADS1X15_DEFAULT_ADDRESS = 0x48 _ADS1X15_POINTER_CONVERSION = 0x00 _ADS1X15_POINTER_CONFIG = 0x01 _ADS1X15_CONFIG_OS_SINGLE = 0x8000 _ADS1X15_CONFIG_MUX_OFFSET = 12 _ADS1X15_CONFIG_COMP_QUE_DISABLE = 0x0003 _ADS1X15_CONFIG_GAIN = { 2 / 3: 0x0000, 1: 0x0200, 2: 0x0400, ...
components/ADC_LCD/ads1115/ads1x15.py
from smbus2 import SMBus, i2c_msg _ADS1X15_DEFAULT_ADDRESS = 0x48 _ADS1X15_POINTER_CONVERSION = 0x00 _ADS1X15_POINTER_CONFIG = 0x01 _ADS1X15_CONFIG_OS_SINGLE = 0x8000 _ADS1X15_CONFIG_MUX_OFFSET = 12 _ADS1X15_CONFIG_COMP_QUE_DISABLE = 0x0003 _ADS1X15_CONFIG_GAIN = { 2 / 3: 0x0000, 1: 0x0200, 2: 0x0400, ...
0.766031
0.36923
from urllib.parse import quote_plus from requests import get import os import globals token = os.environ['TOKEN'] url = f'https://api.telegram.org/bot{token}/' __all__ = [ 'chunks', 'copy_file_name', 'delete', 'download_file', 'escape_md', 'get_reply', 'send', 'send...
functions/utils.py
from urllib.parse import quote_plus from requests import get import os import globals token = os.environ['TOKEN'] url = f'https://api.telegram.org/bot{token}/' __all__ = [ 'chunks', 'copy_file_name', 'delete', 'download_file', 'escape_md', 'get_reply', 'send', 'send...
0.148417
0.073663
import numpy as np from scipy.linalg import pinv def distance_vec_rep_of_fibers(fi): '''This function calculates the distance of each point on the fiber fr m th first point Input: fi - a (n,3) np.ndarray of a single fiber. n is the number of points that represent the fiber Output: d...
clustering/poly_representaion_fibers.py
import numpy as np from scipy.linalg import pinv def distance_vec_rep_of_fibers(fi): '''This function calculates the distance of each point on the fiber fr m th first point Input: fi - a (n,3) np.ndarray of a single fiber. n is the number of points that represent the fiber Output: d...
0.822759
0.810329
import os from django.db import models from django.contrib.auth.models import User from ckeditor_uploader.fields import RichTextUploadingField from applications.alumniprofile.models import Profile from applications.events_news.models import Event from applications.gallery.models import Album def upload_photo(instance...
applications/chapter/models.py
import os from django.db import models from django.contrib.auth.models import User from ckeditor_uploader.fields import RichTextUploadingField from applications.alumniprofile.models import Profile from applications.events_news.models import Event from applications.gallery.models import Album def upload_photo(instance...
0.444806
0.113973
import os import torch import numpy as np from utils.datasets import DeepFashionDataset from torchvision.transforms import Compose from torchvision.transforms import Resize from torchvision.transforms import ToTensor from torchvision.transforms import Normalize from config.deep_fashion import DeepFashionConfig as cfg f...
plt_emb.py
import os import torch import numpy as np from utils.datasets import DeepFashionDataset from torchvision.transforms import Compose from torchvision.transforms import Resize from torchvision.transforms import ToTensor from torchvision.transforms import Normalize from config.deep_fashion import DeepFashionConfig as cfg f...
0.529507
0.54468
import importlib import json from typing import Dict, List, Optional import requests from pydantic import BaseSettings, Field, root_validator, validator from pydantic.types import Path DEFAULT_CONFIG_FILE_PATH = str(Path.home().joinpath(".emmet.json")) class EmmetSettings(BaseSettings): """ Settings for the...
emmet-core/emmet/core/settings.py
import importlib import json from typing import Dict, List, Optional import requests from pydantic import BaseSettings, Field, root_validator, validator from pydantic.types import Path DEFAULT_CONFIG_FILE_PATH = str(Path.home().joinpath(".emmet.json")) class EmmetSettings(BaseSettings): """ Settings for the...
0.797004
0.362997
import random import sys import multiprocessing from collections import namedtuple from wicked21st.graph import load_graph, Graph, save_graph, Cascades import graphviz DEBUG = False rand = random.Random(42) if len(sys.argv) > 1: graph_file = sys.argv[1] else: import config graph_file = config.GRAPH ...
graph_to_cascades.py
import random import sys import multiprocessing from collections import namedtuple from wicked21st.graph import load_graph, Graph, save_graph, Cascades import graphviz DEBUG = False rand = random.Random(42) if len(sys.argv) > 1: graph_file = sys.argv[1] else: import config graph_file = config.GRAPH ...
0.192388
0.291813
# template file: justice_py_sdk_codegen/__main__.py # justice-iam-service (5.10.1) # pylint: disable=duplicate-code # pylint: disable=line-too-long # pylint: disable=missing-function-docstring # pylint: disable=missing-module-docstring # pylint: disable=too-many-arguments # pylint: disable=too-many-branches # pylint...
accelbyte_py_sdk/ext/iam.py
# template file: justice_py_sdk_codegen/__main__.py # justice-iam-service (5.10.1) # pylint: disable=duplicate-code # pylint: disable=line-too-long # pylint: disable=missing-function-docstring # pylint: disable=missing-module-docstring # pylint: disable=too-many-arguments # pylint: disable=too-many-branches # pylint...
0.375248
0.039122
import os import gzip import logging import numpy as np import unidecode from transformers import AutoTokenizer from probing.data.base_data import BaseDataset, DataFields class WLSTMFields(DataFields): _fields = ( 'probe_target', 'label', 'probe_target_len', 'target_idx', 'raw_idx', 'raw_target...
probing/data/sentence_probe_data.py
import os import gzip import logging import numpy as np import unidecode from transformers import AutoTokenizer from probing.data.base_data import BaseDataset, DataFields class WLSTMFields(DataFields): _fields = ( 'probe_target', 'label', 'probe_target_len', 'target_idx', 'raw_idx', 'raw_target...
0.609524
0.121165
from os.path import abspath from os.path import dirname from os.path import join from glob import glob import subprocess from Bio import SeqIO from click.testing import CliRunner import click import pandas as pd import pytest from click_demultiplex import cli from click_demultiplex import commands ROOT = abspath(d...
tests/test_commands.py
from os.path import abspath from os.path import dirname from os.path import join from glob import glob import subprocess from Bio import SeqIO from click.testing import CliRunner import click import pandas as pd import pytest from click_demultiplex import cli from click_demultiplex import commands ROOT = abspath(d...
0.413596
0.372619
import argparse import numpy as np from data_loader import load_data from train import train np.random.seed(555) parser = argparse.ArgumentParser() # movie parser.add_argument('--dataset', type=str, default='movie', help='which dataset to use') parser.add_argument('--n_epochs', type=int, default=20, help='the numbe...
src/main.py
import argparse import numpy as np from data_loader import load_data from train import train np.random.seed(555) parser = argparse.ArgumentParser() # movie parser.add_argument('--dataset', type=str, default='movie', help='which dataset to use') parser.add_argument('--n_epochs', type=int, default=20, help='the numbe...
0.564939
0.099558
import unittest from actionlib.simple_action_client import SimpleActionClient import rospy from actionlib_msgs.msg import GoalStatus from std_msgs.msg import Int32 from std_srvs.srv import SetBool, SetBoolRequest, SetBoolResponse from actionlib_tutorials.msg import (FibonacciAction, FibonacciGoal, FibonacciResult, ...
ros_bt_py/test/rostest/test_ros_leaf_utility.py
import unittest from actionlib.simple_action_client import SimpleActionClient import rospy from actionlib_msgs.msg import GoalStatus from std_msgs.msg import Int32 from std_srvs.srv import SetBool, SetBoolRequest, SetBoolResponse from actionlib_tutorials.msg import (FibonacciAction, FibonacciGoal, FibonacciResult, ...
0.508788
0.249527
from dataclasses import dataclass, field from datetime import datetime from notion.client import NotionClient from notion.collection import CollectionView, CollectionRowBlock, NotionDate from utils import MetaSingleton from typing import Dict, List, Set import logging logger = logging.getLogger(__name__) def check_a...
nbot/clients/notion_db.py
from dataclasses import dataclass, field from datetime import datetime from notion.client import NotionClient from notion.collection import CollectionView, CollectionRowBlock, NotionDate from utils import MetaSingleton from typing import Dict, List, Set import logging logger = logging.getLogger(__name__) def check_a...
0.66769
0.100481
__author__ = "<NAME>" __maintainer__ = __author__ import cython import numpy as np from .general import AbstractDetector class FKMDetector(AbstractDetector): """Rainflow detector as described in FKM non linear. The algorithm has been published by Clormann & Seeger 1985 and has been cited heavily since...
src/pylife/stress/rainflow/fkm.py
__author__ = "<NAME>" __maintainer__ = __author__ import cython import numpy as np from .general import AbstractDetector class FKMDetector(AbstractDetector): """Rainflow detector as described in FKM non linear. The algorithm has been published by Clormann & Seeger 1985 and has been cited heavily since...
0.850748
0.421076
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Category', fields=[ ('category', models.CharField(max_leng...
studenthub/games/trivia/migrations/0001_initial.py
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Category', fields=[ ('category', models.CharField(max_leng...
0.61057
0.188511
import argparse import logging import numpy as np from cv2 import resize from lib.scene import Pose from lib.homography import getFrameFlattening, getFramePxlsInMeter import lib.conventions from lib.iterateScenes import iterateCamerasPoses def makePitchAndSizeMaps(camera_id, pose_id, dry_run=False): ''' Generates ...
shuffler/lib/scenes/MakePitchAndSizeMaps.py
import argparse import logging import numpy as np from cv2 import resize from lib.scene import Pose from lib.homography import getFrameFlattening, getFramePxlsInMeter import lib.conventions from lib.iterateScenes import iterateCamerasPoses def makePitchAndSizeMaps(camera_id, pose_id, dry_run=False): ''' Generates ...
0.620852
0.263762
import unittest import numpy as np import matplotlib.pyplot as plt import lmfit from pycqed.analysis.tools.plotting import SI_prefix_and_scale_factor from pycqed.analysis.tools.plotting import set_xlabel, set_ylabel from pycqed.analysis.tools.plotting import SI_val_to_msg_str from pycqed.analysis.tools.plotting import...
pycqed/tests/analysis/test_tools_plotting.py
import unittest import numpy as np import matplotlib.pyplot as plt import lmfit from pycqed.analysis.tools.plotting import SI_prefix_and_scale_factor from pycqed.analysis.tools.plotting import set_xlabel, set_ylabel from pycqed.analysis.tools.plotting import SI_val_to_msg_str from pycqed.analysis.tools.plotting import...
0.752104
0.529385
import time import praw __all__ = ['PrawOAuth2Mini'] REDIRECT_URL = 'http://127.0.0.1:9999/authorize_callback' SCOPES = ['identity', 'read'] EXPIRY_DURATION = 3500 class PrawOAuth2Mini: """ Creates a `PrawOAuth2Mini` instance. `PrawOAuth2Mini` meant to be used in the bot and it needs valid `access_to...
prawoauth2/PrawOAuth2Mini.py
import time import praw __all__ = ['PrawOAuth2Mini'] REDIRECT_URL = 'http://127.0.0.1:9999/authorize_callback' SCOPES = ['identity', 'read'] EXPIRY_DURATION = 3500 class PrawOAuth2Mini: """ Creates a `PrawOAuth2Mini` instance. `PrawOAuth2Mini` meant to be used in the bot and it needs valid `access_to...
0.63375
0.257187
import random class FewshotSampleBase: ''' Abstract Class DO NOT USE Build your own Sample class and inherit from this class ''' def __init__(self): self.class_count = {} def get_class_count(self): ''' return a dictionary of {class_name:count} in format {any : int} ...
src/fewnerd/fewnerd/util/fewshotsampler.py
import random class FewshotSampleBase: ''' Abstract Class DO NOT USE Build your own Sample class and inherit from this class ''' def __init__(self): self.class_count = {} def get_class_count(self): ''' return a dictionary of {class_name:count} in format {any : int} ...
0.68742
0.320901
import matplotlib.pyplot as plt import numpy as np from misc.ansi_color_codes import ACC def gen_plot(timeline, filename, title): if not isinstance(timeline, list): timeline = [timeline] plt.figure(10000) plt.clf() for i in range(len(timeline)): plt.plot(timeline[i]) plt.title(title) ...
misc/output.py
import matplotlib.pyplot as plt import numpy as np from misc.ansi_color_codes import ACC def gen_plot(timeline, filename, title): if not isinstance(timeline, list): timeline = [timeline] plt.figure(10000) plt.clf() for i in range(len(timeline)): plt.plot(timeline[i]) plt.title(title) ...
0.423458
0.447702
import os import shutil import subprocess print " " print "===============================" print "| Frostfall Release Builder |" print "| \/ |" print "| _\_\/\/_/_ |" print "| _\_\/_/_ |" print "| __/_/\_\__ |" print "| / /\/\ \ ...
Frostfall_BuildRelease.py
import os import shutil import subprocess print " " print "===============================" print "| Frostfall Release Builder |" print "| \/ |" print "| _\_\/\/_/_ |" print "| _\_\/_/_ |" print "| __/_/\_\__ |" print "| / /\/\ \ ...
0.096025
0.033812
import logging from makobot.utils import reaction_to_int logger = logging.getLogger(__name__) class Plugin(object): @property def enabled(self): """ REturns true if the plugin has been enabled or false if not. Typically this will check if the necessary environment variables are ...
makobot/plugins/base.py
import logging from makobot.utils import reaction_to_int logger = logging.getLogger(__name__) class Plugin(object): @property def enabled(self): """ REturns true if the plugin has been enabled or false if not. Typically this will check if the necessary environment variables are ...
0.550124
0.351172
import datetime from django.urls import reverse from systori.lib.testing import ClientTestCase from ..project.factories import ProjectFactory from .factories import JobFactory, GroupFactory, TaskFactory, LineItemFactory from .models import Task, Job, ProgressReport, ExpendReport from .views import JobCopy, JobPaste ...
systori/apps/task/test_views.py
import datetime from django.urls import reverse from systori.lib.testing import ClientTestCase from ..project.factories import ProjectFactory from .factories import JobFactory, GroupFactory, TaskFactory, LineItemFactory from .models import Task, Job, ProgressReport, ExpendReport from .views import JobCopy, JobPaste ...
0.427516
0.226891
#%% Imports import numpy as np from calib_main import calib_main from load_pickle import load_pickle #%% Version number version_num = 'V9' #%% data path directory = 'F:\\Arbeit und Uni\\MasterArbeit\\' # path to the pupil capture data data_directory = directory + 'Pupil_VR_Recordings\\' # path to the cali...
Calib_Tools/calib_start.py
#%% Imports import numpy as np from calib_main import calib_main from load_pickle import load_pickle #%% Version number version_num = 'V9' #%% data path directory = 'F:\\Arbeit und Uni\\MasterArbeit\\' # path to the pupil capture data data_directory = directory + 'Pupil_VR_Recordings\\' # path to the cali...
0.378804
0.171685
import sympy as sy import numpy as np from scipy.signal import cont2discrete class CostModel(object): def __init__(self, NX=None, NU=None): assert NX != None assert NU != None self.NX = NX self.NU = NU self.Lqq, self.Luu, self.Luq, \ self.Lq, self.Lu, self.L,\ ...
classic_gym/cost/__init__.py
import sympy as sy import numpy as np from scipy.signal import cont2discrete class CostModel(object): def __init__(self, NX=None, NU=None): assert NX != None assert NU != None self.NX = NX self.NU = NU self.Lqq, self.Luu, self.Luq, \ self.Lq, self.Lu, self.L,\ ...
0.628977
0.656878
"""Tests for the file-like object implementation using the SleuthKit (TSK).""" import os import unittest from dfvfs.file_io import tsk_file_io from dfvfs.lib import definitions from dfvfs.lib import errors from dfvfs.path import factory as path_spec_factory from dfvfs.resolver import context from tests.file_io impor...
tests/file_io/tsk_file_io.py
"""Tests for the file-like object implementation using the SleuthKit (TSK).""" import os import unittest from dfvfs.file_io import tsk_file_io from dfvfs.lib import definitions from dfvfs.lib import errors from dfvfs.path import factory as path_spec_factory from dfvfs.resolver import context from tests.file_io impor...
0.563858
0.344774
import numpy as np def normalize(np_values, _=None): mean = np.mean(np_values) normalized = np_values - int(mean) return normalized def subtract_min(np_values, _=None): minimum = np.min(np_values) result = np_values - int(minimum) return result def none(np_values, _=None): return np_v...
code/Backend/analysis-tool/preprocessing.py
import numpy as np def normalize(np_values, _=None): mean = np.mean(np_values) normalized = np_values - int(mean) return normalized def subtract_min(np_values, _=None): minimum = np.min(np_values) result = np_values - int(minimum) return result def none(np_values, _=None): return np_v...
0.463201
0.745445
from common import date_utils from datetime import datetime from collections import namedtuple import unittest Range = namedtuple('Range', ['start', 'end']) """ From root directory TeamUp: python3 -m test.test_date_utils """ class TestDaysOverlap(unittest.TestCase): def test_no_overlap(self): self.longMe...
test/test_date_utils.py
from common import date_utils from datetime import datetime from collections import namedtuple import unittest Range = namedtuple('Range', ['start', 'end']) """ From root directory TeamUp: python3 -m test.test_date_utils """ class TestDaysOverlap(unittest.TestCase): def test_no_overlap(self): self.longMe...
0.515132
0.703155
import logging import sys from os.path import dirname, realpath, isdir, isfile, join from abstract_data import abstract_info_list LOGGER = logging.getLogger(__name__) class AbstractHelp(object): def __init__(self, title, year, dataset_doi, desc_filename): self.title = title self.year = year ...
scripts/tabular_test_data/code/abstract_help.py
import logging import sys from os.path import dirname, realpath, isdir, isfile, join from abstract_data import abstract_info_list LOGGER = logging.getLogger(__name__) class AbstractHelp(object): def __init__(self, title, year, dataset_doi, desc_filename): self.title = title self.year = year ...
0.319865
0.233171
from sqlalchemy import Column, Integer, String from . import Base class Timetable(Base): """ Map class for table timetable. - **timetable_id**: Integer, primary_key. - **open_hour**: Integer, not null. - **open_minute**: Integer, not null. - **close_hour**: Integer, not nul...
alchemist_lib/database/timetable.py
from sqlalchemy import Column, Integer, String from . import Base class Timetable(Base): """ Map class for table timetable. - **timetable_id**: Integer, primary_key. - **open_hour**: Integer, not null. - **open_minute**: Integer, not null. - **close_hour**: Integer, not nul...
0.695855
0.15444
from typing import Dict, Optional from overrides import overrides import torch from allennlp.models.model import Model from allennlp.data import Vocabulary, TextFieldTensors from allennlp.training.metrics import Average, Auc from torch import Tensor from transformers import BertModel, BertForSequenceClassification ...
src/models/hatefulmememodel.py
from typing import Dict, Optional from overrides import overrides import torch from allennlp.models.model import Model from allennlp.data import Vocabulary, TextFieldTensors from allennlp.training.metrics import Average, Auc from torch import Tensor from transformers import BertModel, BertForSequenceClassification ...
0.952486
0.278373
import pandas as pd import numpy as np import json import os from sklearn.cluster import KMeans import matplotlib.pyplot as plt def kmeans_relevance(similarity_matrix): """ Using cosine similarities computes kmeans clustering :similarity_matrix: rows -> queries, columns -> document ids :r...
models/tf_idf2kmeans.py
import pandas as pd import numpy as np import json import os from sklearn.cluster import KMeans import matplotlib.pyplot as plt def kmeans_relevance(similarity_matrix): """ Using cosine similarities computes kmeans clustering :similarity_matrix: rows -> queries, columns -> document ids :r...
0.562417
0.607576
from div_free_interpolation import * from discrete_shell_potential import * import datetime import numpy as np import os from shape_utils import * from base_tools import * from param import * import matplotlib.pyplot as plt import scipy.io def np_to_torch(m, long=False): if long: return torch.as_tensor(m,...
interpolation/eval_interpolation.py
from div_free_interpolation import * from discrete_shell_potential import * import datetime import numpy as np import os from shape_utils import * from base_tools import * from param import * import matplotlib.pyplot as plt import scipy.io def np_to_torch(m, long=False): if long: return torch.as_tensor(m,...
0.34632
0.481088
from modules.whos_on_first_common import ButtonPosition SCREEN_TO_BUTTON_TO_READ = { "YES": ButtonPosition.middle_left, "FIRST": ButtonPosition.top_right, "DISPLAY": ButtonPosition.bottom_right, "OKAY": ButtonPosition.top_right, "SAYS": ButtonPosition.bottom_right, "NOTHING": ButtonPosition.mid...
src/modules/whos_on_first_solution.py
from modules.whos_on_first_common import ButtonPosition SCREEN_TO_BUTTON_TO_READ = { "YES": ButtonPosition.middle_left, "FIRST": ButtonPosition.top_right, "DISPLAY": ButtonPosition.bottom_right, "OKAY": ButtonPosition.top_right, "SAYS": ButtonPosition.bottom_right, "NOTHING": ButtonPosition.mid...
0.266166
0.435241
import os import numpy as np from gym import utils from gym.envs.mujoco import mujoco_env import xml.etree.ElementTree as et import mujoco_py class PusherEnv3DofEnv(mujoco_env.MujocoEnv, utils.EzPickle): def __init__(self, **kwargs): utils.EzPickle.__init__(self) self.reference_path = os.path.joi...
envs/pusher3dof.py
import os import numpy as np from gym import utils from gym.envs.mujoco import mujoco_env import xml.etree.ElementTree as et import mujoco_py class PusherEnv3DofEnv(mujoco_env.MujocoEnv, utils.EzPickle): def __init__(self, **kwargs): utils.EzPickle.__init__(self) self.reference_path = os.path.joi...
0.390243
0.239305
import pandas as pd from argparse import ArgumentParser import glob import shutil import os import uuid import random def main(target_folder, csv_path, out_folder, dry_run = False, train_test_split=0.8): filenames = glob.glob(os.path.join(target_folder, "*.jpg")) ids = [] ages = [] imagenos = [] ...
src/pseudonomize.py
import pandas as pd from argparse import ArgumentParser import glob import shutil import os import uuid import random def main(target_folder, csv_path, out_folder, dry_run = False, train_test_split=0.8): filenames = glob.glob(os.path.join(target_folder, "*.jpg")) ids = [] ages = [] imagenos = [] ...
0.228673
0.143818
from nonebot import on_command from nonebot.adapters import Bot from nonebot.adapters.cqhttp import GROUP, GroupMessageEvent, Message, MessageSegment from nonebot.typing import T_State from modules.user_info import UserInfo from utils.log import logger from .accident import random_accident from .data_source import * f...
plugins/russian_roulette/__init__.py
from nonebot import on_command from nonebot.adapters import Bot from nonebot.adapters.cqhttp import GROUP, GroupMessageEvent, Message, MessageSegment from nonebot.typing import T_State from modules.user_info import UserInfo from utils.log import logger from .accident import random_accident from .data_source import * f...
0.169337
0.148078
import gzip from diskcache import FanoutCache, Disk from diskcache.core import BytesType, MODE_BINARY, BytesIO from pathlib import Path from .logconf import logging log = logging.getLogger(__name__) log.setLevel(logging.WARN) log.setLevel(logging.INFO) log.setLevel(logging.DEBUG) # Cache Directory # Currently using ...
utils/disk.py
import gzip from diskcache import FanoutCache, Disk from diskcache.core import BytesType, MODE_BINARY, BytesIO from pathlib import Path from .logconf import logging log = logging.getLogger(__name__) log.setLevel(logging.WARN) log.setLevel(logging.INFO) log.setLevel(logging.DEBUG) # Cache Directory # Currently using ...
0.615781
0.216012
import argparse import json import os import pickle import sys import stanfordnlp from tqdm import tqdm from utils import ( WORD_MAP_FILENAME, decode_caption, get_caption_without_special_tokens, IMAGES_META_FILENAME, DATA_CAPTIONS, DATA_COCO_SPLIT, POS_TAGGED_CAPTIONS_FILENAME, ) # stanf...
data_preprocessing_utils/pos_tag_captions.py
import argparse import json import os import pickle import sys import stanfordnlp from tqdm import tqdm from utils import ( WORD_MAP_FILENAME, decode_caption, get_caption_without_special_tokens, IMAGES_META_FILENAME, DATA_CAPTIONS, DATA_COCO_SPLIT, POS_TAGGED_CAPTIONS_FILENAME, ) # stanf...
0.299003
0.12787
from functools import wraps import logging import types from selenium.common import exceptions as selenium_ex LOGGER = logging.getLogger(__name__) class FreshWebElement(object): """ Selenium WebElement proxy/wrapper watching over errors due to element staleness. """ __ATTEMPTS = 5 __STALE...
webstr/selenium/webelement.py
from functools import wraps import logging import types from selenium.common import exceptions as selenium_ex LOGGER = logging.getLogger(__name__) class FreshWebElement(object): """ Selenium WebElement proxy/wrapper watching over errors due to element staleness. """ __ATTEMPTS = 5 __STALE...
0.712732
0.085061
import ast import glob import os import re import shlex import shutil import signal import sys import termios import threading import tty from utils import _utils CUSTOM_DIC_PATH = "docs/common/custom_dic" HUNSPELL_CMD = [ "hunspell", "-a", # Pipe mode "-d", "en_GB", # Graphcore uses en_GB for doc...
scripts/check_spelling.py
import ast import glob import os import re import shlex import shutil import signal import sys import termios import threading import tty from utils import _utils CUSTOM_DIC_PATH = "docs/common/custom_dic" HUNSPELL_CMD = [ "hunspell", "-a", # Pipe mode "-d", "en_GB", # Graphcore uses en_GB for doc...
0.386416
0.14851
# GrovePi + Rotary Angle Sensor (Potentiometer) + LED # http://www.seeedstudio.com/wiki/Grove_-_Rotary_Angle_Sensor # http://www.seeedstudio.com/wiki/Grove_-_LED_Socket_Kit ''' The MIT License (MIT) GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi. Copyright (C) ...
02_iot-raspbian/04_button-led.py
# GrovePi + Rotary Angle Sensor (Potentiometer) + LED # http://www.seeedstudio.com/wiki/Grove_-_Rotary_Angle_Sensor # http://www.seeedstudio.com/wiki/Grove_-_LED_Socket_Kit ''' The MIT License (MIT) GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi. Copyright (C) ...
0.723212
0.298019
import datetime as dt import re from data import store as store from utils import ui _logger = ui.get_logger() class Option: def __init__(self, ticker: str, product: str, strike: str, expiry: dt.datetime): # Specified self.ticker = ticker self.product = product self.strike = stri...
options/option.py
import datetime as dt import re from data import store as store from utils import ui _logger = ui.get_logger() class Option: def __init__(self, ticker: str, product: str, strike: str, expiry: dt.datetime): # Specified self.ticker = ticker self.product = product self.strike = stri...
0.545286
0.20454
from collections import OrderedDict import tensorflow as tf from ..tfcompat import variables_initializer, global_variables __all__ = [ 'ensure_default_session', 'get_variable_values', 'get_variable_values_as_dict', 'get_uninitialized_variables', 'ensure_variables_initialized', ] def ensure_default_sess...
madoka/utils/tfhelper/session.py
from collections import OrderedDict import tensorflow as tf from ..tfcompat import variables_initializer, global_variables __all__ = [ 'ensure_default_session', 'get_variable_values', 'get_variable_values_as_dict', 'get_uninitialized_variables', 'ensure_variables_initialized', ] def ensure_default_sess...
0.891271
0.442034
from unittest.mock import mock_open, patch import pytest from satosa.metadata_creation.description import ContactPersonDesc, UIInfoDesc, OrganizationDesc, MetadataDescription class TestContactPersonDesc(object): def test_to_dict(self): desc = ContactPersonDesc() desc.contact_type = "test" ...
tests/satosa/metadata_creation/test_description.py
from unittest.mock import mock_open, patch import pytest from satosa.metadata_creation.description import ContactPersonDesc, UIInfoDesc, OrganizationDesc, MetadataDescription class TestContactPersonDesc(object): def test_to_dict(self): desc = ContactPersonDesc() desc.contact_type = "test" ...
0.627951
0.477798
import re from ..message_server import Message from ..util import app_logging log = app_logging.getLogger('Log Utils') code = re.compile('%CODE') class FlowModInfo(object): """ All we need to retrieve FlowMod from Database. """ def __init__(self, entry): dpid, flow_mod = entry self....
adapters/pox/ext/debugger/elt/logger/util.py
import re from ..message_server import Message from ..util import app_logging log = app_logging.getLogger('Log Utils') code = re.compile('%CODE') class FlowModInfo(object): """ All we need to retrieve FlowMod from Database. """ def __init__(self, entry): dpid, flow_mod = entry self....
0.506591
0.147955
from os import PathLike from pathlib import Path from typing import ( Any, Callable, Container, Dict, Iterable, List, Optional, Sequence, Tuple, TypeVar, Union, overload, ) import click import joblib import numpy as np import tqdm import yaml from sklearn.base import Ba...
ertk/utils.py
from os import PathLike from pathlib import Path from typing import ( Any, Callable, Container, Dict, Iterable, List, Optional, Sequence, Tuple, TypeVar, Union, overload, ) import click import joblib import numpy as np import tqdm import yaml from sklearn.base import Ba...
0.871448
0.32546
__doc__ = """ Script to use jellyfish to get kmer information Input: fasta/fastq file Output: kmer information, one of: 1. hash: binary hash of counts 2. stats: summary stats 3. dump: profile (kmer seq - count) 4. histo: histogram (count - abundance) 5. histo ranked: count, abundance, count*abundance, reverse...
scripts/kmer-tool.py
__doc__ = """ Script to use jellyfish to get kmer information Input: fasta/fastq file Output: kmer information, one of: 1. hash: binary hash of counts 2. stats: summary stats 3. dump: profile (kmer seq - count) 4. histo: histogram (count - abundance) 5. histo ranked: count, abundance, count*abundance, reverse...
0.282295
0.211539
# instead of using yearly performance (return and volatility) # use monthly data import numpy as np import pandas as pd from pandas_datareader import data as wb import matplotlib.pyplot as plt # matplotlib inline import scipy.optimize as sco # load data for portfolio mixed_tickers = [] with open('./data/mixed_portf...
stock_selection/optimization.py
# instead of using yearly performance (return and volatility) # use monthly data import numpy as np import pandas as pd from pandas_datareader import data as wb import matplotlib.pyplot as plt # matplotlib inline import scipy.optimize as sco # load data for portfolio mixed_tickers = [] with open('./data/mixed_portf...
0.709925
0.680507
import requests from bs4 import BeautifulSoup import datetime import pandas as pd URL = "http://www1.river.go.jp" DAT_HEAD_ROWS = 9 class _DataPage(object): def __init__(self): self._url_base = "" self._kind = 1 self.begin_date = "" self.end_date = "" self.s...
mlit/data_page.py
import requests from bs4 import BeautifulSoup import datetime import pandas as pd URL = "http://www1.river.go.jp" DAT_HEAD_ROWS = 9 class _DataPage(object): def __init__(self): self._url_base = "" self._kind = 1 self.begin_date = "" self.end_date = "" self.s...
0.245356
0.071819
u""" compute_tide_corrections.py Written by <NAME> (09/2021) Calculates tidal elevations for correcting elevation or imagery data Uses OTIS format tidal solutions provided by Ohio State University and ESR http://volkov.oce.orst.edu/tides/region.html https://www.esr.org/research/polar-tide-models/list-of-polar-...
pyTMD/compute_tide_corrections.py
u""" compute_tide_corrections.py Written by <NAME> (09/2021) Calculates tidal elevations for correcting elevation or imagery data Uses OTIS format tidal solutions provided by Ohio State University and ESR http://volkov.oce.orst.edu/tides/region.html https://www.esr.org/research/polar-tide-models/list-of-polar-...
0.865764
0.748881
from django import test from django.shortcuts import resolve_url from django.test import TestCase from django.test.utils import override_settings from mock import patch from django_opt_out.models import OptOut from django_opt_out.plugins.sparkpost import send_email, signals from .test_views import CaptureSignal clas...
tests/test_sparkpost.py
from django import test from django.shortcuts import resolve_url from django.test import TestCase from django.test.utils import override_settings from mock import patch from django_opt_out.models import OptOut from django_opt_out.plugins.sparkpost import send_email, signals from .test_views import CaptureSignal clas...
0.448909
0.161122
import design import debug from tech import drc, info from vector import vector import contact from ptx import ptx from globals import OPTS class single_level_column_mux(design.design): """ This module implements the columnmux bitline cell used in the design. Creates a single columnmux cell. """ d...
compiler/modules/single_level_column_mux.py
import design import debug from tech import drc, info from vector import vector import contact from ptx import ptx from globals import OPTS class single_level_column_mux(design.design): """ This module implements the columnmux bitline cell used in the design. Creates a single columnmux cell. """ d...
0.489015
0.2243
import os import tensorflow as tf from keras import backend as K from keras import metrics from keras.callbacks import TensorBoard from keras.layers import Conv2D, MaxPooling2D, UpSampling2D from keras.models import Sequential from keras.optimizers import Adadelta from keras.preprocessing.image import ImageDataGenerat...
model/autoencoder.py
import os import tensorflow as tf from keras import backend as K from keras import metrics from keras.callbacks import TensorBoard from keras.layers import Conv2D, MaxPooling2D, UpSampling2D from keras.models import Sequential from keras.optimizers import Adadelta from keras.preprocessing.image import ImageDataGenerat...
0.787482
0.505981
import unittest from ie.isde import ComplexTypes, ISDEDatasetMetadata, RDFNamespaces class ISDETools(unittest.TestCase): _ie_marine_data__dataset_1000 = r"https://irishspatialdataexchange.blob.core.windows.net/metadata/xml/ie_marine_data__dataset_1000.xml" _ie_nbdc_dataset_BioMar = r"http://www.isde.ie/geon...
test.py
import unittest from ie.isde import ComplexTypes, ISDEDatasetMetadata, RDFNamespaces class ISDETools(unittest.TestCase): _ie_marine_data__dataset_1000 = r"https://irishspatialdataexchange.blob.core.windows.net/metadata/xml/ie_marine_data__dataset_1000.xml" _ie_nbdc_dataset_BioMar = r"http://www.isde.ie/geon...
0.645455
0.453746
from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateModel( name...
users/migrations/0001_initial.py
from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateModel( name...
0.523908
0.167559
from .response import Response from ..simplates import Simplate, SimplateDefaults, SimplateException class Static(object): """Model a static HTTP resource. """ def __init__(self, website, fspath, raw, media_type): self.website = website self.raw = raw self.media_type = media_type ...
aspen/http/resource.py
from .response import Response from ..simplates import Simplate, SimplateDefaults, SimplateException class Static(object): """Model a static HTTP resource. """ def __init__(self, website, fspath, raw, media_type): self.website = website self.raw = raw self.media_type = media_type ...
0.480235
0.113187
from easyai.base_name.model_name import ModelName from easyai.base_name.backbone_name import BackboneName from easyai.base_name.block_name import NormalizationType, ActivationType from easyai.base_name.block_name import LayerType, BlockType from easyai.base_name.loss_name import LossType from easyai.loss.utility.cross_...
easyai/model/seg/pspnet_seg.py
from easyai.base_name.model_name import ModelName from easyai.base_name.backbone_name import BackboneName from easyai.base_name.block_name import NormalizationType, ActivationType from easyai.base_name.block_name import LayerType, BlockType from easyai.base_name.loss_name import LossType from easyai.loss.utility.cross_...
0.864425
0.191517
import datetime from dateutil.relativedelta import relativedelta from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from MESAeveryday import login_manager, app, bcrypt from flask_login import UserMixin from flask import flash import os from sqlalchemy import Column, Integer, String, create_engine, F...
MESAeveryday/models.py
import datetime from dateutil.relativedelta import relativedelta from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from MESAeveryday import login_manager, app, bcrypt from flask_login import UserMixin from flask import flash import os from sqlalchemy import Column, Integer, String, create_engine, F...
0.386416
0.121869
__author__ = 'mnowotka' #----------------------------------------------------------------------------------------------------------------------- from chembl_beaker.beaker import app from bottle import request from chembl_beaker.beaker.core_apps.conversions.impl import _ctab2smiles, _smiles2ctab, _inchi2ctab, _ctab2sm...
chembl_beaker/beaker/core_apps/conversions/views.py
__author__ = 'mnowotka' #----------------------------------------------------------------------------------------------------------------------- from chembl_beaker.beaker import app from bottle import request from chembl_beaker.beaker.core_apps.conversions.impl import _ctab2smiles, _smiles2ctab, _inchi2ctab, _ctab2sm...
0.47098
0.104249
import os from unittest import TestCase import pandas as pd import plotly.graph_objects as go from pandas.testing import assert_frame_equal from moonstone.parsers.metadata import MetadataParser, YAMLBasedMetadataParser class TestMetadataParser(TestCase): def setUp(self): self.metadata_file = os.path.joi...
tests/parsers/test_metadata.py
import os from unittest import TestCase import pandas as pd import plotly.graph_objects as go from pandas.testing import assert_frame_equal from moonstone.parsers.metadata import MetadataParser, YAMLBasedMetadataParser class TestMetadataParser(TestCase): def setUp(self): self.metadata_file = os.path.joi...
0.605099
0.439326
from urllib import parse from celery import shared_task, states from celery.canvas import group from django.conf import settings from django.db import transaction from extras.tasks import CurrentUserTaskMixin from registry.models import CatalougeService, WebFeatureService, WebMapService from registry.models.metadata i...
backend/registry/tasks/service.py
from urllib import parse from celery import shared_task, states from celery.canvas import group from django.conf import settings from django.db import transaction from extras.tasks import CurrentUserTaskMixin from registry.models import CatalougeService, WebFeatureService, WebMapService from registry.models.metadata i...
0.34632
0.086362
import os import numpy as np import cobra from enzyme import enzyme from warnings import filterwarnings class TestFBAModel: def setup_class(self): modelPath='../data/external/yeast_7.6/yeast_7.6.xml' filterwarnings('ignore', 'charge of s_[0-9][0-9][0-9][0-9] is not a number ()') filterwarn...
flux_balance_analysis/test_code.py
import os import numpy as np import cobra from enzyme import enzyme from warnings import filterwarnings class TestFBAModel: def setup_class(self): modelPath='../data/external/yeast_7.6/yeast_7.6.xml' filterwarnings('ignore', 'charge of s_[0-9][0-9][0-9][0-9] is not a number ()') filterwarn...
0.505615
0.423518
import sys import regex as re __author__ = '<NAME>' __license__ = 'MIT License' __version__ = '1.0.0' __status__ = '4 - Beta Development' class MultiRegex(object): simple = False regexes = () def __init__(self): try: self._rx = re.compile('|'.join(self.regexes), flag...
nielsenTools/multiregex.py
import sys import regex as re __author__ = '<NAME>' __license__ = 'MIT License' __version__ = '1.0.0' __status__ = '4 - Beta Development' class MultiRegex(object): simple = False regexes = () def __init__(self): try: self._rx = re.compile('|'.join(self.regexes), flag...
0.154058
0.405213
from cgitb import text from cloudant import Cloudant from flask import Flask, render_template, request, jsonify, url_for, redirect import atexit import os import json import xml.etree.ElementTree as ET tree = ET.parse('catalog.xml') root = tree.getroot() app = Flask(__name__, static_url_path='') db_name = 'mydb' cl...
hello.py
from cgitb import text from cloudant import Cloudant from flask import Flask, render_template, request, jsonify, url_for, redirect import atexit import os import json import xml.etree.ElementTree as ET tree = ET.parse('catalog.xml') root = tree.getroot() app = Flask(__name__, static_url_path='') db_name = 'mydb' cl...
0.322526
0.046486
import argparse import json import numpy as np import os # manually selected list benchs_list = { "raw": ["cartpolereduced", "BNNOnProteinStructure", "BNNOnYearPrediction"], "surro": ["ParamNetReducedAdultOnTimeBenchmark", "ParamNetReducedHiggsOnTimeBenchmark", "ParamNetReducedLetterOnTimeBenchmark", "ParamNetRed...
scripts/get_runtime.py
import argparse import json import numpy as np import os # manually selected list benchs_list = { "raw": ["cartpolereduced", "BNNOnProteinStructure", "BNNOnYearPrediction"], "surro": ["ParamNetReducedAdultOnTimeBenchmark", "ParamNetReducedHiggsOnTimeBenchmark", "ParamNetReducedLetterOnTimeBenchmark", "ParamNetRed...
0.233357
0.230205
import re import requests import logging from copy import deepcopy from typing import List, Dict from logging import Logger from datetime import timedelta, datetime import fbchat from fbchat import Client, User, Message, Mention, ThreadType class Reporter(Client): debug: bool logger: Logger maxage: time...
veritaserum/reporter.py
import re import requests import logging from copy import deepcopy from typing import List, Dict from logging import Logger from datetime import timedelta, datetime import fbchat from fbchat import Client, User, Message, Mention, ThreadType class Reporter(Client): debug: bool logger: Logger maxage: time...
0.610221
0.072505
from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('core', '0001_initial'), ] operations = [ migrations.CreateModel( ...
ecs/meetings/migrations/0001_initial.py
from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('core', '0001_initial'), ] operations = [ migrations.CreateModel( ...
0.560373
0.184768
from .base import Base from utilities import authenticate import requests import datetime class reservations(Base): """Make 'get reservations' function calls to Teem with parameters passed via CLI""" Rooms = { 'showcase': 130700, 'pistachio': 218764, 'almond': 218763, '2...
teem/commands/reservations.py
from .base import Base from utilities import authenticate import requests import datetime class reservations(Base): """Make 'get reservations' function calls to Teem with parameters passed via CLI""" Rooms = { 'showcase': 130700, 'pistachio': 218764, 'almond': 218763, '2...
0.330471
0.112065
from django import forms from django.utils.translation import gettext_lazy as _ from .base import ChangeSettingsForm class ChangeThreadsSettingsForm(ChangeSettingsForm): settings = [ "attachment_403_image", "attachment_404_image", "daily_post_limit", "hourly_post_limit", "...
misago/misago/conf/admin/forms/threads.py
from django import forms from django.utils.translation import gettext_lazy as _ from .base import ChangeSettingsForm class ChangeThreadsSettingsForm(ChangeSettingsForm): settings = [ "attachment_403_image", "attachment_404_image", "daily_post_limit", "hourly_post_limit", "...
0.602997
0.118793
import sys from socket import * import threading import time import datetime as dt # The argument of client servername = sys.argv[1] serverPort = sys.argv[2] udpPort = sys.argv[3] serverPort = int(serverPort) # Create the TCP socket clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((serve...
code/testclient.py
import sys from socket import * import threading import time import datetime as dt # The argument of client servername = sys.argv[1] serverPort = sys.argv[2] udpPort = sys.argv[3] serverPort = int(serverPort) # Create the TCP socket clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((serve...
0.126515
0.050518
import numpy as np import cv2 import glob import pickle import matplotlib.pyplot as plt import matplotlib.image as mpimg # Class that holds both the left and right line tracking data class tracker(): # Constructor? def __init__(self, Mywindow_width, Mywindow_height, Mymargin, My_ym = ...
tracker.py
import numpy as np import cv2 import glob import pickle import matplotlib.pyplot as plt import matplotlib.image as mpimg # Class that holds both the left and right line tracking data class tracker(): # Constructor? def __init__(self, Mywindow_width, Mywindow_height, Mymargin, My_ym = ...
0.678647
0.339663
import os import time import typing import typer from hrflow_importer.importer.worker import send_batch_to_hrflow from hrflow_importer.utils.config.config import config #TODO improve module naming for import from hrflow import Hrflow PIPELINES_LOGS_FILE = "{}/importer_logs.txt".format(config.STORAGE_DIRECTORY_PATH) ...
src/hrflow_importer/import_cli.py
import os import time import typing import typer from hrflow_importer.importer.worker import send_batch_to_hrflow from hrflow_importer.utils.config.config import config #TODO improve module naming for import from hrflow import Hrflow PIPELINES_LOGS_FILE = "{}/importer_logs.txt".format(config.STORAGE_DIRECTORY_PATH) ...
0.215598
0.169681
import torch import torch.nn as nn import torch.nn.functional as F def logsumexp_2d(tensor): tensor_flatten = tensor.view(tensor.size(0), tensor.size(1), -1) s, _ = torch.max(tensor_flatten, dim=2, keepdim=True) outputs = s + (tensor_flatten - s).exp().sum(dim=2, keepdim=True).log() return outputs d...
ibug/age_estimation/module.py
import torch import torch.nn as nn import torch.nn.functional as F def logsumexp_2d(tensor): tensor_flatten = tensor.view(tensor.size(0), tensor.size(1), -1) s, _ = torch.max(tensor_flatten, dim=2, keepdim=True) outputs = s + (tensor_flatten - s).exp().sum(dim=2, keepdim=True).log() return outputs d...
0.935553
0.696479
import unittest def interleavedp(begins,ends,m=None) : if( len(begins) != len(ends) ) : print 'begin-end token number mismatch' # Should learn to throw... return False if m : if len(m) > len(begins) : print 'excess else tokens' return False ok...
components/elm/src/external_models/sbetr/3rd-party/pfunit/bin/mods/pre/interleavedp.py
import unittest def interleavedp(begins,ends,m=None) : if( len(begins) != len(ends) ) : print 'begin-end token number mismatch' # Should learn to throw... return False if m : if len(m) > len(begins) : print 'excess else tokens' return False ok...
0.276105
0.524395
from __future__ import absolute_import from __future__ import division from __future__ import print_function import unittest import numpy as np import tensorflow as tf import gym from easy_rl.agents import agents from easy_rl.models import DQNModel from easy_rl.utils.window_stat import WindowStat from easy_rl.models ...
tests/test_convergence.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import unittest import numpy as np import tensorflow as tf import gym from easy_rl.agents import agents from easy_rl.models import DQNModel from easy_rl.utils.window_stat import WindowStat from easy_rl.models ...
0.741674
0.18462
from typing import List, Optional, Union import pyinflect # noqa: F401 import spacy from nltk.tokenize.treebank import TreebankWordDetokenizer from spacy.symbols import AUX, NOUN, PRON, PROPN, VERB, aux, cc, nsubj from spacy.tokens import Span, Token from spacy.tokens.doc import Doc from initialize import spacy_nlp ...
transformations/yes_no_question/transformation.py
from typing import List, Optional, Union import pyinflect # noqa: F401 import spacy from nltk.tokenize.treebank import TreebankWordDetokenizer from spacy.symbols import AUX, NOUN, PRON, PROPN, VERB, aux, cc, nsubj from spacy.tokens import Span, Token from spacy.tokens.doc import Doc from initialize import spacy_nlp ...
0.875242
0.283949
import numpy as np import matplotlib.pyplot as plt # importing the numpy & matplot libraries to help manipulate the data, and giving them shorthand names # Alternately I could import these into iPython while testing. Remember I'm working on a multivariate dataset data = np.genfromtxt('Data/Iris.csv', delimiter...
NumpyData.py
import numpy as np import matplotlib.pyplot as plt # importing the numpy & matplot libraries to help manipulate the data, and giving them shorthand names # Alternately I could import these into iPython while testing. Remember I'm working on a multivariate dataset data = np.genfromtxt('Data/Iris.csv', delimiter...
0.410402
0.614857
from pubnub import utils from pubnub.endpoints.endpoint import Endpoint from pubnub.enums import HttpMethod, PNOperationType from pubnub.exceptions import PubNubException from pubnub.models.consumer.message_count import PNMessageCountResult class MessageCount(Endpoint): MESSAGE_COUNT_PATH = '/v3/history/sub-key/%...
pubnub/endpoints/message_count.py
from pubnub import utils from pubnub.endpoints.endpoint import Endpoint from pubnub.enums import HttpMethod, PNOperationType from pubnub.exceptions import PubNubException from pubnub.models.consumer.message_count import PNMessageCountResult class MessageCount(Endpoint): MESSAGE_COUNT_PATH = '/v3/history/sub-key/%...
0.622574
0.077343
import torch from torch import nn from torch.nn import functional as F from torch_geometric.nn import MessagePassing, global_mean_pool from torch_geometric.utils import degree, dense_to_sparse from torch_geometric.nn import ECConv from torch_scatter import scatter_add def _make_block_diag(mats, mat_sizes): block_d...
MolRep/Models/graph_based/ECC.py
import torch from torch import nn from torch.nn import functional as F from torch_geometric.nn import MessagePassing, global_mean_pool from torch_geometric.utils import degree, dense_to_sparse from torch_geometric.nn import ECConv from torch_scatter import scatter_add def _make_block_diag(mats, mat_sizes): block_d...
0.866175
0.559771
"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_databa...
terra_sdk/protobuf/ibc/core/types/v1/genesis_pb2.py
"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_databa...
0.329715
0.070336
__author__ = '<NAME>' __email__ = '<EMAIL>' __status__ = 'Development' __license__ = 'Apache 2.0' import wx import massoc from massoc.scripts.main import resource_path from wx.lib.pubsub import pub from massoc.GUI.intro import IntroPanel from massoc.GUI.input import InputPanel from massoc.GUI.process import ProcessPan...
massocGUI.py
__author__ = '<NAME>' __email__ = '<EMAIL>' __status__ = 'Development' __license__ = 'Apache 2.0' import wx import massoc from massoc.scripts.main import resource_path from wx.lib.pubsub import pub from massoc.GUI.intro import IntroPanel from massoc.GUI.input import InputPanel from massoc.GUI.process import ProcessPan...
0.422505
0.168309
from typing import Dict from python import DOCUMENT_ID, TOPIC_ID from python.handwritten_baseline.pipeline.data.base import Dataset, BaselineDataProcessorStage class DataReducerStage(BaselineDataProcessorStage): def __init__(self, pos, config, config_global, logger): super(DataReducerStage, self).__init...
python/handwritten_baseline/pipeline/data/processing/reducer.py
from typing import Dict from python import DOCUMENT_ID, TOPIC_ID from python.handwritten_baseline.pipeline.data.base import Dataset, BaselineDataProcessorStage class DataReducerStage(BaselineDataProcessorStage): def __init__(self, pos, config, config_global, logger): super(DataReducerStage, self).__init...
0.661923
0.480844
from .models import MovieNightEvent, Movie, UserAttendence, LocationPermission from rest_framework import serializers from django.utils import timezone from django.contrib.auth.models import User from .utils import badgify import pytz def strfdelta(tdelta, fmt): d = {"days": abs(tdelta.days)} d["hours"], re...
userhandling/serializers.py
from .models import MovieNightEvent, Movie, UserAttendence, LocationPermission from rest_framework import serializers from django.utils import timezone from django.contrib.auth.models import User from .utils import badgify import pytz def strfdelta(tdelta, fmt): d = {"days": abs(tdelta.days)} d["hours"], re...
0.456894
0.165088
import tensorflow as tf import cv2 import matplotlib.pyplot as plt import numpy as np def gradient_penalty_loss(averaged_output, x_hat): gradients = tf.gradients(averaged_output, x_hat)[0] gradients_sqr = tf.square(gradients) gradients_sqr_sum = tf.reduce_sum(gradients_sqr, axis=np.arange(1, len(gradients...
stargan/utils.py
import tensorflow as tf import cv2 import matplotlib.pyplot as plt import numpy as np def gradient_penalty_loss(averaged_output, x_hat): gradients = tf.gradients(averaged_output, x_hat)[0] gradients_sqr = tf.square(gradients) gradients_sqr_sum = tf.reduce_sum(gradients_sqr, axis=np.arange(1, len(gradients...
0.72331
0.533641
import xmlrpclib from threading import Thread from SimpleXMLRPCServer import SimpleXMLRPCServer config = {} def initialize(): global ccu_url, _gateway_is_connected ccu_ip = config["ccu_ip"] ccu_port = config["ccu_port"] ccu_url = "http://{ip}:{port}".format(ip=ccu_ip, port=ccu_port) _gateway_is...
wirehome.services.homematic.ccu/1.0.0/script.py
import xmlrpclib from threading import Thread from SimpleXMLRPCServer import SimpleXMLRPCServer config = {} def initialize(): global ccu_url, _gateway_is_connected ccu_ip = config["ccu_ip"] ccu_port = config["ccu_port"] ccu_url = "http://{ip}:{port}".format(ip=ccu_ip, port=ccu_port) _gateway_is...
0.485844
0.095771
import torndb import logging import json import environment COMPANY_SERVICE =\ torndb.Connection( 'mysql', 'company_service', user=environment.get_user(), password=<PASSWORD>(), ) def release(): COMPANY_SERVICE.close() class Crawler(object): ''' 爬虫的持久化对象 ''...
database.py
import torndb import logging import json import environment COMPANY_SERVICE =\ torndb.Connection( 'mysql', 'company_service', user=environment.get_user(), password=<PASSWORD>(), ) def release(): COMPANY_SERVICE.close() class Crawler(object): ''' 爬虫的持久化对象 ''...
0.285671
0.074905
import textwrap from exceptions import Error class TextTable(object): def __init__(self, field_names, **kwargs): ''' Arguments: field_names - list or tuple of field names vertical_str - vertical separator betwwen each columns ''' self._field_names = field_names ...
src/texttable.py
import textwrap from exceptions import Error class TextTable(object): def __init__(self, field_names, **kwargs): ''' Arguments: field_names - list or tuple of field names vertical_str - vertical separator betwwen each columns ''' self._field_names = field_names ...
0.568655
0.23292
from __future__ import print_function from __future__ import absolute_import from past.builtins import basestring import os import shutil import sys import time class OutputWrangler: """ This is used in place of an output file when forking to trivially parallelize computations. For example, if you hav...
python/util/fork.py
from __future__ import print_function from __future__ import absolute_import from past.builtins import basestring import os import shutil import sys import time class OutputWrangler: """ This is used in place of an output file when forking to trivially parallelize computations. For example, if you hav...
0.338186
0.165357
import tensorflow as tf from MemoryNetwork import MemoryNetwork import babi_dataset_utils as bb import os import numpy as np import matplotlib.pyplot as plt import sys import errno flags = tf.app.flags # dataset configs flags.DEFINE_string("dataset_selector", "babi", "dataset selector: 'babi' or 'penn' [babi]") flags...
main.py
import tensorflow as tf from MemoryNetwork import MemoryNetwork import babi_dataset_utils as bb import os import numpy as np import matplotlib.pyplot as plt import sys import errno flags = tf.app.flags # dataset configs flags.DEFINE_string("dataset_selector", "babi", "dataset selector: 'babi' or 'penn' [babi]") flags...
0.470493
0.259088
class StatementsRouter: route_app_labels = {'auth', 'contenttypes', 'session', 'admin', 'statements'} def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return...
mysite/routers/db_routers.py
class StatementsRouter: route_app_labels = {'auth', 'contenttypes', 'session', 'admin', 'statements'} def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return...
0.489015
0.154983
from keystoneauth1 import adapter import mock from openstack.tests.unit import base from otcextensions.sdk import sdk_resource # Only a basic tests for extended functionality are implemented since # the _list code is copied from sdk.resource to override headers # TODO(agoncharov) make sense to implement (copy) exis...
otcextensions/tests/unit/sdk/test_sdk_resource.py
from keystoneauth1 import adapter import mock from openstack.tests.unit import base from otcextensions.sdk import sdk_resource # Only a basic tests for extended functionality are implemented since # the _list code is copied from sdk.resource to override headers # TODO(agoncharov) make sense to implement (copy) exis...
0.35031
0.247669
class Terminal: def __init__(self, estimates, regcoeffs): self._estimates = estimates self._regcoeffs = regcoeffs def Process(self, entity): entity.time_Sysp = entity.allTime # Entities receiving no treatment OR palliative treatment (for recurrence)...
Code/SysP_Terminal.py
class Terminal: def __init__(self, estimates, regcoeffs): self._estimates = estimates self._regcoeffs = regcoeffs def Process(self, entity): entity.time_Sysp = entity.allTime # Entities receiving no treatment OR palliative treatment (for recurrence)...
0.541409
0.294114
import time import rospy import rospkg import os import sys import numpy as np import tensorflow as tf from styx_msgs.msg import TrafficLight from io import StringIO MINIMUM_CONFIDENCE = 0.4 class TLClassifier(object): def __init__(self, simulator): # current_path = os.path.dirname(os.path.realpath(__fi...
ros/src/tl_detector/light_classification/tl_classifier.py
import time import rospy import rospkg import os import sys import numpy as np import tensorflow as tf from styx_msgs.msg import TrafficLight from io import StringIO MINIMUM_CONFIDENCE = 0.4 class TLClassifier(object): def __init__(self, simulator): # current_path = os.path.dirname(os.path.realpath(__fi...
0.704668
0.357147
import functools from typing import Optional from absl import logging from growneuron.imagenet import data_util import tensorflow.compat.v2 as tf import tensorflow_datasets as tfds def build_input_fn( builder, global_batch_size, topology, is_training, image_size = 224): """Build input function....
growneuron/imagenet/data.py
import functools from typing import Optional from absl import logging from growneuron.imagenet import data_util import tensorflow.compat.v2 as tf import tensorflow_datasets as tfds def build_input_fn( builder, global_batch_size, topology, is_training, image_size = 224): """Build input function....
0.938513
0.454714
import pandas as pd pd.options.mode.chained_assignment = None from datetime import datetime #Carga de datos Regions = ["WYJ", "YVR"] WeatherData = {} HouseFeatures = pd.DataFrame() HouseData = pd.DataFrame() #Cargar Caracacteristicas de casa with open(r"Data/HouseHold/Features.csv") as file: HouseFeatures = pd.re...
FormatDataConsumption.py
import pandas as pd pd.options.mode.chained_assignment = None from datetime import datetime #Carga de datos Regions = ["WYJ", "YVR"] WeatherData = {} HouseFeatures = pd.DataFrame() HouseData = pd.DataFrame() #Cargar Caracacteristicas de casa with open(r"Data/HouseHold/Features.csv") as file: HouseFeatures = pd.re...
0.210198
0.216529
# Built-ins import os import warnings import datetime import threading # Package import __init__ from elf import utils from elf.webio import get_soup from elf.webio import download_page from elf.parsing import parsetable warnings.warn('EDGAR search-by-text can only search 3 years back. Use alternative downloader if...
search_by_text.py
# Built-ins import os import warnings import datetime import threading # Package import __init__ from elf import utils from elf.webio import get_soup from elf.webio import download_page from elf.parsing import parsetable warnings.warn('EDGAR search-by-text can only search 3 years back. Use alternative downloader if...
0.286768
0.371593