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 requests # pip install requests import json import execjs # pip install PyExecJS import urllib3 # pip install urllib3 ''' author by Benji date at 2018.12.07 实现: 模拟浏览器中Google翻译的url请求 不同于Baidu直接给出API, Google翻译需要调用其封装的lib 参考: https://www.jianshu.com/p/95cf6e73d6ee https://cloud.google.com/trans...
Python/Exercise/Exercise_2018/Translate/googleTranslate.py
import requests # pip install requests import json import execjs # pip install PyExecJS import urllib3 # pip install urllib3 ''' author by Benji date at 2018.12.07 实现: 模拟浏览器中Google翻译的url请求 不同于Baidu直接给出API, Google翻译需要调用其封装的lib 参考: https://www.jianshu.com/p/95cf6e73d6ee https://cloud.google.com/trans...
0.330471
0.189465
import os from shutil import copyfile from PyQt6.QtCore import Qt from PyQt6.QtTest import QTest from PyQt6.QtWidgets import QApplication from password_manager.application_context import ApplicationContext from password_manager.utils.file_helper import FileHelper class SystemTestFixture: def __init__(self, dela...
system_tests/fixture.py
import os from shutil import copyfile from PyQt6.QtCore import Qt from PyQt6.QtTest import QTest from PyQt6.QtWidgets import QApplication from password_manager.application_context import ApplicationContext from password_manager.utils.file_helper import FileHelper class SystemTestFixture: def __init__(self, dela...
0.3295
0.075961
import math print ('----Math functions loaded up---- \nEnter \'list_functions()\' to display available functions') def list_functions(): print ('intoRadians()') print ('intoDegrees()') print ('LOS()') print ('vectorProduct()') print ('vectorMag()') def intoRadians(): degrees = float(input('En...
Math Functions/math functions.py
import math print ('----Math functions loaded up---- \nEnter \'list_functions()\' to display available functions') def list_functions(): print ('intoRadians()') print ('intoDegrees()') print ('LOS()') print ('vectorProduct()') print ('vectorMag()') def intoRadians(): degrees = float(input('En...
0.452536
0.439206
import struct def write_instruction(instruction): pass def calculate_file_size(numbers_data): number_point = numbers_data[0] number_instructions = numbers_data[1] number_pois = numbers_data[2] #size of header adapted to obtain expected number, counted value was 139, need to understan where diff...
source/fit_encode.py
import struct def write_instruction(instruction): pass def calculate_file_size(numbers_data): number_point = numbers_data[0] number_instructions = numbers_data[1] number_pois = numbers_data[2] #size of header adapted to obtain expected number, counted value was 139, need to understan where diff...
0.412648
0.501221
from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from src.fake_news_detector.core.classification.models import ClassificationModel def split_dataset(X, y): X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) # Normalize scaler = Min...
src/fake_news_detector/core/classification/sub_classifications.py
from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from src.fake_news_detector.core.classification.models import ClassificationModel def split_dataset(X, y): X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) # Normalize scaler = Min...
0.812272
0.606644
from __future__ import absolute_import import logging import sys import math import os.path as op from pbcommand.pb_io import write_pipeline_chunks from pbcommand.models import FileTypes, PipelineChunk from pbcoretools.datastore_utils import dataset_to_datastore, datastore_to_datastorefile_objs from .align_json_to_s...
SLpackage/private/pacbio/pythonpkgs/pbsvtools/lib/python2.7/site-packages/pbsvtools/tasks/scatter_align_json_to_svsig.py
from __future__ import absolute_import import logging import sys import math import os.path as op from pbcommand.pb_io import write_pipeline_chunks from pbcommand.models import FileTypes, PipelineChunk from pbcoretools.datastore_utils import dataset_to_datastore, datastore_to_datastorefile_objs from .align_json_to_s...
0.490724
0.279964
import binascii import rsa import base64 import requests import re import json def prelogin(): url="https://login.sina.com.cn/sso/prelogin.php?entry=account&callback=sinaSSOController.preloginCallBack&su=MTU2MjAxNTE0NzU%3D&rsakt=mod&client=ssologin.js(v1.4.15)&_=1476186181803" html=requests.get(url).text j...
weibo_mine_hot/Refresh_cookie.py
import binascii import rsa import base64 import requests import re import json def prelogin(): url="https://login.sina.com.cn/sso/prelogin.php?entry=account&callback=sinaSSOController.preloginCallBack&su=MTU2MjAxNTE0NzU%3D&rsakt=mod&client=ssologin.js(v1.4.15)&_=1476186181803" html=requests.get(url).text j...
0.199932
0.124719
from kubernetes.client import CoreV1Api from app.models.user import User from app.models.route import RouteItem dashboard_route = RouteItem(**{ 'path': '/dashboard', 'name': 'Dashboard', 'component': 'LAYOUT', 'redirect': '/dashboard/overview', 'meta': { "title": 'routes.adminDashboard.das...
app/core/route_admin.py
from kubernetes.client import CoreV1Api from app.models.user import User from app.models.route import RouteItem dashboard_route = RouteItem(**{ 'path': '/dashboard', 'name': 'Dashboard', 'component': 'LAYOUT', 'redirect': '/dashboard/overview', 'meta': { "title": 'routes.adminDashboard.das...
0.412648
0.130009
import unittest import libyang import asyncio import logging import time import itertools from multiprocessing import Process, Queue from goldstone.lib.connector.sysrepo import Connector from goldstone.lib.server_connector import create_server_connector from goldstone.lib.errors import * from goldstone.lib.util import...
src/xlate/openconfig/tests/test.py
import unittest import libyang import asyncio import logging import time import itertools from multiprocessing import Process, Queue from goldstone.lib.connector.sysrepo import Connector from goldstone.lib.server_connector import create_server_connector from goldstone.lib.errors import * from goldstone.lib.util import...
0.428712
0.135919
import torch import torch.nn as nn import torch.nn.functional as F from .aspp import ASPP_Module up_kwargs = {'mode': 'bilinear', 'align_corners': False} norm_layer = nn.BatchNorm2d class _ConvBNReLU(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, di...
models/head/aspp_plus.py
import torch import torch.nn as nn import torch.nn.functional as F from .aspp import ASPP_Module up_kwargs = {'mode': 'bilinear', 'align_corners': False} norm_layer = nn.BatchNorm2d class _ConvBNReLU(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, di...
0.928878
0.360433
import time import unittest from inoft_vocal_framework.audio_editing.audioclip import AudioBlock class MyTestCase(unittest.TestCase): def test_something(self): start = time.time() audio_block_1 = AudioBlock() audio_block_1.create_track() """river_track = Track(is_primary=False, l...
tests/audio_engine/test_audio_editing.py
import time import unittest from inoft_vocal_framework.audio_editing.audioclip import AudioBlock class MyTestCase(unittest.TestCase): def test_something(self): start = time.time() audio_block_1 = AudioBlock() audio_block_1.create_track() """river_track = Track(is_primary=False, l...
0.291384
0.239744
r'''A data-parallel Mean metric. ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import ma...
hybridbackend/tensorflow/metrics/mean.py
r'''A data-parallel Mean metric. ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import ma...
0.938738
0.510802
Copyright (c) 2017, WinQuant Information and Technology Co. Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this li...
api/stocks.py
Copyright (c) 2017, WinQuant Information and Technology Co. Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this li...
0.807271
0.184327
from datetime import timedelta from unittest.mock import patch from django.conf import settings from django.utils.timezone import now from django.utils.translation import override from factory import create_batch from libya_elections.constants import PHONE_NOT_ACTIVATED, NOT_WHITELISTED_NUMBER, \ POLLING_REPORT_C...
polling_reports/tests/test_logic.py
from datetime import timedelta from unittest.mock import patch from django.conf import settings from django.utils.timezone import now from django.utils.translation import override from factory import create_batch from libya_elections.constants import PHONE_NOT_ACTIVATED, NOT_WHITELISTED_NUMBER, \ POLLING_REPORT_C...
0.633637
0.230627
from __future__ import print_function, division import numpy as np import operator from qsrlib_qsrs.qsr_arg_relations_abstractclass import QSR_Arg_Relations_Abstractclass from qsrlib_io.world_qsr_trace import * class QSR_Arg_Relations_Distance(QSR_Arg_Relations_Abstractclass): """Argument distance relations. ...
qsrlib/src/qsrlib_qsrs/qsr_arg_relations_distance.py
from __future__ import print_function, division import numpy as np import operator from qsrlib_qsrs.qsr_arg_relations_abstractclass import QSR_Arg_Relations_Abstractclass from qsrlib_io.world_qsr_trace import * class QSR_Arg_Relations_Distance(QSR_Arg_Relations_Abstractclass): """Argument distance relations. ...
0.697609
0.408778
from mayavi import mlab from BDSpace import Space from BDSpace.Figure.Sphere import * from BDSpace.Curve.Parametric import Arc from BDSpace.Coordinates import Cartesian import BDSpaceVis as Visual solar_system = Space('Solar System') sun = Sphere('Sun', r_outer=0.2) mercury = Space('Mercury', Cartesian(origin=[0.5,...
demo/05_space_visualization_planets.py
from mayavi import mlab from BDSpace import Space from BDSpace.Figure.Sphere import * from BDSpace.Curve.Parametric import Arc from BDSpace.Coordinates import Cartesian import BDSpaceVis as Visual solar_system = Space('Solar System') sun = Sphere('Sun', r_outer=0.2) mercury = Space('Mercury', Cartesian(origin=[0.5,...
0.546738
0.529203
import time from core.utils.const import SQLTuning import logging from core.utils.engines import get_engine from rest_framework.response import Response from core.utils.sql_utils import extract_tables CUSTOM_ERROR = logging.getLogger('SqlManager.core.sql_tuning') import re class SqlTuning(object): def __init__(se...
src/core/api/sql_tuning.py
import time from core.utils.const import SQLTuning import logging from core.utils.engines import get_engine from rest_framework.response import Response from core.utils.sql_utils import extract_tables CUSTOM_ERROR = logging.getLogger('SqlManager.core.sql_tuning') import re class SqlTuning(object): def __init__(se...
0.395835
0.121816
import os import logging from distutils import log from distutils.util import byte_compile from distutils.dir_util import remove_tree, mkpath, copy_tree from distutils.file_util import copy_file from distutils.sysconfig import get_python_version from distutils.command.bdist import bdist from . import COMMON_USER_OPTI...
cpydist/bdist.py
import os import logging from distutils import log from distutils.util import byte_compile from distutils.dir_util import remove_tree, mkpath, copy_tree from distutils.file_util import copy_file from distutils.sysconfig import get_python_version from distutils.command.bdist import bdist from . import COMMON_USER_OPTI...
0.499756
0.106365
from django.conf.urls import url from . import views app_name = "containertemplates" urlpatterns = [ url( regex=r"^site$", view=views.ContainerTemplateSiteListView.as_view(), name="site-list", ), url( regex=r"^site/detail/(?P<containertemplatesite>[0-9a-f-]+)$", ...
containertemplates/urls.py
from django.conf.urls import url from . import views app_name = "containertemplates" urlpatterns = [ url( regex=r"^site$", view=views.ContainerTemplateSiteListView.as_view(), name="site-list", ), url( regex=r"^site/detail/(?P<containertemplatesite>[0-9a-f-]+)$", ...
0.336222
0.192805
import re import logging from typing import TextIO from typing import Optional from typing import Sequence, Iterator, List, Dict from gffpal.parsers.parsers import ParseError, LineParseError from gffpal.parsers.parsers import MULTISPACE_REGEX from gffpal.parsers.parsers import ( parse_int, parse_float, par...
gffpal/parsers/trnascan.py
import re import logging from typing import TextIO from typing import Optional from typing import Sequence, Iterator, List, Dict from gffpal.parsers.parsers import ParseError, LineParseError from gffpal.parsers.parsers import MULTISPACE_REGEX from gffpal.parsers.parsers import ( parse_int, parse_float, par...
0.778355
0.266486
from typing import Iterable, List, Optional from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, func, select from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.orm import declarative_base, relationship, selectinload from vkbot...
vk_bot/db.py
from typing import Iterable, List, Optional from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, func, select from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.orm import declarative_base, relationship, selectinload from vkbot...
0.46393
0.12276
import dailyScript as daily #create each of the days information that will be passed to the daily main script def main(): #day1 d1_trans1 = ["login", "agent", "createAccount", "1234567", "Emma", "logout"] #trans2 will print "Account doesn't exist" d1_trans2 = ["login", "machine", "withdraw", "1234567",...
src/weeklyScript.py
import dailyScript as daily #create each of the days information that will be passed to the daily main script def main(): #day1 d1_trans1 = ["login", "agent", "createAccount", "1234567", "Emma", "logout"] #trans2 will print "Account doesn't exist" d1_trans2 = ["login", "machine", "withdraw", "1234567",...
0.279828
0.379148
class BUIMask(object): """Mask client/servers based on user preferences or user ACL""" def init_app(self, app): """Initialize the mask :param app: Application context :type app: :class:`burpui.engines.server.BUIServer` """ self.app = app @property def is_user_p...
burpui/filter.py
class BUIMask(object): """Mask client/servers based on user preferences or user ACL""" def init_app(self, app): """Initialize the mask :param app: Application context :type app: :class:`burpui.engines.server.BUIServer` """ self.app = app @property def is_user_p...
0.782829
0.177009
from data_structures.linked_lists.singly_linked_list import LinkedList class DoublyListNode: def __init__(self, value=None, next=None, previous=None): self.value = value self.next = next self.previous = previous class DoublyLinkedList(LinkedList): def __init__(self, head=None, tail=N...
data_structures/linked_lists/doubly_linked_list.py
from data_structures.linked_lists.singly_linked_list import LinkedList class DoublyListNode: def __init__(self, value=None, next=None, previous=None): self.value = value self.next = next self.previous = previous class DoublyLinkedList(LinkedList): def __init__(self, head=None, tail=N...
0.619817
0.198646
from fbs_runtime import _state, FbsError import os import sys def is_windows(): """ Return True if the current OS is Windows, False otherwise. """ return name() == 'Windows' def is_mac(): """ Return True if the current OS is macOS, False otherwise. """ return name() == 'Mac' def is_l...
venv/Lib/site-packages/fbs_runtime/platform.py
from fbs_runtime import _state, FbsError import os import sys def is_windows(): """ Return True if the current OS is Windows, False otherwise. """ return name() == 'Windows' def is_mac(): """ Return True if the current OS is macOS, False otherwise. """ return name() == 'Mac' def is_l...
0.306216
0.047558
import os import re import errno import socket import json from chroma_agent.lib.shell import AgentShell from toolz.functoolz import pipe from toolz.itertoolz import getter from toolz.curried import map as cmap, filter as cfilter, mapcat as cmapcat import chroma_agent.lib.normalize_device_path as ndp # Python errno ...
chroma-agent/chroma_agent/device_plugins/linux_components/block_devices.py
import os import re import errno import socket import json from chroma_agent.lib.shell import AgentShell from toolz.functoolz import pipe from toolz.itertoolz import getter from toolz.curried import map as cmap, filter as cfilter, mapcat as cmapcat import chroma_agent.lib.normalize_device_path as ndp # Python errno ...
0.471223
0.146973
import time import numpy as np from copy import deepcopy import matplotlib.pyplot as plt # Resistance in ohms of the resistor r = 1 # Capacitance of the capacitor C = 1 Vin = 10 b = 0 old_v2 = 0 delta_t = 5e-3 t = 5e-3 # Initial guess for the first step (literally doesn't matter) input_vec = [10, 5, -2] results ...
Initial Testing/Jacobian Capacitor Try.py
import time import numpy as np from copy import deepcopy import matplotlib.pyplot as plt # Resistance in ohms of the resistor r = 1 # Capacitance of the capacitor C = 1 Vin = 10 b = 0 old_v2 = 0 delta_t = 5e-3 t = 5e-3 # Initial guess for the first step (literally doesn't matter) input_vec = [10, 5, -2] results ...
0.451568
0.561215
from bs4 import BeautifulSoup import requests import re import wget from subprocess import call import argparse # https://sdl-stickershop.line.naver.jp/stickershop/v1/sticker/17941023/IOS/sticker_animation@2x.png # https://sdl-stickershop.line.naver.jp/stickershop/v1/sticker/17941023/android/sticker.png def striphtml(d...
line.py
from bs4 import BeautifulSoup import requests import re import wget from subprocess import call import argparse # https://sdl-stickershop.line.naver.jp/stickershop/v1/sticker/17941023/IOS/sticker_animation@2x.png # https://sdl-stickershop.line.naver.jp/stickershop/v1/sticker/17941023/android/sticker.png def striphtml(d...
0.188287
0.071009
import datetime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, DateTime, Boolean, create_engine Base = declarative_base() engine = create_engine('sqlite:///db.db?check_same_thread=False') class User(Base): __tablename__ = 'user' id = Column(Integer, p...
src/backend/models.py
import datetime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, DateTime, Boolean, create_engine Base = declarative_base() engine = create_engine('sqlite:///db.db?check_same_thread=False') class User(Base): __tablename__ = 'user' id = Column(Integer, p...
0.55447
0.113064
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), ] operations = [ migrations.CreateModel( ...
foodcartapp/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), ] operations = [ migrations.CreateModel( ...
0.570451
0.132038
import core # +---+ +---+ # | X | | Y | # +---+ +---+ def bn_independent(): g = core.BayesNet() g.add_nodes_from(['X', 'Y']) return g # +---+ +---+ # | X |---->| Y | # +---+ +---+ def bn_dependent(): g = core.BayesNet() g.add_nodes_from(['X', 'Y']) g.add_edge('X', 'Y') ...
Bayesian Networks/gibbs sampling/examples_dsep.py
import core # +---+ +---+ # | X | | Y | # +---+ +---+ def bn_independent(): g = core.BayesNet() g.add_nodes_from(['X', 'Y']) return g # +---+ +---+ # | X |---->| Y | # +---+ +---+ def bn_dependent(): g = core.BayesNet() g.add_nodes_from(['X', 'Y']) g.add_edge('X', 'Y') ...
0.53777
0.170335
import datetime from django.core.management import call_command from django.urls import reverse from dateutil.relativedelta import relativedelta from django.utils.timezone import now, get_current_timezone from factory.fuzzy import FuzzyDate from django_countries.fields import Country as DjangoCountry from freezegun i...
mi/tests/test_country_views.py
import datetime from django.core.management import call_command from django.urls import reverse from dateutil.relativedelta import relativedelta from django.utils.timezone import now, get_current_timezone from factory.fuzzy import FuzzyDate from django_countries.fields import Country as DjangoCountry from freezegun i...
0.382718
0.22306
import os from pathlib import Path import pytest import numpy as np import torch as th from ml.vision.transforms import functional as TF from ml.vision import transforms from ml.vision.ops import clip_boxes_to_image from ml import nn import ml from .fixtures import * @pytest.fixture def dev(): return th.device('...
tests/test_backbone.py
import os from pathlib import Path import pytest import numpy as np import torch as th from ml.vision.transforms import functional as TF from ml.vision import transforms from ml.vision.ops import clip_boxes_to_image from ml import nn import ml from .fixtures import * @pytest.fixture def dev(): return th.device('...
0.483161
0.460592
import requests import json from ckan.plugins import toolkit as tk from ckan import model as ckan_model from ckan.logic import NotFound from ckan.lib.mailer import mail_recipient from .. import model import logging _ = tk._ check_access = tk.check_access side_effect_free = tk.side_effect_free log = logging.getLogger...
ckanext/ckanext-apply_permissions_for_service/ckanext/apply_permissions_for_service/logic/action.py
import requests import json from ckan.plugins import toolkit as tk from ckan import model as ckan_model from ckan.logic import NotFound from ckan.lib.mailer import mail_recipient from .. import model import logging _ = tk._ check_access = tk.check_access side_effect_free = tk.side_effect_free log = logging.getLogger...
0.250821
0.086632
from __future__ import absolute_import, division, print_function, unicode_literals import sys import argparse import fileinput from cocoprep.archive_exceptions import PreprocessingException, PreprocessingWarning from cocoprep.archive_load_data import parse_archive_file_name, parse_range, get_key_value, get_file_name_...
code-preprocessing/log-reconstruction/evaluations_append.py
from __future__ import absolute_import, division, print_function, unicode_literals import sys import argparse import fileinput from cocoprep.archive_exceptions import PreprocessingException, PreprocessingWarning from cocoprep.archive_load_data import parse_archive_file_name, parse_range, get_key_value, get_file_name_...
0.448668
0.238473
from homeassistant.components.device_tracker import DOMAIN, config_entry as ce from homeassistant.helpers import device_registry as dr, entity_registry as er from tests.common import MockConfigEntry def test_tracker_entity(): """Test tracker entity.""" class TestEntry(ce.TrackerEntity): """Mock trac...
tests/components/device_tracker/test_config_entry.py
from homeassistant.components.device_tracker import DOMAIN, config_entry as ce from homeassistant.helpers import device_registry as dr, entity_registry as er from tests.common import MockConfigEntry def test_tracker_entity(): """Test tracker entity.""" class TestEntry(ce.TrackerEntity): """Mock trac...
0.739046
0.303151
import pygame import sys from states.intro import Intro from states.menu import Menu from states.game import Game from states.transition import Transition from states.editor import Editor from utils import music_manager as Music_Manager import random class Main(object): def __init__(self): pygame.init()...
main.py
import pygame import sys from states.intro import Intro from states.menu import Menu from states.game import Game from states.transition import Transition from states.editor import Editor from utils import music_manager as Music_Manager import random class Main(object): def __init__(self): pygame.init()...
0.234933
0.130923
import sys import PySimpleGUI as sg import etl_asset_data as etl import data_base from datetime import datetime as dt sg.theme("DarkTeal10") def create_main_window(): layout = [ [ sg.Text("Selecione o seu arquivo TXT"), sg.In(key="-FILE-"), sg.FileBrowse("Seleciona...
gui.py
import sys import PySimpleGUI as sg import etl_asset_data as etl import data_base from datetime import datetime as dt sg.theme("DarkTeal10") def create_main_window(): layout = [ [ sg.Text("Selecione o seu arquivo TXT"), sg.In(key="-FILE-"), sg.FileBrowse("Seleciona...
0.354992
0.263053
import itertools import numpy as np import gym from gym_minigrid.minigrid import COLORS, WorldObj from .verifier import * from .levelgen import * class ColorSplitsBase(RoomGridLevel): def __init__(self, room_size=8, num_dists=8, seed=None, box_colors = ['red', 'green', 'blue'], ball_colors = ['purple', 'yellow'...
babyai/levels/embodiment_levels.py
import itertools import numpy as np import gym from gym_minigrid.minigrid import COLORS, WorldObj from .verifier import * from .levelgen import * class ColorSplitsBase(RoomGridLevel): def __init__(self, room_size=8, num_dists=8, seed=None, box_colors = ['red', 'green', 'blue'], ball_colors = ['purple', 'yellow'...
0.617397
0.198491
# Script for organizing ASL data to BIDS format # Pull scan name from asl and m0 image, NEED TO DO: output to examcard2json # Remove asl image (or just don't put it in the BIDS folder?) # Convert dicom to nifti import glob import os import sys, getopt from pydicom import dcmread import json def main(argv): indir = ...
xnatwrapper/organize_data.py
# Script for organizing ASL data to BIDS format # Pull scan name from asl and m0 image, NEED TO DO: output to examcard2json # Remove asl image (or just don't put it in the BIDS folder?) # Convert dicom to nifti import glob import os import sys, getopt from pydicom import dcmread import json def main(argv): indir = ...
0.123696
0.252004
from django.contrib.auth import get_user_model from rest_framework import serializers from bmh_lims.database import models User = get_user_model() class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'groups'] class Workfl...
bmh_lims/database/api/serializers.py
from django.contrib.auth import get_user_model from rest_framework import serializers from bmh_lims.database import models User = get_user_model() class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'groups'] class Workfl...
0.619356
0.115511
# This file is part of the Mad Girlfriend software # See the LICENSE file for copyright information from rules import Rules from alertgenerator import Alert, Alerter from packetparser import Packet import signal, sys, os, socket, time, traceback, exceptions def getMemoryUsage(): data = open('/proc/meminfo', 'r'...
madgirlfriend.py
# This file is part of the Mad Girlfriend software # See the LICENSE file for copyright information from rules import Rules from alertgenerator import Alert, Alerter from packetparser import Packet import signal, sys, os, socket, time, traceback, exceptions def getMemoryUsage(): data = open('/proc/meminfo', 'r'...
0.307878
0.141578
import sgtk from sgtk.platform.qt import QtCore, QtGui from .custom_widget_item import CustomTreeWidgetItem logger = sgtk.platform.get_logger(__name__) from .tree_node_base import TreeNodeBase from .tree_node_task import TreeNodeTask class TreeNodeItem(TreeNodeBase): """ Tree item for a publish item "...
install/app_store/tk-multi-publish2/v2.0.6/python/tk_multi_publish2/publish_tree_widget/tree_node_item.py
import sgtk from sgtk.platform.qt import QtCore, QtGui from .custom_widget_item import CustomTreeWidgetItem logger = sgtk.platform.get_logger(__name__) from .tree_node_base import TreeNodeBase from .tree_node_task import TreeNodeTask class TreeNodeItem(TreeNodeBase): """ Tree item for a publish item "...
0.612078
0.154344
import tensorflow as tf import math def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def conv1d(x, W, s): return tf.nn.conv2d(x, W, strides=s, p...
dla_cnn/Model_v4.py
import tensorflow as tf import math def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def conv1d(x, W, s): return tf.nn.conv2d(x, W, strides=s, p...
0.922989
0.552057
from selenium import webdriver import time import requests from bs4 import BeautifulSoup import re import json from selenium.webdriver.common.keys import Keys import pickle import pandas as pd array_textos_noticias = [] link = [] def elpais_content(user_input): #Headless para evitar que se lance la ventana de chr...
api/scrapers/elPais.py
from selenium import webdriver import time import requests from bs4 import BeautifulSoup import re import json from selenium.webdriver.common.keys import Keys import pickle import pandas as pd array_textos_noticias = [] link = [] def elpais_content(user_input): #Headless para evitar que se lance la ventana de chr...
0.072587
0.075858
from scipy.linalg import solve_continuous_lyapunov from tqdm import tqdm from torch.utils.data import Subset import torch from nnlib.nnlib import utils from .ntk import compute_training_loss_at_time_t, get_predictions_at_time_t, get_weights_at_time_t, \ get_test_predictions_at_time_t from . import misc from .sgd i...
sample_info/modules/stability.py
from scipy.linalg import solve_continuous_lyapunov from tqdm import tqdm from torch.utils.data import Subset import torch from nnlib.nnlib import utils from .ntk import compute_training_loss_at_time_t, get_predictions_at_time_t, get_weights_at_time_t, \ get_test_predictions_at_time_t from . import misc from .sgd i...
0.795062
0.327776
import argparse import sys from array import array from struct import unpack from math import sqrt def doWork(args): from DataFormats.FWLite import Handle, Events from ROOT import TGraphErrors, TFile, gROOT, kOrange output_file = None gr = None if not args.files: return tracks_h = Handl...
hip_xsec.py
import argparse import sys from array import array from struct import unpack from math import sqrt def doWork(args): from DataFormats.FWLite import Handle, Events from ROOT import TGraphErrors, TFile, gROOT, kOrange output_file = None gr = None if not args.files: return tracks_h = Handl...
0.29088
0.295942
import pygame, sys, math, time from utils import MenuItemIndex, utils, TimerObject from BaseRenderer import BaseRenderer class SpaceRace(): def __init__(self, pyg, screen): # General settings print("init SpaceRace") self.pyg = pyg self.myfont = self.pyg.font.SysFont("monospace", 30)...
UranusInvaders/SpaceRace.py
import pygame, sys, math, time from utils import MenuItemIndex, utils, TimerObject from BaseRenderer import BaseRenderer class SpaceRace(): def __init__(self, pyg, screen): # General settings print("init SpaceRace") self.pyg = pyg self.myfont = self.pyg.font.SysFont("monospace", 30)...
0.373647
0.207175
__file__ = 'OffSystem_v1' __date__ = '5/29/14' __author__ = 'ABREZNIC' import os, arcpy, xlwt, datetime #date now = datetime.datetime.now() curMonth = now.strftime("%m") curDay = now.strftime("%d") curYear = now.strftime("%Y") today = curYear + "_" + curMonth + "_" + curDay #variables qcfolder = "C:\\TxDOT\\QC\\Off...
QC/old/OffSystem_v1.py
__file__ = 'OffSystem_v1' __date__ = '5/29/14' __author__ = 'ABREZNIC' import os, arcpy, xlwt, datetime #date now = datetime.datetime.now() curMonth = now.strftime("%m") curDay = now.strftime("%d") curYear = now.strftime("%Y") today = curYear + "_" + curMonth + "_" + curDay #variables qcfolder = "C:\\TxDOT\\QC\\Off...
0.096514
0.162247
import mock from karborclient.tests.unit import base from karborclient.tests.unit.v1 import fakes cs = fakes.FakeClient() mock_request_return = ({}, {'quota': {'plans': 50}}) class QuotasTest(base.TestCaseShell): @mock.patch('karborclient.common.http.HTTPClient.json_request') def test_quota_update(self, m...
karborclient/tests/unit/v1/test_quotas.py
import mock from karborclient.tests.unit import base from karborclient.tests.unit.v1 import fakes cs = fakes.FakeClient() mock_request_return = ({}, {'quota': {'plans': 50}}) class QuotasTest(base.TestCaseShell): @mock.patch('karborclient.common.http.HTTPClient.json_request') def test_quota_update(self, m...
0.584271
0.161849
import json import logging import optparse import os import shutil import tempfile import urllib2 from xml.etree.ElementTree import tostring try: # For Python 3.0 and later from shutil import unpack_archive except ImportError: # Fall back to Python 2 import from setuptools.archive_util import unpack_a...
data_managers/data_manager_manual/data_manager/data_manager_manual.py
import json import logging import optparse import os import shutil import tempfile import urllib2 from xml.etree.ElementTree import tostring try: # For Python 3.0 and later from shutil import unpack_archive except ImportError: # Fall back to Python 2 import from setuptools.archive_util import unpack_a...
0.253399
0.185301
import logging import threading import time from playsound import playsound from pymongo import MongoClient from pymongo.errors import ServerSelectionTimeoutError from sshtunnel import HandlerSSHTunnelForwarderError, SSHTunnelForwarder class CommentResourceAccess: """A data loader class that expands a truncated ...
ghtorrent/CommentResourceAccess.py
import logging import threading import time from playsound import playsound from pymongo import MongoClient from pymongo.errors import ServerSelectionTimeoutError from sshtunnel import HandlerSSHTunnelForwarderError, SSHTunnelForwarder class CommentResourceAccess: """A data loader class that expands a truncated ...
0.605333
0.074332
try: import gsdl2 as pygame except: import pygame import random class MapGrid(): def __init__(self, map_width, map_height): # set map values self.map_width = map_width self.map_height = map_width # generate outside rooms self.outside_terrain_grid = self._generate_...
demos/16_cellular.py
try: import gsdl2 as pygame except: import pygame import random class MapGrid(): def __init__(self, map_width, map_height): # set map values self.map_width = map_width self.map_height = map_width # generate outside rooms self.outside_terrain_grid = self._generate_...
0.242295
0.373847
from .plugin import Plugin class Monitor(Plugin): def __init__(self, running_average=True, epoch_average=True, smoothing=0.7, precision=None, number_format=None, unit=''): if precision is None: precision = 4 if number_format is None: number_format = '.{}f'...
torch/utils/trainer/plugins/monitor.py
from .plugin import Plugin class Monitor(Plugin): def __init__(self, running_average=True, epoch_average=True, smoothing=0.7, precision=None, number_format=None, unit=''): if precision is None: precision = 4 if number_format is None: number_format = '.{}f'...
0.599016
0.205974
from common import RunningStyle, PasswordPolicyConf from copy import deepcopy from sys import platform # possible jtr names john_nick_names = [ 'j', 'jtr', 'JTR', 'JtR', 'John', 'john', 'J', '<NAME>', 'Jtr' ] # possible hc names hc_nick_names = ['h', 'hc', 'HC', 'hashcat', 'H', 'Hashcat', 'Hc'] # For detailed in...
src/config.py
from common import RunningStyle, PasswordPolicyConf from copy import deepcopy from sys import platform # possible jtr names john_nick_names = [ 'j', 'jtr', 'JTR', 'JtR', 'John', 'john', 'J', '<NAME>', 'Jtr' ] # possible hc names hc_nick_names = ['h', 'hc', 'HC', 'hashcat', 'H', 'Hashcat', 'Hc'] # For detailed in...
0.501221
0.173533
import logging import os import uuid from enum import Enum from airflow.exceptions import AirflowException from airflow.providers.http.hooks.http import HttpHook from taurus_datajob_api import ApiClient from taurus_datajob_api import Configuration from taurus_datajob_api import DataJobExecution from taurus_datajob_api...
projects/vdk-plugins/airflow-provider-vdk/vdk_provider/hooks/vdk.py
import logging import os import uuid from enum import Enum from airflow.exceptions import AirflowException from airflow.providers.http.hooks.http import HttpHook from taurus_datajob_api import ApiClient from taurus_datajob_api import Configuration from taurus_datajob_api import DataJobExecution from taurus_datajob_api...
0.470493
0.078926
import os import requests from PIL import Image from io import BytesIO import random class Module: DESC = "" ARGC = 0 ARG_WARNING = "There are not enough arguments to continue." ACC_TOKEN = os.getenv("GROUPME_ACCESS_TOKEN") def __init__: print("Loaded module %s." % self.__clas...
cmds/base.py
import os import requests from PIL import Image from io import BytesIO import random class Module: DESC = "" ARGC = 0 ARG_WARNING = "There are not enough arguments to continue." ACC_TOKEN = os.getenv("GROUPME_ACCESS_TOKEN") def __init__: print("Loaded module %s." % self.__clas...
0.303525
0.080574
import rospy import datetime import os import json from std_msgs.msg import String from sensor_msgs.msg import Image from acrv_apc_2017_perception.msg import autosegmenter_msg import cv_bridge import cv2 NUM_IMGS = 7 seen_items = [ "plastic_wine_glass", "hinged_ruled_index_cards", "black_fashion_gloves"...
apc_state_machine/state_machine/data/image_capture.py
import rospy import datetime import os import json from std_msgs.msg import String from sensor_msgs.msg import Image from acrv_apc_2017_perception.msg import autosegmenter_msg import cv_bridge import cv2 NUM_IMGS = 7 seen_items = [ "plastic_wine_glass", "hinged_ruled_index_cards", "black_fashion_gloves"...
0.375821
0.168515
import gi gi.require_version('Gtk', '3.0') # noinspection PyUnresolvedReferences,PyPep8 from gi.repository import Gtk class SBrickMotorChannelBox(Gtk.Frame): def __init__(self, channel, sbrick_channel): Gtk.Frame.__init__(self) self.sbrickChannel = sbrick_channel self.channel = channel ...
SBrickMotorChannelBox.py
import gi gi.require_version('Gtk', '3.0') # noinspection PyUnresolvedReferences,PyPep8 from gi.repository import Gtk class SBrickMotorChannelBox(Gtk.Frame): def __init__(self, channel, sbrick_channel): Gtk.Frame.__init__(self) self.sbrickChannel = sbrick_channel self.channel = channel ...
0.558688
0.115611
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.p...
third-party/corenlp/third-party/stanza/stanza/research/templates/third-party/tensorflow/core/util/event_pb2.py
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.p...
0.202996
0.115811
from steamCLI.steamapp import SteamApp class Results: def __init__(self, app: SteamApp, result: list=None, max_chars: int=79): self.app = app if result is None: self.result = [] else: self.result = result self.max_chars = max_chars self.description ...
steamCLI/results.py
from steamCLI.steamapp import SteamApp class Results: def __init__(self, app: SteamApp, result: list=None, max_chars: int=79): self.app = app if result is None: self.result = [] else: self.result = result self.max_chars = max_chars self.description ...
0.625552
0.146484
from PIL import Image, ImageChops import argparse import sys parser = argparse.ArgumentParser() parser.add_argument("input_file", type=str, help='The file to rainbowiefy') parser.add_argument("--blend-amount", "-b", type=float, default=0.25, help='How vibrant the colours are') parser.add_argument("--hue-rate", "-r", ...
rainbow.py
from PIL import Image, ImageChops import argparse import sys parser = argparse.ArgumentParser() parser.add_argument("input_file", type=str, help='The file to rainbowiefy') parser.add_argument("--blend-amount", "-b", type=float, default=0.25, help='How vibrant the colours are') parser.add_argument("--hue-rate", "-r", ...
0.425009
0.113162
import numpy as np from functions import * import sys import multiprocessing as mp import datetime import logging import argparse parser = argparse.ArgumentParser() parser.add_argument('-m', '--model', default=1, type=int, help='Model number.') parser.add_argument('-K', '--K', default=3, type=int, help='Model number.'...
experiment.py
import numpy as np from functions import * import sys import multiprocessing as mp import datetime import logging import argparse parser = argparse.ArgumentParser() parser.add_argument('-m', '--model', default=1, type=int, help='Model number.') parser.add_argument('-K', '--K', default=3, type=int, help='Model number.'...
0.341583
0.151624
from django.conf import settings from django.urls import include, path from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from django.views import defaults as default_views from rest_framework.schemas import get_schema_view from rest_framework_simpl...
config/urls.py
from django.conf import settings from django.urls import include, path from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from django.views import defaults as default_views from rest_framework.schemas import get_schema_view from rest_framework_simpl...
0.392337
0.059047
import os import shutil import math import pandas as pd import tensorflow as tf from tensorflow import keras import numpy as np import gc from typing import Tuple from sklearn import preprocessing from sklearn.utils import shuffle import datetime import time from src.data_process.config_paths import Data...
src/training/training_manager.py
import os import shutil import math import pandas as pd import tensorflow as tf from tensorflow import keras import numpy as np import gc from typing import Tuple from sklearn import preprocessing from sklearn.utils import shuffle import datetime import time from src.data_process.config_paths import Data...
0.710226
0.468304
import pandas as pd import numpy as np from constants import DESPESAS_COL, ORCAMENTOS_COL class Importacao: def __init__(self, despesas_caminho_arq, orcamentos_caminho_arq, mysql_obj): self.mysql_obj = mysql_obj despesas = self.criar_despesas_df(despesas_caminho_arq) orcamentos = self.cri...
src/importacao.py
import pandas as pd import numpy as np from constants import DESPESAS_COL, ORCAMENTOS_COL class Importacao: def __init__(self, despesas_caminho_arq, orcamentos_caminho_arq, mysql_obj): self.mysql_obj = mysql_obj despesas = self.criar_despesas_df(despesas_caminho_arq) orcamentos = self.cri...
0.328529
0.164785
import utils.epiweek as utils def get_window(epiweek, left_window, right_window): """ generate a time period [epiweek-left_window, epiweek+right_window] Args: epiweek - the "central" epiweek for a period left_window - the length of "left side" right_window - the length of "right si...
src/hosp/hosp_utils.py
import utils.epiweek as utils def get_window(epiweek, left_window, right_window): """ generate a time period [epiweek-left_window, epiweek+right_window] Args: epiweek - the "central" epiweek for a period left_window - the length of "left side" right_window - the length of "right si...
0.858318
0.664221
import math import numpy as np import logging import os import traceback import concurrent.futures from concurrent.futures import ThreadPoolExecutor from module.MOptions import MArmTwistOffOptions, MOptionsDataSet from mmd.PmxData import PmxModel, Bone # noqa from mmd.VmdData import VmdMotion, VmdBoneFrame, VmdCameraF...
src/service/ConvertArmTwistOffService.py
import math import numpy as np import logging import os import traceback import concurrent.futures from concurrent.futures import ThreadPoolExecutor from module.MOptions import MArmTwistOffOptions, MOptionsDataSet from mmd.PmxData import PmxModel, Bone # noqa from mmd.VmdData import VmdMotion, VmdBoneFrame, VmdCameraF...
0.34621
0.168788
class NetworkDevice(): def __init__(self, name, ip, user='cisco', pw='cisco'): self.name = name self.ip_address = ip self.username = user self.password = pw self.os_type = 'unknown' #---- Class to hold information about an IOS-XE network device -------- class NetworkDevice...
Cisco_PRNE_Exercises/getDevicesTypes_Class_inh.py
class NetworkDevice(): def __init__(self, name, ip, user='cisco', pw='cisco'): self.name = name self.ip_address = ip self.username = user self.password = pw self.os_type = 'unknown' #---- Class to hold information about an IOS-XE network device -------- class NetworkDevice...
0.420243
0.161916
import math import statistics import sys import gzip import itertools import csv def kmers(k, init=0, alph='ACGT'): kmers = {} for tup in itertools.product(alph, repeat=k): kmer = ''.join(tup) kmers[kmer] = init return kmers def count2freq(count): freq = {} total = 0 for k in count: total += count[k] for k...
ime_drafting/v1/imelib.py
import math import statistics import sys import gzip import itertools import csv def kmers(k, init=0, alph='ACGT'): kmers = {} for tup in itertools.product(alph, repeat=k): kmer = ''.join(tup) kmers[kmer] = init return kmers def count2freq(count): freq = {} total = 0 for k in count: total += count[k] for k...
0.153644
0.244448
from django.urls import reverse_lazy from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView, ) from starry_students.manager.forms import ( StudentAddUpdateForm, TeacherAddUpdateForm, ) from starry_students.manager.models import Student, Teacher, TeacherS...
starry_students/manager/views.py
from django.urls import reverse_lazy from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView, ) from starry_students.manager.forms import ( StudentAddUpdateForm, TeacherAddUpdateForm, ) from starry_students.manager.models import Student, Teacher, TeacherS...
0.590543
0.070464
import os import argparse import json import time from datetime import datetime import ipc ipcSocketPath = os.path.split(os.path.realpath(__file__))[0] + os.sep + 'ipcSocket' ################################################################################ # Logging ###################################...
changeSettings.py
import os import argparse import json import time from datetime import datetime import ipc ipcSocketPath = os.path.split(os.path.realpath(__file__))[0] + os.sep + 'ipcSocket' ################################################################################ # Logging ###################################...
0.152001
0.056262
import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin from warnings import warn class CategoricalColumnTransformer(BaseEstimator, TransformerMixin): """ This transformer is useful for describing an object as a bag of the categorical values that have been used to represent it within...
vectorizers/transformers/categorical_columns.py
import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin from warnings import warn class CategoricalColumnTransformer(BaseEstimator, TransformerMixin): """ This transformer is useful for describing an object as a bag of the categorical values that have been used to represent it within...
0.86267
0.681548
from datetime import datetime, date, timedelta import isodate import re def convert_to_interval_and_resolution(values): # Remove fractional seconds if any values = list(map(lambda v : v.split('.')[0], values)) # Convert to datetime times = list(map(lambda t : datetime.strptime(t, "%Y-%m-%dT%H:%M:%S")...
tasks/python3/processTemporalLayer.py
from datetime import datetime, date, timedelta import isodate import re def convert_to_interval_and_resolution(values): # Remove fractional seconds if any values = list(map(lambda v : v.split('.')[0], values)) # Convert to datetime times = list(map(lambda t : datetime.strptime(t, "%Y-%m-%dT%H:%M:%S")...
0.415373
0.472805
import math import numpy as np import torch import torch.nn as nn from torch.autograd import Variable from .prior import Prior from src.modules.nn_layers import * from src.modules.distributions import * from src.utils import args class VampPrior(Prior): """ VAE with a VampPrior https://arxiv.org/abs/1...
vae/src/modules/priors/vampprior.py
import math import numpy as np import torch import torch.nn as nn from torch.autograd import Variable from .prior import Prior from src.modules.nn_layers import * from src.modules.distributions import * from src.utils import args class VampPrior(Prior): """ VAE with a VampPrior https://arxiv.org/abs/1...
0.916157
0.472197
from rest_framework.decorators import api_view, permission_classes from rest_framework import status from rest_framework.response import Response import datetime from .models import User from .serializer import AccountRegistrationSerializer, UserSigninSerializer @api_view(['POST']) @permission_classes([]) def signup...
Back/registeration/views.py
from rest_framework.decorators import api_view, permission_classes from rest_framework import status from rest_framework.response import Response import datetime from .models import User from .serializer import AccountRegistrationSerializer, UserSigninSerializer @api_view(['POST']) @permission_classes([]) def signup...
0.362179
0.051083
# pylint: disable=missing-docstring # pylint: disable=invalid-name import json import os from mock import patch from citest.gcp_testing import GcpAgent def _method_spec(parameter_order, optional=None): parameters = {key: {'required': True} for key in parameter_order} parameters.update({key: {} for key in optio...
tests/gcp_testing/test_gcp_agent.py
# pylint: disable=missing-docstring # pylint: disable=invalid-name import json import os from mock import patch from citest.gcp_testing import GcpAgent def _method_spec(parameter_order, optional=None): parameters = {key: {'required': True} for key in parameter_order} parameters.update({key: {} for key in optio...
0.493164
0.127544
from tinydb import Query # TinyDB is a lightweight document oriented database from t_system.db_fetching import DBFetcher from t_system.motion.action import Position from t_system.administration import is_admin from t_system import dot_t_system_dir, T_SYSTEM_PATH from t_system import mission_manager, emotion_manager ...
t_system/remote_ui/modules/position.py
from tinydb import Query # TinyDB is a lightweight document oriented database from t_system.db_fetching import DBFetcher from t_system.motion.action import Position from t_system.administration import is_admin from t_system import dot_t_system_dir, T_SYSTEM_PATH from t_system import mission_manager, emotion_manager ...
0.676299
0.157169
import os from collections import defaultdict import numpy as np from anago.models import SeqLabeling from anago.data.metrics import get_entities class Tagger(object): def __init__(self, config, weights, save_path='', preprocessor=None, ...
anago/tagger.py
import os from collections import defaultdict import numpy as np from anago.models import SeqLabeling from anago.data.metrics import get_entities class Tagger(object): def __init__(self, config, weights, save_path='', preprocessor=None, ...
0.682891
0.313564
from utils_plus.router import url from utils_plus.views import return_path_view as view str_iter = lambda x: list(map(str, x)) def test_nesting_levels(): urls = list( url("home")[ url("p1", view, "report1"), url("p2", view, "report2"), url("level1", view, "sub1")[ ...
tests/test_router.py
from utils_plus.router import url from utils_plus.views import return_path_view as view str_iter = lambda x: list(map(str, x)) def test_nesting_levels(): urls = list( url("home")[ url("p1", view, "report1"), url("p2", view, "report2"), url("level1", view, "sub1")[ ...
0.377655
0.246477
import mintapi.api import mintapi.cli import mintapi.signIn import json import unittest import requests import tempfile from mintapi import constants from unittest.mock import patch, DEFAULT accounts_example = { "Account": [ { "type": "CreditAccount", "userCardType": "UNKNOWN", ...
tests/test_driver.py
import mintapi.api import mintapi.cli import mintapi.signIn import json import unittest import requests import tempfile from mintapi import constants from unittest.mock import patch, DEFAULT accounts_example = { "Account": [ { "type": "CreditAccount", "userCardType": "UNKNOWN", ...
0.343452
0.387285
from collections import namedtuple from . import ast WorldModel = namedtuple("WorldModel", ["individuals", "assignments"]) def interpret_formula(formula, model): """Given a logical formula and a model of the world, return the formula's denotation in the model. """ if isinstance(formula, ast.Var): ...
montague/interpreter.py
from collections import namedtuple from . import ast WorldModel = namedtuple("WorldModel", ["individuals", "assignments"]) def interpret_formula(formula, model): """Given a logical formula and a model of the world, return the formula's denotation in the model. """ if isinstance(formula, ast.Var): ...
0.633297
0.621053
import functools from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error f...
sdk/ml/azure-ai-ml/azure/ai/ml/_restclient/runhistory/aio/operations/_experiments_operations.py
import functools from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error f...
0.822332
0.112747
import distutils import os import py2exe import shutil import sys def run_py2exe(): py2exe.__version__ sys.argv.append('py2exe') distutils.core.setup( options = {"py2exe":{ "compressed": True, "optimize": 1, "bundle_files": 1, "excludes": ['Tkconstant...
setup.py
import distutils import os import py2exe import shutil import sys def run_py2exe(): py2exe.__version__ sys.argv.append('py2exe') distutils.core.setup( options = {"py2exe":{ "compressed": True, "optimize": 1, "bundle_files": 1, "excludes": ['Tkconstant...
0.155015
0.130009
import re import sys from typing import Optional import ensightreader import numpy as np import argparse def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("ensight_case", metavar="*.case", help="input EnSight Gold case (C Binary)") parser.add_argument("output_obj", metavar="*.obj",...
ensight2obj.py
import re import sys from typing import Optional import ensightreader import numpy as np import argparse def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("ensight_case", metavar="*.case", help="input EnSight Gold case (C Binary)") parser.add_argument("output_obj", metavar="*.obj",...
0.521959
0.217919
import discord from discord.ext import commands import random from discord.commands import slash_command class media(commands.Cog): def __init__(self, bot): self.bot = bot @slash_command(description="Doge smile") async def smile(self, ctx): await ctx.respond('https://tenor.com/view/perro-xd-xd-moises-xd-gif-...
cogs/media.py
import discord from discord.ext import commands import random from discord.commands import slash_command class media(commands.Cog): def __init__(self, bot): self.bot = bot @slash_command(description="Doge smile") async def smile(self, ctx): await ctx.respond('https://tenor.com/view/perro-xd-xd-moises-xd-gif-...
0.298696
0.146118
import os import random import numpy as np import torch from torch import nn, optim from torch.utils.data import DataLoader, Dataset from fairtorch import ConstraintLoss, DemographicParityLoss, EqualiedOddsLoss def seed_everything(seed): random.seed(seed) os.environ["PYTHONHASHSEED"] = str(seed) np.rand...
tests/test_constraint.py
import os import random import numpy as np import torch from torch import nn, optim from torch.utils.data import DataLoader, Dataset from fairtorch import ConstraintLoss, DemographicParityLoss, EqualiedOddsLoss def seed_everything(seed): random.seed(seed) os.environ["PYTHONHASHSEED"] = str(seed) np.rand...
0.775945
0.483344
from copy import deepcopy from math import cos, sin, sqrt, copysign class Vector(object): @staticmethod def _det3x3(matrix): det = 0.0 for inc in range(3): m = 1.0 for r in range(3): c = (r +...
bot1/sensor/vector.py
from copy import deepcopy from math import cos, sin, sqrt, copysign class Vector(object): @staticmethod def _det3x3(matrix): det = 0.0 for inc in range(3): m = 1.0 for r in range(3): c = (r +...
0.854854
0.611875
u""" harmonics.py Written by <NAME> (12/2020) Spherical harmonic data class for processing GRACE/GRACE-FO Level-2 data PYTHON DEPENDENCIES: numpy: Scientific Computing Tools For Python (https://numpy.org) netCDF4: Python interface to the netCDF C library (https://unidata.github.io/netcdf4-python/netCD...
gravity_toolkit/harmonics.py
u""" harmonics.py Written by <NAME> (12/2020) Spherical harmonic data class for processing GRACE/GRACE-FO Level-2 data PYTHON DEPENDENCIES: numpy: Scientific Computing Tools For Python (https://numpy.org) netCDF4: Python interface to the netCDF C library (https://unidata.github.io/netcdf4-python/netCD...
0.708313
0.578924
from tensorflow.python.keras import backend from tensorflow.python.keras import layers from tensorflow.python.keras.applications import imagenet_utils from tensorflow.python.keras.engine import training NUM_CLASSES = 1000 def dense_block(x, blocks, name): for i in range(blocks): x = conv_block(x, 32, nam...
tests/tensorflow/test_models/densenet.py
from tensorflow.python.keras import backend from tensorflow.python.keras import layers from tensorflow.python.keras.applications import imagenet_utils from tensorflow.python.keras.engine import training NUM_CLASSES = 1000 def dense_block(x, blocks, name): for i in range(blocks): x = conv_block(x, 32, nam...
0.900915
0.397997
import torch import torch.nn as nn from torch.nn import functional as F def octonion_mul(O_1, O_2): x0, x1, x2, x3, x4, x5, x6, x7 = O_1 y0, y1, y2, y3, y4, y5, y6, y7 = O_2 x = x0 * y0 - x1 * y1 - x2 * y2 - x3 * y3 - x4 * y4 - x5 * y5 - x6 * y6 - x7 * y7 e1 = x0 * y1 + x1 * y0 + x2 * y3 - x3 * y2 + x...
toolbox/nn/OctonionE.py
import torch import torch.nn as nn from torch.nn import functional as F def octonion_mul(O_1, O_2): x0, x1, x2, x3, x4, x5, x6, x7 = O_1 y0, y1, y2, y3, y4, y5, y6, y7 = O_2 x = x0 * y0 - x1 * y1 - x2 * y2 - x3 * y3 - x4 * y4 - x5 * y5 - x6 * y6 - x7 * y7 e1 = x0 * y1 + x1 * y0 + x2 * y3 - x3 * y2 + x...
0.896149
0.814164
from django.db import models from django.conf import settings from djnfusion import server, key from packages.models import InfusionsoftTag, PackagePurchase class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) archetype = models.CharField(max_length=255, blank=True, ...
dtf/profiles/models.py
from django.db import models from django.conf import settings from djnfusion import server, key from packages.models import InfusionsoftTag, PackagePurchase class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) archetype = models.CharField(max_length=255, blank=True, ...
0.357904
0.111749
from lightbulb.core.utils.httphandler import HTTPHandler from lightbulb.core.utils.common import findlibrary import json META = { 'author': '<NAME>, <NAME>', 'description': 'Identifies a WAF filter using a distinguish tree', 'type':'Distinguisher', 'options': [ ('FILE', None, True, 'File contai...
lightbulb/modules/distinguish_waf.py
from lightbulb.core.utils.httphandler import HTTPHandler from lightbulb.core.utils.common import findlibrary import json META = { 'author': '<NAME>, <NAME>', 'description': 'Identifies a WAF filter using a distinguish tree', 'type':'Distinguisher', 'options': [ ('FILE', None, True, 'File contai...
0.601594
0.162746
import multiprocessing import argparse import os import itertools import shutil from tqdm.auto import tqdm from skimage import io def crop_image(img, path): """ Crop the image and the corresponding ground truth, and saves all sub images img : string, image to crop path : string, path to directory c...
scripts/preprocess_im_sat_data.py
import multiprocessing import argparse import os import itertools import shutil from tqdm.auto import tqdm from skimage import io def crop_image(img, path): """ Crop the image and the corresponding ground truth, and saves all sub images img : string, image to crop path : string, path to directory c...
0.373419
0.329419
from ..map_resource.utility import Utility from .. import tools import pandas as pd settings = { 'app_id': 'F8aPRXcW3MmyUvQ8Z3J9', 'app_code' : 'IVp1_zoGHdLdz0GvD_Eqsw', 'map_tile_base_url': 'https://1.traffic.maps.cit.api.here.com/maptile/2.1/traffictile/newest/normal.day/', 'json_tile_base_url': 'htt...
streettraffic/tests/test_utility.py
from ..map_resource.utility import Utility from .. import tools import pandas as pd settings = { 'app_id': 'F8aPRXcW3MmyUvQ8Z3J9', 'app_code' : 'IVp1_zoGHdLdz0GvD_Eqsw', 'map_tile_base_url': 'https://1.traffic.maps.cit.api.here.com/maptile/2.1/traffictile/newest/normal.day/', 'json_tile_base_url': 'htt...
0.502441
0.405979
from msg import ReqMsg from cmds import Cmd class Window(Cmd): def __init__(self, session): self._session = session # Function: window_get_buffer # Parameters Window: window # Returns Buffer # Recieves channel id False # Can fail True def get_buffer(self, window): return ...
client/nvim_funcs.py
from msg import ReqMsg from cmds import Cmd class Window(Cmd): def __init__(self, session): self._session = session # Function: window_get_buffer # Parameters Window: window # Returns Buffer # Recieves channel id False # Can fail True def get_buffer(self, window): return ...
0.849222
0.086516
import logging import time import warnings import numpy as np import xgboost from matplotlib import pyplot as plt from mpl_toolkits import mplot3d from sklearn.base import clone from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import RBF from sklearn.metrics import me...
examples.py
import logging import time import warnings import numpy as np import xgboost from matplotlib import pyplot as plt from mpl_toolkits import mplot3d from sklearn.base import clone from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import RBF from sklearn.metrics import me...
0.749179
0.563108
from pygmol.abc import Chemistry, PlasmaParameters, Equations class DefaultChemistry(Chemistry): """Default concrete Chemistry subclass for testing.""" # species: e-, Ar, Ar+ species_ids = ["Ar", "Ar+"] species_charges = [0, 1] species_masses = [39.948, 39.948] species_lj_sigma_coefficients =...
tests/resources.py
from pygmol.abc import Chemistry, PlasmaParameters, Equations class DefaultChemistry(Chemistry): """Default concrete Chemistry subclass for testing.""" # species: e-, Ar, Ar+ species_ids = ["Ar", "Ar+"] species_charges = [0, 1] species_masses = [39.948, 39.948] species_lj_sigma_coefficients =...
0.834036
0.669502
import argparse import os import xml.etree.ElementTree as ET from pathlib import Path # Directory for product data def transform_name(product_name): # IMPLEMENT return product_name directory = r'/workspace/datasets/product_data/products/' parser = argparse.ArgumentParser(description='Process some integers.') ...
week3/createContentTrainingData.py
import argparse import os import xml.etree.ElementTree as ET from pathlib import Path # Directory for product data def transform_name(product_name): # IMPLEMENT return product_name directory = r'/workspace/datasets/product_data/products/' parser = argparse.ArgumentParser(description='Process some integers.') ...
0.451327
0.157137
import numpy as np from skimage import io, transform def get_data(img_root, x_file, y_file): """ Retrieves the image data and labels from the directory and files as given by the associated parameters. Note that images retrieved are resized to be 300 x 300 pixels. :param img_root: The directory wh...
utils.py
import numpy as np from skimage import io, transform def get_data(img_root, x_file, y_file): """ Retrieves the image data and labels from the directory and files as given by the associated parameters. Note that images retrieved are resized to be 300 x 300 pixels. :param img_root: The directory wh...
0.823719
0.765155