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 sys
import time
import numpy as num
#------------------------
# ANUGA Modules
#------------------------
from anuga import Domain
from anuga import Reflective_boundary
from anuga import Dirichlet_boundary
from anuga import Time_boundary
from anuga import Transmissive_boundary
from anuga import rect... | examples/parallel/run_sequential_dist_distribute_merimbula.py |
import os
import sys
import time
import numpy as num
#------------------------
# ANUGA Modules
#------------------------
from anuga import Domain
from anuga import Reflective_boundary
from anuga import Dirichlet_boundary
from anuga import Time_boundary
from anuga import Transmissive_boundary
from anuga import rect... | 0.474875 | 0.198064 |
from collections import OrderedDict, Mapping, Container
from pprint import pprint
from sys import getsizeof
def deep_compare(a, b, pointer='/'):
if a == b:
return
if type(a) != type(b):
reason = 'Different data types'
extra = str((type(a), type(b)))
x(pointer, reason, extra)
... | deeper.py | from collections import OrderedDict, Mapping, Container
from pprint import pprint
from sys import getsizeof
def deep_compare(a, b, pointer='/'):
if a == b:
return
if type(a) != type(b):
reason = 'Different data types'
extra = str((type(a), type(b)))
x(pointer, reason, extra)
... | 0.464659 | 0.256529 |
import sys
import os
import re
from java.lang import System
#Python Script to manage applications in weblogic server.
#This script takes input from command line and executes it.
#It can be used to check status,stop,start,deploy,undeploy of applications in weblogic server using weblogic wlst tool.
import getopt
... | files/appDeploymentScript.py | import sys
import os
import re
from java.lang import System
#Python Script to manage applications in weblogic server.
#This script takes input from command line and executes it.
#It can be used to check status,stop,start,deploy,undeploy of applications in weblogic server using weblogic wlst tool.
import getopt
... | 0.055663 | 0.076339 |
import sys
from nose.tools import assert_almost_equals, eq_
from unitbench import TimeSet, Benchmark, BenchResult, Reporter, CsvReporter
from unittest import TestCase
if sys.version_info < (3, 0):
from StringIO import StringIO
else:
from io import StringIO
class NullReporter(Reporter):
pass
... | tests/test_unitbench.py | import sys
from nose.tools import assert_almost_equals, eq_
from unitbench import TimeSet, Benchmark, BenchResult, Reporter, CsvReporter
from unittest import TestCase
if sys.version_info < (3, 0):
from StringIO import StringIO
else:
from io import StringIO
class NullReporter(Reporter):
pass
... | 0.432782 | 0.36557 |
import os, sys, re
from typing import List
class Node:
def __init__(self, pycore_dir: str, node_dir: str) -> None:
self.name = node_dir.split(".")[0]
self.path = "/tmp/{}/{}".format(pycore_dir, node_dir)
self.protocols = self._get_protocols()
def get_log_path(self, protocol: str) -> str:
return "{... | tools/logs.py | import os, sys, re
from typing import List
class Node:
def __init__(self, pycore_dir: str, node_dir: str) -> None:
self.name = node_dir.split(".")[0]
self.path = "/tmp/{}/{}".format(pycore_dir, node_dir)
self.protocols = self._get_protocols()
def get_log_path(self, protocol: str) -> str:
return "{... | 0.330579 | 0.136292 |
"""Tests for ranking_policy."""
from absl.testing import parameterized
import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import
from tf_agents.bandits.networks import global_and_arm_feature_network as arm_net
from tf_agents.bandits.policies import ranking_policy
from tf_agents.specs import band... | tf_agents/bandits/policies/ranking_policy_test.py |
"""Tests for ranking_policy."""
from absl.testing import parameterized
import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import
from tf_agents.bandits.networks import global_and_arm_feature_network as arm_net
from tf_agents.bandits.policies import ranking_policy
from tf_agents.specs import band... | 0.806396 | 0.569553 |
from dotenv import load_dotenv
from expertai.nlapi.cloud.client import ExpertAiClient
import os
import sys
import re
import tweepy
import json
# Load and set environment variables
load_dotenv()
# Load NLP API
client = ExpertAiClient()
# Authenticate and fetch tweets
auth = tweepy.OAuthHandler(os.getenv("consumer_key... | get_rating.py | from dotenv import load_dotenv
from expertai.nlapi.cloud.client import ExpertAiClient
import os
import sys
import re
import tweepy
import json
# Load and set environment variables
load_dotenv()
# Load NLP API
client = ExpertAiClient()
# Authenticate and fetch tweets
auth = tweepy.OAuthHandler(os.getenv("consumer_key... | 0.199698 | 0.106041 |
import os
import PySimpleGUIQt as sg
from multiprocessing import Process
from toolbox_creator.globe_icon import globe_icon
from toolbox_creator.function_window import create_function_window
from toolbox_creator.function_validation import validate_tool_list
from toolbox_creator.utils import get_list_of_keys
global wind... | toolbox_creator/gui.py | import os
import PySimpleGUIQt as sg
from multiprocessing import Process
from toolbox_creator.globe_icon import globe_icon
from toolbox_creator.function_window import create_function_window
from toolbox_creator.function_validation import validate_tool_list
from toolbox_creator.utils import get_list_of_keys
global wind... | 0.53777 | 0.174551 |
import configparser
import os
import redis
from ansible_collections.nordsec.team_password_manager.plugins.module_utils.manager import (
TeamPasswordManager,
CachingTeamPasswordManager,
BaseTeamPasswordManager
)
import tpm
ENV_VARIABLE_TPM_CONFIGURATION = "TPM_CONFIGURATION"
ENV_VARIABLE_TPM_CONFIGURATION_F... | plugins/module_utils/factory.py | import configparser
import os
import redis
from ansible_collections.nordsec.team_password_manager.plugins.module_utils.manager import (
TeamPasswordManager,
CachingTeamPasswordManager,
BaseTeamPasswordManager
)
import tpm
ENV_VARIABLE_TPM_CONFIGURATION = "TPM_CONFIGURATION"
ENV_VARIABLE_TPM_CONFIGURATION_F... | 0.309232 | 0.051942 |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context
from .models import Museo, Comentario, Museo_añadido, Seleccion
from .parser import parserXML
from django.views.decorators.csrf import csrf_exempt
from d... | guiamuseos/museos/views.py | from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context
from .models import Museo, Comentario, Museo_añadido, Seleccion
from .parser import parserXML
from django.views.decorators.csrf import csrf_exempt
from d... | 0.151718 | 0.052086 |
from __future__ import with_statement
import time
from . import portalocker
DEFAULT_TIMEOUT = 5
DEFAULT_CHECK_INTERVAL = 0.25
LOCK_METHOD = portalocker.LOCK_EX | portalocker.LOCK_NB
__all__ = [
'Lock',
'AlreadyLocked',
]
class AlreadyLocked(Exception):
pass
class Lock(object):
def __init__(
... | metasync/portalocker/utils.py | from __future__ import with_statement
import time
from . import portalocker
DEFAULT_TIMEOUT = 5
DEFAULT_CHECK_INTERVAL = 0.25
LOCK_METHOD = portalocker.LOCK_EX | portalocker.LOCK_NB
__all__ = [
'Lock',
'AlreadyLocked',
]
class AlreadyLocked(Exception):
pass
class Lock(object):
def __init__(
... | 0.636579 | 0.165458 |
import unittest
import pycompiler.util
from pycompiler.util import *
import os.path, sys, StringIO, types
class TestStack(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
def tearDown(self):
unittest.TestCase.tearDown(self)
def test_stack_push_an_i... | src/test/test_util.py |
import unittest
import pycompiler.util
from pycompiler.util import *
import os.path, sys, StringIO, types
class TestStack(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
def tearDown(self):
unittest.TestCase.tearDown(self)
def test_stack_push_an_i... | 0.348534 | 0.58059 |
from decouple import config
from imapclient import IMAPClient
import mailparser
from bs4 import BeautifulSoup
import pickle
import pandas as pd
import re
import numpy as np
from datetime import datetime
from dateutil import parser
import datefinder
import parsing
class dataExtraction:
"""Class that extracts all pr... | extractData.py | from decouple import config
from imapclient import IMAPClient
import mailparser
from bs4 import BeautifulSoup
import pickle
import pandas as pd
import re
import numpy as np
from datetime import datetime
from dateutil import parser
import datefinder
import parsing
class dataExtraction:
"""Class that extracts all pr... | 0.144903 | 0.065276 |
#
# # Intro
# In this tutorial we will execute a `dvmdostem` simulation from a Jupyter Notebook (IPython Notebook). The tutorial assumes:
# * You have built all the `dvmdostem` Docker images (see the comments and directions in the [Dockerfile](https://github.com/ua-snap/dvm-dos-tem/blob/master/Dockerfile) and [Docker... | scripts/docker-ipython-notebook-run.py |
#
# # Intro
# In this tutorial we will execute a `dvmdostem` simulation from a Jupyter Notebook (IPython Notebook). The tutorial assumes:
# * You have built all the `dvmdostem` Docker images (see the comments and directions in the [Dockerfile](https://github.com/ua-snap/dvm-dos-tem/blob/master/Dockerfile) and [Docker... | 0.800146 | 0.777088 |
import os, sys
import joblib
from copy import deepcopy
from typing import Optional, Dict, Tuple, List
import numpy as np
np.set_printoptions(precision=5, suppress=True)
import wfdb
import torch
from torch import nn
from scipy.signal import resample, resample_poly
from easydict import EasyDict as ED
from get_12ECG_fe... | official_phase_legacy/run_12ECG_classifier.py |
import os, sys
import joblib
from copy import deepcopy
from typing import Optional, Dict, Tuple, List
import numpy as np
np.set_printoptions(precision=5, suppress=True)
import wfdb
import torch
from torch import nn
from scipy.signal import resample, resample_poly
from easydict import EasyDict as ED
from get_12ECG_fe... | 0.6137 | 0.266378 |
import asyncio
from cleo import Command
from cleo.helpers import option
from netaudio.dante.browser import DanteBrowser
class SubscriptionAddCommand(Command):
name = "add"
description = "Add a subscription"
options = [
option("rx-channel-name", None, "Specify Rx channel by name", flag=False),
... | netaudio/console/commands/subscription/_add.py | import asyncio
from cleo import Command
from cleo.helpers import option
from netaudio.dante.browser import DanteBrowser
class SubscriptionAddCommand(Command):
name = "add"
description = "Add a subscription"
options = [
option("rx-channel-name", None, "Specify Rx channel by name", flag=False),
... | 0.41941 | 0.105763 |
from typing import List, Optional, Tuple, Type, overload
from ufdl.json.core.filter import FilterExpression
from ufdl.json.core.filter.field import Exact
from wai.json.object import OptionallyPresent, StrictJSONObject
from wai.json.object.property import (
BoolProperty,
NumberProperty,
StringProperty,
... | src/ufdl/jobtypes/standard/server/_PretrainedModel.py | from typing import List, Optional, Tuple, Type, overload
from ufdl.json.core.filter import FilterExpression
from ufdl.json.core.filter.field import Exact
from wai.json.object import OptionallyPresent, StrictJSONObject
from wai.json.object.property import (
BoolProperty,
NumberProperty,
StringProperty,
... | 0.91914 | 0.190573 |
{
"variables": {
"realm_node_build_as_library%": "0",
"realm_download_binaries%": "1"
},
"includes": [
"target_defaults.gypi",
"realm.gypi"
],
"targets": [
{
"target_name": "realm",
"dependencies": [
"object-store"
],
"sources": [
"src/node/platform.... | binding.gyp | {
"variables": {
"realm_node_build_as_library%": "0",
"realm_download_binaries%": "1"
},
"includes": [
"target_defaults.gypi",
"realm.gypi"
],
"targets": [
{
"target_name": "realm",
"dependencies": [
"object-store"
],
"sources": [
"src/node/platform.... | 0.476823 | 0.176352 |
from __main__ import qt, ctk, slicer
from GBMWizardStep import *
from Helper import *
""" PreprocessStep inherits from GBMWizardStep, with itself inherits
from a ctk workflow class.
"""
class PreprocessStep( GBMWizardStep ) :
def __init__( self, stepid ):
self.initialize( stepid )
self... | GBMWizard/GBMWizard_Lib/Preprocess.py | from __main__ import qt, ctk, slicer
from GBMWizardStep import *
from Helper import *
""" PreprocessStep inherits from GBMWizardStep, with itself inherits
from a ctk workflow class.
"""
class PreprocessStep( GBMWizardStep ) :
def __init__( self, stepid ):
self.initialize( stepid )
self... | 0.79732 | 0.238218 |
import base64
import random
import re
import httpx
from nonebot import get_driver
from nonebot.adapters import Bot, Event
from nonebot.adapters.cqhttp import MessageSegment, GROUP_ADMIN, GROUP_OWNER
from nonebot.permission import SUPERUSER
from nonebot.plugin import on_regex, on_command
from nonebot.typing import T_St... | src/plugins/eat/__init__.py | import base64
import random
import re
import httpx
from nonebot import get_driver
from nonebot.adapters import Bot, Event
from nonebot.adapters.cqhttp import MessageSegment, GROUP_ADMIN, GROUP_OWNER
from nonebot.permission import SUPERUSER
from nonebot.plugin import on_regex, on_command
from nonebot.typing import T_St... | 0.175044 | 0.0686 |
import Vars
import Offsets
import math
class Vector2 ():
x = 0
y = 0
xDir = ""
yDir = ""
class Player ():
type = "Player"
id = 0
x = 0
y = 0
xVel = 0
yVel = 0
damageTaken = 0
grounded = False
inAnimation = False
inStun = False
canAttack = False
jumpCount... | Player.py | import Vars
import Offsets
import math
class Vector2 ():
x = 0
y = 0
xDir = ""
yDir = ""
class Player ():
type = "Player"
id = 0
x = 0
y = 0
xVel = 0
yVel = 0
damageTaken = 0
grounded = False
inAnimation = False
inStun = False
canAttack = False
jumpCount... | 0.290377 | 0.241344 |
from .analyst.report import Report
from .analyst.draw_engine import DrawEngine
from .analyst.automated_suite import do_statistics
from .clockmaster import adjust_clock
from .datasource.log_engine import proceed as l_proceed
from .driver import Driver
from .utils import Report as ParserReport
from .workflow.engine impor... | workflow_parser/loader.py | from .analyst.report import Report
from .analyst.draw_engine import DrawEngine
from .analyst.automated_suite import do_statistics
from .clockmaster import adjust_clock
from .datasource.log_engine import proceed as l_proceed
from .driver import Driver
from .utils import Report as ParserReport
from .workflow.engine impor... | 0.41739 | 0.109706 |
import os
import yaml
import six
from pssh.exceptions import BadKeyNameError, MissingKeyError
if six.PY2:
from io import open
def get_user_configuration_path():
"""
Get the config path for the current user.
:rtype: Path to the config file (str)
"""
return os.path.normpath(os.path.expandus... | pssh/config.py |
import os
import yaml
import six
from pssh.exceptions import BadKeyNameError, MissingKeyError
if six.PY2:
from io import open
def get_user_configuration_path():
"""
Get the config path for the current user.
:rtype: Path to the config file (str)
"""
return os.path.normpath(os.path.expandus... | 0.581184 | 0.31384 |
from email.parser import Parser
from fabric.api import local, require, settings, task
from fabric.state import env
from jinja2 import Environment, FileSystemLoader
from termcolor import colored
from datetime import datetime
import app_config
# Other fabfiles
import assets
import boto.ses
import data
import flat
impo... | fabfile/__init__.py |
from email.parser import Parser
from fabric.api import local, require, settings, task
from fabric.state import env
from jinja2 import Environment, FileSystemLoader
from termcolor import colored
from datetime import datetime
import app_config
# Other fabfiles
import assets
import boto.ses
import data
import flat
impo... | 0.376279 | 0.079961 |
from collections.abc import MutableMapping
import json
import os.path
import pathlib
from typing import Any, Optional, Type, Union
import warnings
from weakref import proxy
class ProjectEncoder(json.JSONEncoder):
"""Make project parts serialisable on json dump"""
def default(self, obj):
if isinstance... | indirect/indirect.py | from collections.abc import MutableMapping
import json
import os.path
import pathlib
from typing import Any, Optional, Type, Union
import warnings
from weakref import proxy
class ProjectEncoder(json.JSONEncoder):
"""Make project parts serialisable on json dump"""
def default(self, obj):
if isinstance... | 0.782829 | 0.136695 |
import json
from unittest import TestCase
from unittest.mock import Mock
from main import AtonCore
class TestDrawingCards(TestCase):
def test_draw_cards_from_deck(self):
aton = AtonCore()
aton.red.deck = [1, 2, 3, 4, 4, 3, 2, 1]
aton.start()
self.assertEqual(aton.red.hand, [1, 2... | tests/tests_drawing_cards.py | import json
from unittest import TestCase
from unittest.mock import Mock
from main import AtonCore
class TestDrawingCards(TestCase):
def test_draw_cards_from_deck(self):
aton = AtonCore()
aton.red.deck = [1, 2, 3, 4, 4, 3, 2, 1]
aton.start()
self.assertEqual(aton.red.hand, [1, 2... | 0.558929 | 0.594728 |
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from .models import Infobox
import json
from .utils import *
default_fields = [ 'born', 'died', 'nationality', 'known for' ]
def render_search_result(inf... | wiki-index/server/infobox/views.py | from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from .models import Infobox
import json
from .utils import *
default_fields = [ 'born', 'died', 'nationality', 'known for' ]
def render_search_result(inf... | 0.375936 | 0.088505 |
import os
def test_001(settings, inspector):
"""
Sample doing depth imports
"""
sources = [
os.path.join(settings.sample_path, 'main_depth_import-1.scss'),
os.path.join(settings.sample_path, 'main_depth_import-2.scss'),
os.path.join(settings.sample_path, 'main_depth_import-3.sc... | tests/010_inspector/004_depth.py | import os
def test_001(settings, inspector):
"""
Sample doing depth imports
"""
sources = [
os.path.join(settings.sample_path, 'main_depth_import-1.scss'),
os.path.join(settings.sample_path, 'main_depth_import-2.scss'),
os.path.join(settings.sample_path, 'main_depth_import-3.sc... | 0.554229 | 0.336726 |
# Stdlib
from abc import ABCMeta, abstractmethod
# External
import capnp
# SCION
from lib.errors import SCIONParseError, SCIONTypeError
from lib.util import hex_str
class Serializable(object, metaclass=ABCMeta): # pragma: no cover
"""
Base class for all objects which serialize into raw bytes.
"""
d... | python/lib/packet/packet_base.py | # Stdlib
from abc import ABCMeta, abstractmethod
# External
import capnp
# SCION
from lib.errors import SCIONParseError, SCIONTypeError
from lib.util import hex_str
class Serializable(object, metaclass=ABCMeta): # pragma: no cover
"""
Base class for all objects which serialize into raw bytes.
"""
d... | 0.729616 | 0.236153 |
import config as cfg
from micro_image_large import ScanLinesMicroImage, BitMapMicroImage
from parasite import Parasite
from simulate_data import Simulator
import os
import numpy as np
if __name__ == "__main__":
session_name = "lab_sess"
'''
First, simulate some data using the Simulator class, upholding a... | main.py | import config as cfg
from micro_image_large import ScanLinesMicroImage, BitMapMicroImage
from parasite import Parasite
from simulate_data import Simulator
import os
import numpy as np
if __name__ == "__main__":
session_name = "lab_sess"
'''
First, simulate some data using the Simulator class, upholding a... | 0.425128 | 0.584805 |
import pandas as pd
import os
from os.path import join
import logging
from datetime import datetime
import sys
# TODO: Quota management
# TODO: Fix file not fond error
# TODO: Make filecount check - if 0 - do not continue
def get_export_files(directory):
"""
Return a list of UPCC export files from given dire... | Work/Parse_UPCC_Export.py | import pandas as pd
import os
from os.path import join
import logging
from datetime import datetime
import sys
# TODO: Quota management
# TODO: Fix file not fond error
# TODO: Make filecount check - if 0 - do not continue
def get_export_files(directory):
"""
Return a list of UPCC export files from given dire... | 0.122431 | 0.098729 |
from django.http.response import HttpResponse
from cart.models import Cart
from django.shortcuts import render, get_object_or_404, redirect
from .models import Product, Category, Contact
from django.contrib.auth.decorators import login_required
from django.template.loader import render_to_string
from django.http import... | ecom/views.py | from django.http.response import HttpResponse
from cart.models import Cart
from django.shortcuts import render, get_object_or_404, redirect
from .models import Product, Category, Contact
from django.contrib.auth.decorators import login_required
from django.template.loader import render_to_string
from django.http import... | 0.236164 | 0.116563 |
from .api import Api
from .types import *
class Client(object):
"""
Initializes the API for the client
:param token: Authorization token
:type token: str
:param headers: Additional headers **except Authorization**
:type headers: dict
"""
def __init__(self, token: str, headers=None):... | byte_api/client.py | from .api import Api
from .types import *
class Client(object):
"""
Initializes the API for the client
:param token: Authorization token
:type token: str
:param headers: Additional headers **except Authorization**
:type headers: dict
"""
def __init__(self, token: str, headers=None):... | 0.746971 | 0.218982 |
import sys, math, argparse
import os.path
import ConfigParser
from pymonetdb.sql.connections import Connection as connect
from pymonetdb.exceptions import Error as DBError
from gsm import utils as gu
from gsm.exceptions import GSMException
parser = argparse.ArgumentParser(prog='gsm')
parser.add_argument('--dbconf',... | gsm.py |
import sys, math, argparse
import os.path
import ConfigParser
from pymonetdb.sql.connections import Connection as connect
from pymonetdb.exceptions import Error as DBError
from gsm import utils as gu
from gsm.exceptions import GSMException
parser = argparse.ArgumentParser(prog='gsm')
parser.add_argument('--dbconf',... | 0.230313 | 0.050121 |
import re
from jinja2 import Template
from praw.models import Comment
import bot_logger
import crypto
import lang
import models
import user_function
# Resend tips to previously unregistered users that are now registered
def replay_pending_tip(reddit, tx_queue, failover_time):
# check if user have pending tips
... | bot_command.py | import re
from jinja2 import Template
from praw.models import Comment
import bot_logger
import crypto
import lang
import models
import user_function
# Resend tips to previously unregistered users that are now registered
def replay_pending_tip(reddit, tx_queue, failover_time):
# check if user have pending tips
... | 0.316053 | 0.07393 |
import os, sys
from AnyQt.QtWidgets import QSizePolicy, QStyle, QMessageBox, QFileDialog
from AnyQt.QtCore import QTimer
from Orange.misc import DistMatrix
from Orange.widgets import widget, gui
from Orange.data import get_sample_datasets_dir
from Orange.widgets.utils.filedialogs import RecentPathsWComboMixin
from Or... | orange3/Orange/widgets/unsupervised/owdistancefile.py | import os, sys
from AnyQt.QtWidgets import QSizePolicy, QStyle, QMessageBox, QFileDialog
from AnyQt.QtCore import QTimer
from Orange.misc import DistMatrix
from Orange.widgets import widget, gui
from Orange.data import get_sample_datasets_dir
from Orange.widgets.utils.filedialogs import RecentPathsWComboMixin
from Or... | 0.390476 | 0.101278 |
import json
import os
from aws_lambda_powertools import Logger, Tracer
from chalice import Chalice, ConvertToMiddleware, Cron
from chalicelib import Database
app = Chalice(app_name="bobotinho", debug=os.environ.get("DEBUG"))
logger = Logger(service=app.app_name)
tracer = Tracer(service=app.app_name)
app.register_mi... | app.py | import json
import os
from aws_lambda_powertools import Logger, Tracer
from chalice import Chalice, ConvertToMiddleware, Cron
from chalicelib import Database
app = Chalice(app_name="bobotinho", debug=os.environ.get("DEBUG"))
logger = Logger(service=app.app_name)
tracer = Tracer(service=app.app_name)
app.register_mi... | 0.581065 | 0.104067 |
import numpy as np
# Navigation Views
import navigation_vis.Raster as NavGridView
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib import cm as cm, pyplot as plt, colors as mplotcolors
def plot_grid_data_helper(data, ann=None, ann_sz=12, ann_col="black", title=None, grid=None, cmap=cm.viridis, ... | navigation_mdp/plotting.py | import numpy as np
# Navigation Views
import navigation_vis.Raster as NavGridView
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib import cm as cm, pyplot as plt, colors as mplotcolors
def plot_grid_data_helper(data, ann=None, ann_sz=12, ann_col="black", title=None, grid=None, cmap=cm.viridis, ... | 0.688992 | 0.465205 |
import types
import sys
from peval.core.callable import inspect_callable, Callable
def test_builtin_function():
assert inspect_callable(isinstance) == Callable(isinstance)
def test_builtin_constructor():
assert inspect_callable(str) == Callable(str, init=True)
def test_builtin_unbound_method():
assert ... | tests/test_core/test_callable.py | import types
import sys
from peval.core.callable import inspect_callable, Callable
def test_builtin_function():
assert inspect_callable(isinstance) == Callable(isinstance)
def test_builtin_constructor():
assert inspect_callable(str) == Callable(str, init=True)
def test_builtin_unbound_method():
assert ... | 0.340485 | 0.397646 |
import atexit
import traitlets
from traitlets.config.configurable import Configurable
class MotorController:
def __init__(self, channel, base_speed=400):
self.channel = channel
self.base_speed = float(base_speed)
self.power_stat = 0
def _set_motor_l_speed(self, motor_speed):
t... | jnmouse/motor.py | import atexit
import traitlets
from traitlets.config.configurable import Configurable
class MotorController:
def __init__(self, channel, base_speed=400):
self.channel = channel
self.base_speed = float(base_speed)
self.power_stat = 0
def _set_motor_l_speed(self, motor_speed):
t... | 0.408041 | 0.139367 |
import datetime
import decimal
import gzip
import logging
import os
from db_hammer.util.date import date_to_str
def get_headers(cursor):
col_names = cursor.description
cc = []
for c in col_names:
cc.append(c[0])
return cc
def count_rows(cursor, sql, log=None):
log = log or logging.getLo... | db_hammer/csv.py | import datetime
import decimal
import gzip
import logging
import os
from db_hammer.util.date import date_to_str
def get_headers(cursor):
col_names = cursor.description
cc = []
for c in col_names:
cc.append(c[0])
return cc
def count_rows(cursor, sql, log=None):
log = log or logging.getLo... | 0.14885 | 0.091342 |
import math
import pygame
from pygame.locals import *
DRAW_LETTERS = [chr(i) for i in range(65, 71)]
FORWARD_LETTERS = [chr(i) for i in range(71, 77)]
NON_CONSTRUCTION_LETTERS = DRAW_LETTERS + FORWARD_LETTERS
class LSystem:
'''
* A class for generating L-Systems from
* a given set of rule definitions.... | LSystem.py | import math
import pygame
from pygame.locals import *
DRAW_LETTERS = [chr(i) for i in range(65, 71)]
FORWARD_LETTERS = [chr(i) for i in range(71, 77)]
NON_CONSTRUCTION_LETTERS = DRAW_LETTERS + FORWARD_LETTERS
class LSystem:
'''
* A class for generating L-Systems from
* a given set of rule definitions.... | 0.425128 | 0.197232 |
from __future__ import print_function
import os
import tensorflow as tf
import tensorflow.contrib.keras as kr
from cnn_model import TCNNConfig, TextCNN
from data.cnews_loader import read_category, read_vocab
from rnn_model import TRNNConfig,TextRNN
try:
bool(type(unicode))
except NameError:
unicode = str
... | predict.py |
from __future__ import print_function
import os
import tensorflow as tf
import tensorflow.contrib.keras as kr
from cnn_model import TCNNConfig, TextCNN
from data.cnews_loader import read_category, read_vocab
from rnn_model import TRNNConfig,TextRNN
try:
bool(type(unicode))
except NameError:
unicode = str
... | 0.376394 | 0.112673 |
import logging
import threading
import serial
import serial.tools.list_ports
import fiber_reading
from collections import deque
def select_device():
"""User-provided serial device selector.
Args:
None
Returns:
The selected serial device as ListPortInfo.
"""
while True:
pr... | ui/serial_reader.py |
import logging
import threading
import serial
import serial.tools.list_ports
import fiber_reading
from collections import deque
def select_device():
"""User-provided serial device selector.
Args:
None
Returns:
The selected serial device as ListPortInfo.
"""
while True:
pr... | 0.58676 | 0.131145 |
# This could be quite useful...
from random import randrange
dice = []
running = True
class Die:
def __init__(self, number_of_sides, myname):
self.__number_of_sides = number_of_sides
self.myname = myname
def throw_dice(self):
return str(randrange(1, self.__number_of_sides))
def thro... | school_stuff/useless_programs/python/dice_manager/dice.py |
# This could be quite useful...
from random import randrange
dice = []
running = True
class Die:
def __init__(self, number_of_sides, myname):
self.__number_of_sides = number_of_sides
self.myname = myname
def throw_dice(self):
return str(randrange(1, self.__number_of_sides))
def thro... | 0.330039 | 0.191026 |
from lammps_data.bonds import extrapolate_periodic_bonds
from lammps_data.bonds import extrapolate_bonds
def test_zero_cell_vectors_should_give_same_bonds_with_nonperiodic():
cell_vectors = [[0] * 3] * 3
atoms = [(0, 0, 0, 1)]
assert extrapolate_bonds(atoms) == extrapolate_periodic_bonds(atoms, cell_vecto... | tests/test_extrapolate_periodic_bonds.py | from lammps_data.bonds import extrapolate_periodic_bonds
from lammps_data.bonds import extrapolate_bonds
def test_zero_cell_vectors_should_give_same_bonds_with_nonperiodic():
cell_vectors = [[0] * 3] * 3
atoms = [(0, 0, 0, 1)]
assert extrapolate_bonds(atoms) == extrapolate_periodic_bonds(atoms, cell_vecto... | 0.774413 | 0.857082 |
import numpy
from crystal_util import crystal_fh2, bragg_calc2
if __name__ == "__main__":
import sys
if len(sys.argv) > 1:
import argparse
parser = argparse.ArgumentParser(description='Calculation structure factor')
#args = parser.parse_args()
parser.add_argument('-n','--na... | yb66/calc_struct.py | import numpy
from crystal_util import crystal_fh2, bragg_calc2
if __name__ == "__main__":
import sys
if len(sys.argv) > 1:
import argparse
parser = argparse.ArgumentParser(description='Calculation structure factor')
#args = parser.parse_args()
parser.add_argument('-n','--na... | 0.193681 | 0.121738 |
import cartography.intel.aws.ec2
import cartography.intel.aws.iam
import tests.data.aws.ec2.instances
import tests.data.aws.iam
from cartography.util import run_analysis_job
TEST_ACCOUNT_ID = '000000000000'
TEST_REGION = 'us-east-1'
TEST_UPDATE_TAG = 123456789
def test_load_ec2_instances(neo4j_session, *args):
"... | tests/integration/cartography/intel/aws/ec2/test_ec2_instances.py | import cartography.intel.aws.ec2
import cartography.intel.aws.iam
import tests.data.aws.ec2.instances
import tests.data.aws.iam
from cartography.util import run_analysis_job
TEST_ACCOUNT_ID = '000000000000'
TEST_REGION = 'us-east-1'
TEST_UPDATE_TAG = 123456789
def test_load_ec2_instances(neo4j_session, *args):
"... | 0.5083 | 0.456955 |
from socket import getfqdn
import logging
import os
from datetime import datetime
DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S"
def format_body_request(
docker_image='',
dockerim_version=None,
registry_url='',
input_data={},
param_as_envar=True,
volume_mapping={},
queue... | ogcservice/celery_request.py | from socket import getfqdn
import logging
import os
from datetime import datetime
DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S"
def format_body_request(
docker_image='',
dockerim_version=None,
registry_url='',
input_data={},
param_as_envar=True,
volume_mapping={},
queue... | 0.432183 | 0.101367 |
from typing import List
from ball.pybullet_ball import PyBulletBall
from utils.button import Button
from utils.physics import get_force_vector
class PyBulletBallController:
def __init__(self, ball: PyBulletBall):
self.pybullet_client = ball.pybullet_client
self._ball = ball
self._set_rot... | ball/pybullet_ball_controller.py | from typing import List
from ball.pybullet_ball import PyBulletBall
from utils.button import Button
from utils.physics import get_force_vector
class PyBulletBallController:
def __init__(self, ball: PyBulletBall):
self.pybullet_client = ball.pybullet_client
self._ball = ball
self._set_rot... | 0.90387 | 0.272595 |
import json
import tempfile
import zipfile
from contextlib import contextmanager
from utils import (
codepipeline_lambda_handler,
create_zip_file,
get_artifact_s3_client,
get_cloudformation_template,
get_input_artifact_location,
get_output_artifact_location,
get_session,
get_user_parame... | modules/pipeline/prepare_deployment/lambda.py | import json
import tempfile
import zipfile
from contextlib import contextmanager
from utils import (
codepipeline_lambda_handler,
create_zip_file,
get_artifact_s3_client,
get_cloudformation_template,
get_input_artifact_location,
get_output_artifact_location,
get_session,
get_user_parame... | 0.455925 | 0.083516 |
from abc import ABC, abstractmethod
from typing import Callable, Dict, List, Tuple
import numpy as np
from showml.losses.base_loss import Loss
from showml.optimizers.base_optimizer import Optimizer
from showml.utils.dataset import Dataset
from showml.utils.model_utilities import generate_minibatches, initialize_params... | showml/linear_model/regression.py | from abc import ABC, abstractmethod
from typing import Callable, Dict, List, Tuple
import numpy as np
from showml.losses.base_loss import Loss
from showml.optimizers.base_optimizer import Optimizer
from showml.utils.dataset import Dataset
from showml.utils.model_utilities import generate_minibatches, initialize_params... | 0.976118 | 0.751124 |
import logging
import os
# Current wrappers version. Note that this is not the same as the Engine version.
WRAPPER_VERSION = '1.5.1'
# CHANGELOG:
# 1.5.1 (06 Jan 2022):
# - Minor fix to mod9-asr-switchboard-benchmark.
# 1.5.0 (06 Jan 2022):
# - Fixed handling of gs:// URIs in which the blob name requires per... | mod9/reformat/config.py | import logging
import os
# Current wrappers version. Note that this is not the same as the Engine version.
WRAPPER_VERSION = '1.5.1'
# CHANGELOG:
# 1.5.1 (06 Jan 2022):
# - Minor fix to mod9-asr-switchboard-benchmark.
# 1.5.0 (06 Jan 2022):
# - Fixed handling of gs:// URIs in which the blob name requires per... | 0.531209 | 0.12711 |
from magicbot import AutonomousStateMachine, state, feedback, timed_state
from components.Actuators.LowLevel.driveTrain import DriveTrain
from components.Input.colorSensor import ColorSensor
from components.Actuators.LowLevel.intakeMotor import IntakeMotor
from components.Actuators.HighLevel.hopperMotor import HopperMo... | autonomous/smokeTest.py | from magicbot import AutonomousStateMachine, state, feedback, timed_state
from components.Actuators.LowLevel.driveTrain import DriveTrain
from components.Input.colorSensor import ColorSensor
from components.Actuators.LowLevel.intakeMotor import IntakeMotor
from components.Actuators.HighLevel.hopperMotor import HopperMo... | 0.676406 | 0.38769 |
import serial
import time
ports = {
"fpga_in": "COM15",
"x_motor": "COM19",
}
fpga_in = serial.Serial(ports["fpga_in"], 115200)
x_motor = serial.Serial(ports["x_motor"], 9600, timeout=1)
fpga_in.name = "fpga_in"
x_motor.name = "x_motor"
def wait_then_write(interface, cmd, receive_interface=None):
if re... | init_x_motor.py | import serial
import time
ports = {
"fpga_in": "COM15",
"x_motor": "COM19",
}
fpga_in = serial.Serial(ports["fpga_in"], 115200)
x_motor = serial.Serial(ports["x_motor"], 9600, timeout=1)
fpga_in.name = "fpga_in"
x_motor.name = "x_motor"
def wait_then_write(interface, cmd, receive_interface=None):
if re... | 0.149376 | 0.099164 |
import tensorflow as tf
import os
import numpy as np
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.datasets.cifar import load_batch
def get_cifar10():
num_train_samples = 50000
x_train = np.empty((num_train_samples, 3, 32, 32), dtype='uint8')
y_train = np.empty((num_train_s... | src/models/train_cifar10.py | import tensorflow as tf
import os
import numpy as np
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.datasets.cifar import load_batch
def get_cifar10():
num_train_samples = 50000
x_train = np.empty((num_train_samples, 3, 32, 32), dtype='uint8')
y_train = np.empty((num_train_s... | 0.789031 | 0.417509 |
from os.path import join
from sklearn.externals import joblib
import sys
from grasping_position_inference.training.model_generator import generate_models
from grasping_position_inference.inference.model import Model
MODEL_PATH = 'models'
def get_probability_distribution_for_grid(x, y, model_name):
model_filepat... | __main__.py | from os.path import join
from sklearn.externals import joblib
import sys
from grasping_position_inference.training.model_generator import generate_models
from grasping_position_inference.inference.model import Model
MODEL_PATH = 'models'
def get_probability_distribution_for_grid(x, y, model_name):
model_filepat... | 0.385375 | 0.121399 |
from collections import defaultdict
from blockdiag.tests.utils import BuilderTestCase
class TestBuilderNode(BuilderTestCase):
def test_single_node_diagram(self):
diagram = self.build('single_node.diag')
self.assertEqual(1, len(diagram.nodes))
self.assertEqual(0, len(diagram.edges))
... | src/blockdiag/tests/test_builder_node.py |
from collections import defaultdict
from blockdiag.tests.utils import BuilderTestCase
class TestBuilderNode(BuilderTestCase):
def test_single_node_diagram(self):
diagram = self.build('single_node.diag')
self.assertEqual(1, len(diagram.nodes))
self.assertEqual(0, len(diagram.edges))
... | 0.797478 | 0.541773 |
# FIXME:
# - Too many buttons -- saving should be automatic?
# - Make purpose of 'Add' button clearer.
# - Indicate when the match was fuzzy in the buffer text.
import os
import threading
import urllib
from gi.repository import Gtk, GLib
from quodlibet import const
from quodlibet import qltk
from quodlibet import u... | stdlib2-src/dist-packages/quodlibet/qltk/lyrics.py |
# FIXME:
# - Too many buttons -- saving should be automatic?
# - Make purpose of 'Add' button clearer.
# - Indicate when the match was fuzzy in the buffer text.
import os
import threading
import urllib
from gi.repository import Gtk, GLib
from quodlibet import const
from quodlibet import qltk
from quodlibet import u... | 0.284179 | 0.082846 |
from urllib.parse import urljoin
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from ...text import create_slug
from ..magic import MisencodedCharField, MisencodedTextField
... | ddcz/models/used/users.py | from urllib.parse import urljoin
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from ...text import create_slug
from ..magic import MisencodedCharField, MisencodedTextField
... | 0.292595 | 0.08617 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import tensorflow as tf
import numpy as np
import queue
from tf_agents.environments import py_environment
from tf_agents.environments import tf_environment
from tf_agents.environments import tf_py_e... | racing_env.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import tensorflow as tf
import numpy as np
import queue
from tf_agents.environments import py_environment
from tf_agents.environments import tf_environment
from tf_agents.environments import tf_py_e... | 0.589716 | 0.169406 |
from abc import ABC, abstractmethod
class Conta(ABC):
def __init__(self, agencia, conta, saldo):
self._agencia = agencia
self._conta = conta
self._saldo = saldo
@property
def agencia(self):
return self._agencia
@property
def conta(self):
return self._conta... | Aulas/Python_Orientado_a_Objetos/Classes_Abstratas/exemplo_pratico.py | from abc import ABC, abstractmethod
class Conta(ABC):
def __init__(self, agencia, conta, saldo):
self._agencia = agencia
self._conta = conta
self._saldo = saldo
@property
def agencia(self):
return self._agencia
@property
def conta(self):
return self._conta... | 0.693992 | 0.180431 |
import os
import sys
import unittest
from selenium.common.exceptions import InvalidElementStateException
sys.path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
os.path.pardir)))
import base_test
class ElementClearTest(base_test.WebDriverBaseTest):
def te... | misc/webdriver-w3c-tests/user_input/clear_test.py |
import os
import sys
import unittest
from selenium.common.exceptions import InvalidElementStateException
sys.path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
os.path.pardir)))
import base_test
class ElementClearTest(base_test.WebDriverBaseTest):
def te... | 0.329284 | 0.212497 |
from __future__ import annotations
# stdlib
import logging
import re
from typing import Optional, Union, List, Iterable
# externals
import pandas as pd
import uproot
# tdub
import tdub.config
from tdub.data import (
Region,
avoids_for,
categorize_branches,
branches_from,
selection_branches,
... | src/tdub/frames.py |
from __future__ import annotations
# stdlib
import logging
import re
from typing import Optional, Union, List, Iterable
# externals
import pandas as pd
import uproot
# tdub
import tdub.config
from tdub.data import (
Region,
avoids_for,
categorize_branches,
branches_from,
selection_branches,
... | 0.883902 | 0.4206 |
import json
import requests
from django.shortcuts import redirect, render
from django.core.paginator import Paginator
from django.core.exceptions import SuspiciousOperation
from django.contrib import messages
from django.shortcuts import HttpResponse
from .models import *
from .forms import *
from django.http import Js... | tbr3App/views.py | import json
import requests
from django.shortcuts import redirect, render
from django.core.paginator import Paginator
from django.core.exceptions import SuspiciousOperation
from django.contrib import messages
from django.shortcuts import HttpResponse
from .models import *
from .forms import *
from django.http import Js... | 0.261708 | 0.055056 |
from importlib import resources
import pandas as pd
def load_bio_kdd04(as_frame: bool = False):
"""Load and return the higly imbalanced binary classification Protein Homology
Dataset from [KDD cup 2004](https://www.kdd.org/kdd-cup/view/kdd-cup-2004/Data).
This datasets include only bio_train.dat part of ... | pytorch_widedeep/datasets/_base.py | from importlib import resources
import pandas as pd
def load_bio_kdd04(as_frame: bool = False):
"""Load and return the higly imbalanced binary classification Protein Homology
Dataset from [KDD cup 2004](https://www.kdd.org/kdd-cup/view/kdd-cup-2004/Data).
This datasets include only bio_train.dat part of ... | 0.777215 | 0.73053 |
from icarus.clients.superclient import SuperClient
import speech_recognition as sr
from gtts import gTTS
import os
import platform
from playsound import playsound
from icarus.logging import icarus_logger
try:
from icarus.clients.WakeWordEngines.porcupine import Porcupine
except OSError:
icarus_logger.warning('T... | icarus/clients/speechclient.py | from icarus.clients.superclient import SuperClient
import speech_recognition as sr
from gtts import gTTS
import os
import platform
from playsound import playsound
from icarus.logging import icarus_logger
try:
from icarus.clients.WakeWordEngines.porcupine import Porcupine
except OSError:
icarus_logger.warning('T... | 0.272315 | 0.064772 |
#!/usr/bin/env python
import csv
import sys
import os
import datetime
import random
import re
import datetime
import logging
import openpyxl
from optparse import OptionParser
class GraphExcel:
def __init__(self, inputFilename, verbose=False):
self.logger = logging.getLogger('graph_excel')
self.rowSize = 0
... | src/GraphExcel.py |
#!/usr/bin/env python
import csv
import sys
import os
import datetime
import random
import re
import datetime
import logging
import openpyxl
from optparse import OptionParser
class GraphExcel:
def __init__(self, inputFilename, verbose=False):
self.logger = logging.getLogger('graph_excel')
self.rowSize = 0
... | 0.165458 | 0.10393 |
import time
from syndicate.commons.log_helper import get_logger
from syndicate.core import ClientError
from syndicate.core.helper import unpack_kwargs
from syndicate.core.resources.base_resource import BaseResource
from syndicate.core.resources.helper import build_description_obj
_LOG = get_logger('syndicate.core.res... | syndicate/core/resources/kinesis_resource.py | import time
from syndicate.commons.log_helper import get_logger
from syndicate.core import ClientError
from syndicate.core.helper import unpack_kwargs
from syndicate.core.resources.base_resource import BaseResource
from syndicate.core.resources.helper import build_description_obj
_LOG = get_logger('syndicate.core.res... | 0.416678 | 0.081264 |
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from .models import Snack
class ThingTests(TestCase) :
def setUp(self):
self.user = get_user_model().objects.create(
username = "tester", email = "<EMAIL>", password = "<PASSWORD>"
... | snacks/tests.py | from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from .models import Snack
class ThingTests(TestCase) :
def setUp(self):
self.user = get_user_model().objects.create(
username = "tester", email = "<EMAIL>", password = "<PASSWORD>"
... | 0.527317 | 0.267815 |
import numpy as np
import matplotlib.image as io
import matplotlib.pyplot as plt
alpha = 30
seedX = 998244353
seedY = 1000000007
''' First alpha = 5
oriFile = "qrcode.png"
waterMarkFile = "testwm.png"
outFile = "watermarked.png"
'''
''' Second alpha = 30
oriFile = "test.png"
waterMarkFile = "website.png"
outFile = "... | BlindWatermarkDFT/encode.py | import numpy as np
import matplotlib.image as io
import matplotlib.pyplot as plt
alpha = 30
seedX = 998244353
seedY = 1000000007
''' First alpha = 5
oriFile = "qrcode.png"
waterMarkFile = "testwm.png"
outFile = "watermarked.png"
'''
''' Second alpha = 30
oriFile = "test.png"
waterMarkFile = "website.png"
outFile = "... | 0.280912 | 0.608507 |
from os import path
import os
from datetime import datetime
import pandas as pd
proc_dir = 'processed'
file = ':dir/:year/AIS_:year_:month_Zone:zone.csv'
file_out = ':dir/:year/AIS_:year_:month.csv'
vessel_file = 'vessel_types.csv'
flag_file = 'maritime_vessel_identification.csv'
years = ['2015']
months = ['01', '02'... | ais_usa/ais/process_ais_files.py | from os import path
import os
from datetime import datetime
import pandas as pd
proc_dir = 'processed'
file = ':dir/:year/AIS_:year_:month_Zone:zone.csv'
file_out = ':dir/:year/AIS_:year_:month.csv'
vessel_file = 'vessel_types.csv'
flag_file = 'maritime_vessel_identification.csv'
years = ['2015']
months = ['01', '02'... | 0.203906 | 0.216177 |
from __future__ import absolute_import
from cssselect import GenericTranslator
from diazo import utils
from lxml import etree
from optparse import OptionParser
import logging
import sys
logger = logging.getLogger('diazo')
usage = __doc__
class LocationPathTranslator(GenericTranslator):
def xpath_descendant_co... | lib/diazo/cssrules.py | from __future__ import absolute_import
from cssselect import GenericTranslator
from diazo import utils
from lxml import etree
from optparse import OptionParser
import logging
import sys
logger = logging.getLogger('diazo')
usage = __doc__
class LocationPathTranslator(GenericTranslator):
def xpath_descendant_co... | 0.422147 | 0.088583 |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro... | nssrc/com/citrix/netscaler/nitro/resource/config/contentinspection/contentinspectioncallout.py |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro... | 0.678753 | 0.254578 |
from typing import List
import numpy
from deep_qa.data.data_indexer import DataIndexer
from deep_qa.data.instances.multiple_choice_qa.question_answer_instance import IndexedQuestionAnswerInstance
from deep_qa.data.instances.multiple_choice_qa.question_answer_instance import QuestionAnswerInstance
from ....common.test... | tests/data/instances/multiple_choice_qa/question_answer_instance_test.py | from typing import List
import numpy
from deep_qa.data.data_indexer import DataIndexer
from deep_qa.data.instances.multiple_choice_qa.question_answer_instance import IndexedQuestionAnswerInstance
from deep_qa.data.instances.multiple_choice_qa.question_answer_instance import QuestionAnswerInstance
from ....common.test... | 0.740737 | 0.631424 |
import attr
import json
import numpy as np
from text2qdmr.datasets.utils.extract_values import GroundingKey, ValueUnit
from text2qdmr.datasets.qdmr import QDMRStepArg
def to_dict_with_sorted_values(d, key=None):
return {k: sorted(v, key=key) for k, v in d.items()}
def to_dict_with_set_values(d):
result = {}... | text2qdmr/utils/serialization.py | import attr
import json
import numpy as np
from text2qdmr.datasets.utils.extract_values import GroundingKey, ValueUnit
from text2qdmr.datasets.qdmr import QDMRStepArg
def to_dict_with_sorted_values(d, key=None):
return {k: sorted(v, key=key) for k, v in d.items()}
def to_dict_with_set_values(d):
result = {}... | 0.531696 | 0.208108 |
from autoarray.plot import inversion_plotters, fit_interferometer_plotters
from autogalaxy.plot.mat_wrap import lensing_mat_plot, lensing_include, lensing_visuals
from autogalaxy.plot import plane_plotters
from autogalaxy.fit import fit_interferometer
class FitInterferometerPlotter(
fit_interferometer_plot... | autogalaxy/plot/fit_interferometer_plotters.py | from autoarray.plot import inversion_plotters, fit_interferometer_plotters
from autogalaxy.plot.mat_wrap import lensing_mat_plot, lensing_include, lensing_visuals
from autogalaxy.plot import plane_plotters
from autogalaxy.fit import fit_interferometer
class FitInterferometerPlotter(
fit_interferometer_plot... | 0.875814 | 0.44734 |
from re import match
from fit.record import TIMESTAMP_FIELD_NUM, TIMESTAMP_MASK, \
TIMESTAMP_FIELD_NAME
from fit.record.fields import Fields
from fit.types import Type
from fit.types.array import Array
from fit.types.dynamic import Dynamic
from fit.types.extended import LocalDateTime
from fit.utils import get_know... | fit/messages/__init__.py | from re import match
from fit.record import TIMESTAMP_FIELD_NUM, TIMESTAMP_MASK, \
TIMESTAMP_FIELD_NAME
from fit.record.fields import Fields
from fit.types import Type
from fit.types.array import Array
from fit.types.dynamic import Dynamic
from fit.types.extended import LocalDateTime
from fit.utils import get_know... | 0.732592 | 0.115088 |
load("@io_bazel_rules_docker//container:load.bzl", "container_load")
BUILD_BAZEL = """
java_import(
name = "server",
jars = ["buildfarm-server_deploy.jar"],
visibility = ["//visibility:public"],
)
java_import(
name = "worker",
jars = ["buildfarm-worker_deploy.jar"],
visibility = ["//visibility:... | farm/workspace.bzl | load("@io_bazel_rules_docker//container:load.bzl", "container_load")
BUILD_BAZEL = """
java_import(
name = "server",
jars = ["buildfarm-server_deploy.jar"],
visibility = ["//visibility:public"],
)
java_import(
name = "worker",
jars = ["buildfarm-worker_deploy.jar"],
visibility = ["//visibility:... | 0.468061 | 0.078008 |
import unittest
from LuckyNumbers import count
from typing import Dict, List
class TestLuckyNumbers(unittest.TestCase):
"""
All the unit tests of the lucky numbers program.
"""
def test_count_0(self):
"""
Tests the simplest case, with 0.
"""
self.assertEqual(count(0), ... | Communautaires/[UT] The lucky number.py | import unittest
from LuckyNumbers import count
from typing import Dict, List
class TestLuckyNumbers(unittest.TestCase):
"""
All the unit tests of the lucky numbers program.
"""
def test_count_0(self):
"""
Tests the simplest case, with 0.
"""
self.assertEqual(count(0), ... | 0.787768 | 0.836087 |
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class CreateUser(Document):
def before_save(self):
# CHECK SITE LIMIT OR DELETE USER WHEN USER RECORD
# [CREATE USER] WHEN USER IS NOT CREATED IN [USER] ------ ??????????????
create_user(self... | create_user/create_user/doctype/create_user/create_user.py |
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class CreateUser(Document):
def before_save(self):
# CHECK SITE LIMIT OR DELETE USER WHEN USER RECORD
# [CREATE USER] WHEN USER IS NOT CREATED IN [USER] ------ ??????????????
create_user(self... | 0.253676 | 0.074198 |
from provider.aws.all.command import All
from provider.aws.common_aws import generate_session, aws_verbose
from provider.aws.iot.command import Iot
from provider.aws.limit.command import Limit
from provider.aws.policy.command import Policy
from provider.aws.security.command import Security
from provider.aws.vpc.command... | cloudiscovery/provider/aws/command.py | from provider.aws.all.command import All
from provider.aws.common_aws import generate_session, aws_verbose
from provider.aws.iot.command import Iot
from provider.aws.limit.command import Limit
from provider.aws.policy.command import Policy
from provider.aws.security.command import Security
from provider.aws.vpc.command... | 0.434701 | 0.106319 |
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
import egg.core as core
from egg.core import ConsoleLogger
from egg.core.callbacks import WandbLogger
from egg.zoo.population_game.data import get_dataloader
from egg.zoo.populatio... | egg/zoo/population_game/train.py |
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
import egg.core as core
from egg.core import ConsoleLogger
from egg.core.callbacks import WandbLogger
from egg.zoo.population_game.data import get_dataloader
from egg.zoo.populatio... | 0.766468 | 0.338979 |
import os
import shutil
from time import sleep
import pytest
import yaml
from ap.topic_model.v1.TopicModelBase_pb2 import (
DocId,
Document,
DocumentPack,
ParallelDocIds,
)
from ap.topic_model.v1.TopicModelTrain_pb2 import (
AddDocumentsToModelRequest,
AddDocumentsToModelResponse,
StartTra... | tests/train/test_train_server.py | import os
import shutil
from time import sleep
import pytest
import yaml
from ap.topic_model.v1.TopicModelBase_pb2 import (
DocId,
Document,
DocumentPack,
ParallelDocIds,
)
from ap.topic_model.v1.TopicModelTrain_pb2 import (
AddDocumentsToModelRequest,
AddDocumentsToModelResponse,
StartTra... | 0.328637 | 0.216167 |
import os
import sentencepiece as spm
DATAFILE = '../data/pg16457.txt'
MODELDIR = 'models'
spm.SentencePieceTrainer.train(f'''\
--model_type=bpe\
--input={DATAFILE}\
--model_prefix={MODELDIR}/bpe\
--vocab_size=500''')
sp = spm.SentencePieceProcessor()
sp.load(os.path.join(MODELDIR, 'bpe.model'))
inp... | tokenization/bpe_tokenization.py | import os
import sentencepiece as spm
DATAFILE = '../data/pg16457.txt'
MODELDIR = 'models'
spm.SentencePieceTrainer.train(f'''\
--model_type=bpe\
--input={DATAFILE}\
--model_prefix={MODELDIR}/bpe\
--vocab_size=500''')
sp = spm.SentencePieceProcessor()
sp.load(os.path.join(MODELDIR, 'bpe.model'))
inp... | 0.51562 | 0.271481 |
import os
import sys
import random
import numpy as np
from PIL import Image
import h5py
from glob import glob
from tqdm import tqdm
class Dataset():
def __init__(self, h5_path, mode, img_width, img_height, img_dim, is_mem=True):
"""For inputting/outputting font images' dataset.
Use hdf5 files.
... | dataset.py | import os
import sys
import random
import numpy as np
from PIL import Image
import h5py
from glob import glob
from tqdm import tqdm
class Dataset():
def __init__(self, h5_path, mode, img_width, img_height, img_dim, is_mem=True):
"""For inputting/outputting font images' dataset.
Use hdf5 files.
... | 0.496094 | 0.271074 |
import json
import re
from io import BytesIO
from tabnanny import verbose
from urllib.parse import urlparse
import pandas as pd
import PyPDF2
from datasource.io import get_data_from_url
from datasource.utils import get_logger
# DEFINING GLOBAL VARIABLES
API_URL = "https://aides-territoires.beta.gouv.fr/api/aids/"
CR... | scripts/scrap_pdf_files.py | import json
import re
from io import BytesIO
from tabnanny import verbose
from urllib.parse import urlparse
import pandas as pd
import PyPDF2
from datasource.io import get_data_from_url
from datasource.utils import get_logger
# DEFINING GLOBAL VARIABLES
API_URL = "https://aides-territoires.beta.gouv.fr/api/aids/"
CR... | 0.531696 | 0.08819 |
import math
import os
import pytest
import torch
import pearl.bayesnet as bayesnet
import pearl.common as common
import pearl.nodes.categorical as categorical
import pearl.nodes.continuous as continuous
import pearl.nodes.deterministic as deterministic
ABS_TOL = 1e-4
def test_yaml_encoding_for_categorical_with_dir... | tests/serialization_test.py | import math
import os
import pytest
import torch
import pearl.bayesnet as bayesnet
import pearl.common as common
import pearl.nodes.categorical as categorical
import pearl.nodes.continuous as continuous
import pearl.nodes.deterministic as deterministic
ABS_TOL = 1e-4
def test_yaml_encoding_for_categorical_with_dir... | 0.708414 | 0.572783 |
import re
import subprocess
from ovs.log.logHandler import LogHandler
logger = LogHandler('extensions', name='exportfs')
class Nfsexports(object):
"""
Basic management for /etc/exports
"""
def __init__(self):
self._exportsFile = '/etc/exports'
self._cmd = ['/usr/bin/sudo', '-u', 'roo... | ovs/extensions/fs/exportfs.py |
import re
import subprocess
from ovs.log.logHandler import LogHandler
logger = LogHandler('extensions', name='exportfs')
class Nfsexports(object):
"""
Basic management for /etc/exports
"""
def __init__(self):
self._exportsFile = '/etc/exports'
self._cmd = ['/usr/bin/sudo', '-u', 'roo... | 0.299617 | 0.065366 |
import malaya
def test_pretrained_bayes_sentiment():
positive_text = 'Kerajaan negeri Kelantan mempersoalkan motif kenyataan Menteri Kewangan Lim Guan Eng yang hanya menyebut Kelantan penerima terbesar bantuan kewangan dari Kerajaan Persekutuan. Sedangkan menurut Timbalan Menteri Besarnya, Datuk <NAME> Nik Abdulla... | tests/test_sentiment.py | import malaya
def test_pretrained_bayes_sentiment():
positive_text = 'Kerajaan negeri Kelantan mempersoalkan motif kenyataan Menteri Kewangan Lim Guan Eng yang hanya menyebut Kelantan penerima terbesar bantuan kewangan dari Kerajaan Persekutuan. Sedangkan menurut Timbalan Menteri Besarnya, Datuk <NAME> Nik Abdulla... | 0.439747 | 0.433652 |
from .model_properties import String, Integer
from managers import *
class DjangorientBaseNode(type):
"""
Metaclass for Nodes & Edges
"""
def __new__(cls, name, bases, attrs):
#super(DjangorientBaseModel, cls).__new__(name, bases, attrs)
super_new = super(DjangorientBaseNode, cls).__new__
# DjangorientNode... | django_orientdb/models.py | from .model_properties import String, Integer
from managers import *
class DjangorientBaseNode(type):
"""
Metaclass for Nodes & Edges
"""
def __new__(cls, name, bases, attrs):
#super(DjangorientBaseModel, cls).__new__(name, bases, attrs)
super_new = super(DjangorientBaseNode, cls).__new__
# DjangorientNode... | 0.467332 | 0.091261 |
import numpy as np
class Flow(object):
def __new__(cls, *args, **kwargs):
"""
Creates a new Flow object.
:param argument 1: Timestepper object
:param argument 2: Vectorfield object
:param kwargs: Additional parameters accepted by the solver.
:return: Flow object.
... | liepack/flow/flow.py | import numpy as np
class Flow(object):
def __new__(cls, *args, **kwargs):
"""
Creates a new Flow object.
:param argument 1: Timestepper object
:param argument 2: Vectorfield object
:param kwargs: Additional parameters accepted by the solver.
:return: Flow object.
... | 0.709824 | 0.727776 |
from datetime import datetime
import functools
import os
import time
import sys
from schedule import run_all
# to import local fuctions
sys.path.insert(0, '../tools')
import schedule
from extract.earnings import extract_earnings
from extract.fundamentals import update_fundamental_dates, extract_fundamentals
from ext... | scheduler/scheduler.py | from datetime import datetime
import functools
import os
import time
import sys
from schedule import run_all
# to import local fuctions
sys.path.insert(0, '../tools')
import schedule
from extract.earnings import extract_earnings
from extract.fundamentals import update_fundamental_dates, extract_fundamentals
from ext... | 0.362292 | 0.153486 |
import numpy as np
from multiagent.core import World, Agent, Landmark
from multiagent.scenario import BaseScenario
class Scenario(BaseScenario):
def make_world(self):
world = World()
# world characteristics
world.dim_c = 2
num_agents = 3
world.num_agents = num_agents
... | multiagent/scenarios/formation.py | import numpy as np
from multiagent.core import World, Agent, Landmark
from multiagent.scenario import BaseScenario
class Scenario(BaseScenario):
def make_world(self):
world = World()
# world characteristics
world.dim_c = 2
num_agents = 3
world.num_agents = num_agents
... | 0.458349 | 0.464537 |
import sys
import os
import torch
from allennlp.data.iterators import BucketIterator
from allennlp.data.iterators import BasicIterator
from allennlp.modules.text_field_embedders import TextFieldEmbedder
import torch.optim as optim
from acsa.acsc_pytorch.my_allennlp_trainer import Trainer
from allennlp.data.vocabulary ... | acsa/acsc_pytorch/acsc_templates.py | import sys
import os
import torch
from allennlp.data.iterators import BucketIterator
from allennlp.data.iterators import BasicIterator
from allennlp.modules.text_field_embedders import TextFieldEmbedder
import torch.optim as optim
from acsa.acsc_pytorch.my_allennlp_trainer import Trainer
from allennlp.data.vocabulary ... | 0.466359 | 0.169406 |
from Muse_v2 import *
import struct
import json
import google.protobuf.internal.containers
import threading
import time
import Queue
class MuseProtoBufReaderV2(object):
def __init__(self, verbose):
self.events = []
self.__objects = []
self.__config_id = 0
self.thread_lock = thread... | src/proto_reader_v2.py | from Muse_v2 import *
import struct
import json
import google.protobuf.internal.containers
import threading
import time
import Queue
class MuseProtoBufReaderV2(object):
def __init__(self, verbose):
self.events = []
self.__objects = []
self.__config_id = 0
self.thread_lock = thread... | 0.407098 | 0.178812 |
from typing import List, Any, Union, Dict, Tuple
from numpy import ndarray
from sentence_transformers import SentenceTransformer, util
import torch
import pickle
from torch import Tensor
from models.models_tools import filter_data
from sklearn.cluster import AgglomerativeClustering
import sklearn.cluster
class Contex... | models/contextuals/sbert.py | from typing import List, Any, Union, Dict, Tuple
from numpy import ndarray
from sentence_transformers import SentenceTransformer, util
import torch
import pickle
from torch import Tensor
from models.models_tools import filter_data
from sklearn.cluster import AgglomerativeClustering
import sklearn.cluster
class Contex... | 0.949047 | 0.485356 |
from __future__ import print_function, unicode_literals
from telegrambot.api.base import APIObject
class ReplyKeyboardMarkup(APIObject):
"""
This object represents a custom keyboard with reply options.
keyboard Array of Array of String Array of button rows, each represented by an Array o... | telegrambot/api/keyboards.py | from __future__ import print_function, unicode_literals
from telegrambot.api.base import APIObject
class ReplyKeyboardMarkup(APIObject):
"""
This object represents a custom keyboard with reply options.
keyboard Array of Array of String Array of button rows, each represented by an Array o... | 0.696578 | 0.284554 |
from copy import copy
from unittest.mock import MagicMock
import pytest
import typing as t
from collections.abc import Callable
from tests.abc import BaseTestCase
from uzi import InjectorLookupError
from uzi.graph.nodes import MissingNode as Dependency, SimpleNode
from uzi.injectors import Injector
Dependency = De... | tests/graph/nodes/lookup_error_tests.py | from copy import copy
from unittest.mock import MagicMock
import pytest
import typing as t
from collections.abc import Callable
from tests.abc import BaseTestCase
from uzi import InjectorLookupError
from uzi.graph.nodes import MissingNode as Dependency, SimpleNode
from uzi.injectors import Injector
Dependency = De... | 0.808257 | 0.397792 |
import enum
from typing import Iterable, Optional, Tuple
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from database import BLOCKCHAIN, Database
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
import numpy as np
import csv
class ViewMode(enum.Enum):
ASCII_HISTOGRAM = "a... | view.py | import enum
from typing import Iterable, Optional, Tuple
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from database import BLOCKCHAIN, Database
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
import numpy as np
import csv
class ViewMode(enum.Enum):
ASCII_HISTOGRAM = "a... | 0.669853 | 0.357007 |