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 warnings
import sys
import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from get_data import read_params
import argparse
import... | src/train_evaluate.py | import os
import warnings
import sys
import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from get_data import read_params
import argparse
import... | 0.309858 | 0.15588 |
import random
import sys
from tensorflow import keras
import numpy as np
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import RMSprop
# ### Preparing the data
path = keras.utils.get_file(
"nietzsche.txt", origin="https://s3.amazonaws.com/text-... | docs/keras/p10_Deep_Learning_with_Python/Chapter_8/s81_text_generation_with_lstm.py |
import random
import sys
from tensorflow import keras
import numpy as np
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import RMSprop
# ### Preparing the data
path = keras.utils.get_file(
"nietzsche.txt", origin="https://s3.amazonaws.com/text-... | 0.516839 | 0.382372 |
import logging
import json
import re
import gzip
import socket
import ssl
import certifi
from StringIO import StringIO
import os
from uuid import UUID
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.info('Loading function...')
REGION = os.environ.get('region') or 'eu'
ENDPOINT = '{}.data.logs.insig... | le_cloudwatch.py | import logging
import json
import re
import gzip
import socket
import ssl
import certifi
from StringIO import StringIO
import os
from uuid import UUID
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.info('Loading function...')
REGION = os.environ.get('region') or 'eu'
ENDPOINT = '{}.data.logs.insig... | 0.255622 | 0.045692 |
import os
import sys
import json
import pprint
from datetime import datetime
from collections import OrderedDict
import click
# ----------------------------------------------------------------------------
# VERSION = '1.0.0' # Initial release
VERSION = '1.0.1' # Added -no-incept option
IDENT = 'cctconvert ' + VER... | cctconvert/cctconvert.py | import os
import sys
import json
import pprint
from datetime import datetime
from collections import OrderedDict
import click
# ----------------------------------------------------------------------------
# VERSION = '1.0.0' # Initial release
VERSION = '1.0.1' # Added -no-incept option
IDENT = 'cctconvert ' + VER... | 0.286968 | 0.077274 |
import django
import sys,os
rootpath = os.path.dirname(os.path.realpath(__file__)).replace("\\","/")
rootpath = rootpath.split("/apps")[0]
# print(rootpath)
syspath=sys.path
sys.path=[]
sys.path.append(rootpath) #指定搜索路径绝对目录
sys.path.extend([rootpath+i for i in os.listdir(rootpath) if i[0]!="."])#将工程目录下的一级目录添加到python搜索路... | AutotestWebD/apps/webportal/scripts/web_portal_openApi_interface_test.py | import django
import sys,os
rootpath = os.path.dirname(os.path.realpath(__file__)).replace("\\","/")
rootpath = rootpath.split("/apps")[0]
# print(rootpath)
syspath=sys.path
sys.path=[]
sys.path.append(rootpath) #指定搜索路径绝对目录
sys.path.extend([rootpath+i for i in os.listdir(rootpath) if i[0]!="."])#将工程目录下的一级目录添加到python搜索路... | 0.054638 | 0.090937 |
import os
from gi.repository import Gio, GLib, GObject, Gdk, Gtk, GdkPixbuf, Pango
from b8 import ui
DEFAULT_FILE_ATTRIBUTES = '*'
class FileListItem:
"""Item to go in the file list.
This is a thin wrapper over a Gio.FileInfo.
"""
def __init__(self, info: Gio.FileInfo, parent: Gio.File):
self.info =... | b8/files.py | import os
from gi.repository import Gio, GLib, GObject, Gdk, Gtk, GdkPixbuf, Pango
from b8 import ui
DEFAULT_FILE_ATTRIBUTES = '*'
class FileListItem:
"""Item to go in the file list.
This is a thin wrapper over a Gio.FileInfo.
"""
def __init__(self, info: Gio.FileInfo, parent: Gio.File):
self.info =... | 0.577734 | 0.134918 |
from catalyst.api import order_target_percent, record, symbol, cancel_order, get_open_orders
def initialize(context):
context.ASSET_NAME = 'USDT_ETH'
context.asset = symbol(context.ASSET_NAME)
# For all trading pairs in the poloniex bundle, the default denomination
# currently supported by ... | 2018_02_15_cryptocurrencies_trading/algorithms/shared/dynamic_rebalancing-1500964615447.py | from catalyst.api import order_target_percent, record, symbol, cancel_order, get_open_orders
def initialize(context):
context.ASSET_NAME = 'USDT_ETH'
context.asset = symbol(context.ASSET_NAME)
# For all trading pairs in the poloniex bundle, the default denomination
# currently supported by ... | 0.691706 | 0.445349 |
import re
from containers.collections.elementary.mappers.base import DefaultMapper
from containers.collections.elementary.mappers import MixedMapperCollector
class MapIterView(object):
def __init__(self, map_view, *args, **kwargs):
self._map_view = map_view
self.iter_loc = self._map_view.iterabl... | src/containers/collections/elementary/views/common.py | import re
from containers.collections.elementary.mappers.base import DefaultMapper
from containers.collections.elementary.mappers import MixedMapperCollector
class MapIterView(object):
def __init__(self, map_view, *args, **kwargs):
self._map_view = map_view
self.iter_loc = self._map_view.iterabl... | 0.815306 | 0.311244 |
import logging
from dbaas_credentials.models import CredentialType
from util import get_credentials_for
from util import full_stack
from dbaas_cloudstack.models import HostAttr
from dbaas_cloudstack.models import DatabaseInfraAttr
from dbaas_cloudstack.provider import CloudStackProvider
from workflow.steps.util.base im... | dbaas/workflow/steps/mysql/flipperfox_migration/create_secondary_ip.py | import logging
from dbaas_credentials.models import CredentialType
from util import get_credentials_for
from util import full_stack
from dbaas_cloudstack.models import HostAttr
from dbaas_cloudstack.models import DatabaseInfraAttr
from dbaas_cloudstack.provider import CloudStackProvider
from workflow.steps.util.base im... | 0.410166 | 0.055336 |
import copy
import numpy as np
from . import friendly_matrix as fm
__all__ = [
'moveaxis_A',
'moveaxis',
'swapaxes_A',
'swapaxes',
'transpose_A',
'transpose',
'concatenate_A',
'concatenate',
'stack_A',
'stack',
'vstack_A',
'vstack',
'hstack_A',
'hstack',
'fl... | src/friendly_matrix/operations.py | import copy
import numpy as np
from . import friendly_matrix as fm
__all__ = [
'moveaxis_A',
'moveaxis',
'swapaxes_A',
'swapaxes',
'transpose_A',
'transpose',
'concatenate_A',
'concatenate',
'stack_A',
'stack',
'vstack_A',
'vstack',
'hstack_A',
'hstack',
'fl... | 0.758153 | 0.647157 |
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('organizations', '0001_initial'),
migrations.swappable_depe... | rpas/migrations/0001_initial.py | from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('organizations', '0001_initial'),
migrations.swappable_depe... | 0.555797 | 0.130618 |
class Solution(object):
def suggestedProducts(self, products, searchWord):
def search(products, word):
l = 0
r = len(products)-1
n = len(word)
while l<=r:
m = (l+r)/2
if products[l].startswith(word): return getTop3(... | problems/search-suggestions-system.py | class Solution(object):
def suggestedProducts(self, products, searchWord):
def search(products, word):
l = 0
r = len(products)-1
n = len(word)
while l<=r:
m = (l+r)/2
if products[l].startswith(word): return getTop3(... | 0.374791 | 0.26195 |
from django.db import models
from django.contrib.postgres.fields import ArrayField
import random
# Crea la tabla de Autor la cual contiene información sobre los autores disponibles.
class Autor(models.Model):
name = models.CharField(max_length=30)
youtube = models.CharField(max_length=100)
twitter = models... | themyscira/models.py | from django.db import models
from django.contrib.postgres.fields import ArrayField
import random
# Crea la tabla de Autor la cual contiene información sobre los autores disponibles.
class Autor(models.Model):
name = models.CharField(max_length=30)
youtube = models.CharField(max_length=100)
twitter = models... | 0.504639 | 0.354712 |
import re
class ChapterRead(object):
def __init__(self, title, text_list, text, previous, list, next):
# 标题
self.__title = None
# 内容列表
self.__text_list = None
# 内容文字
self.__text = None
# 上一章节
self.__previous = None
# 章节目录
self.__list ... | bean/chapter_read.py | import re
class ChapterRead(object):
def __init__(self, title, text_list, text, previous, list, next):
# 标题
self.__title = None
# 内容列表
self.__text_list = None
# 内容文字
self.__text = None
# 上一章节
self.__previous = None
# 章节目录
self.__list ... | 0.291787 | 0.081119 |
"""utils_check_patterns - Check whether a given graph contains a given pattern"""
# =============================================================================
# Imports
# =============================================================================
import networkx as nx
from networkx.algorithms.isomorphism import Gr... | gicpg/utils_check_patterns.py | """utils_check_patterns - Check whether a given graph contains a given pattern"""
# =============================================================================
# Imports
# =============================================================================
import networkx as nx
from networkx.algorithms.isomorphism import Gr... | 0.819569 | 0.42471 |
import requests
from Tkinter import *
import ttk
import json
root = Tk()
root.title("Currency Converter")
root.geometry('800x250+0+0')
root.configure (background='black')
Title=Label(root, text="Currency Converter")
Title.config(font=('century gothic',(25)),bg='yellow',width=0,relief=RAISED)
Title.pack(expand=1, anch... | Final.py | import requests
from Tkinter import *
import ttk
import json
root = Tk()
root.title("Currency Converter")
root.geometry('800x250+0+0')
root.configure (background='black')
Title=Label(root, text="Currency Converter")
Title.config(font=('century gothic',(25)),bg='yellow',width=0,relief=RAISED)
Title.pack(expand=1, anch... | 0.182316 | 0.162314 |
import os
import re
import shutil
from csb.io import Shell
from csb.io import TempFolder
class ProcheckParser():
"""
Simple Prochceck Summary parser
"""
def __init__(self):
self.binary = 'procheck.scr'
self.acc = 2.0
def parse(self, fn):
"""
@param fn: sour... | csb/bio/io/procheck.py | import os
import re
import shutil
from csb.io import Shell
from csb.io import TempFolder
class ProcheckParser():
"""
Simple Prochceck Summary parser
"""
def __init__(self):
self.binary = 'procheck.scr'
self.acc = 2.0
def parse(self, fn):
"""
@param fn: sour... | 0.448426 | 0.261458 |
import os
import json
import pem
from Crypto.PublicKey import RSA
from jupyterhub.handlers import BaseHandler
from illumidesk.authenticators.utils import LTIUtils
from illumidesk.lti13.auth import get_jwk
class LTI13ConfigHandler(BaseHandler):
"""
Handles JSON configuration file for LTI 1.3
"""
a... | src/illumidesk/lti13/handlers.py | import os
import json
import pem
from Crypto.PublicKey import RSA
from jupyterhub.handlers import BaseHandler
from illumidesk.authenticators.utils import LTIUtils
from illumidesk.lti13.auth import get_jwk
class LTI13ConfigHandler(BaseHandler):
"""
Handles JSON configuration file for LTI 1.3
"""
a... | 0.419648 | 0.126407 |
import argparse
import numpy as np
from data import H, W
from PIL import Image, ImageDraw
import util as u
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--manifest-a', type=str, default='manifest',
help='filenames corresponding to emb... | debug_embedding_near_neighbours.py |
import argparse
import numpy as np
from data import H, W
from PIL import Image, ImageDraw
import util as u
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--manifest-a', type=str, default='manifest',
help='filenames corresponding to emb... | 0.297674 | 0.250151 |
from __future__ import print_function # pylint: disable=unused-variable
import os
import subprocess
import sys
import unittest
from coverage import Coverage
from deplytils.contexts.coverage import CoverageContext
class Checker(object):
"""
Object to make sure unittests pass, the appropriate coverage is
... | tests/run.py | from __future__ import print_function # pylint: disable=unused-variable
import os
import subprocess
import sys
import unittest
from coverage import Coverage
from deplytils.contexts.coverage import CoverageContext
class Checker(object):
"""
Object to make sure unittests pass, the appropriate coverage is
... | 0.456894 | 0.249433 |
from __future__ import unicode_literals
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 ... | src/rating/migrations/0001_initial.py | from __future__ import unicode_literals
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 ... | 0.619011 | 0.13969 |
import unittest
import tornado.httputil
from imbi import errors
class DefaultFunctionalityTests(unittest.TestCase):
def test_that_error_url_can_be_configured(self):
saved_error_url = errors.ERROR_URL
try:
errors.set_canonical_server('server.example.com')
err = errors.Appl... | tests/test_errors.py | import unittest
import tornado.httputil
from imbi import errors
class DefaultFunctionalityTests(unittest.TestCase):
def test_that_error_url_can_be_configured(self):
saved_error_url = errors.ERROR_URL
try:
errors.set_canonical_server('server.example.com')
err = errors.Appl... | 0.446977 | 0.281884 |
from __future__ import unicode_literals
from __future__ import absolute_import
import logging
import json
import requests
from pypuppetdb.errors import (
ImproperlyConfiguredError,
EmptyResponseError,
UnsupportedVersionError,
APIError,
)
log = logging.getLogger(__name__)
API_VERSIONS = {
2:... | pypuppetdb/api/__init__.py | from __future__ import unicode_literals
from __future__ import absolute_import
import logging
import json
import requests
from pypuppetdb.errors import (
ImproperlyConfiguredError,
EmptyResponseError,
UnsupportedVersionError,
APIError,
)
log = logging.getLogger(__name__)
API_VERSIONS = {
2:... | 0.885161 | 0.169681 |
from __future__ import annotations
import tempfile
import warnings
from abc import abstractmethod
from functools import reduce
from operator import iconcat
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, Iterable, Optional, Sequence, Union
from weakref import WeakKeyDictionary
from mesonic.backe... | src/mesonic/backend/backend_sc3nb.py | from __future__ import annotations
import tempfile
import warnings
from abc import abstractmethod
from functools import reduce
from operator import iconcat
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, Iterable, Optional, Sequence, Union
from weakref import WeakKeyDictionary
from mesonic.backe... | 0.794863 | 0.184915 |
from part1 import (
gamma_board,
gamma_busy_fields,
gamma_delete,
gamma_free_fields,
gamma_golden_move,
gamma_golden_possible,
gamma_move,
gamma_new,
)
"""
scenario: test_random_actions
uuid: 461268954
"""
"""
random actions, total chaos
"""
board = gamma_new(5, 8, 5, 8)
assert board is... | z2/part2/interactive/jm/random_fuzzy_arrows_1/461268954.py | from part1 import (
gamma_board,
gamma_busy_fields,
gamma_delete,
gamma_free_fields,
gamma_golden_move,
gamma_golden_possible,
gamma_move,
gamma_new,
)
"""
scenario: test_random_actions
uuid: 461268954
"""
"""
random actions, total chaos
"""
board = gamma_new(5, 8, 5, 8)
assert board is... | 0.807309 | 0.792745 |
import argparse
import os
import logging
import sys
import yaml
try:
# Try to use libyaml which is faster
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
# fall back on python implementation
from yaml import Loader, Dumper
def main(args):
logging.basicConfig(level=logging.DEBUG)
... | analysis/count_boolean_key.py | import argparse
import os
import logging
import sys
import yaml
try:
# Try to use libyaml which is faster
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
# fall back on python implementation
from yaml import Loader, Dumper
def main(args):
logging.basicConfig(level=logging.DEBUG)
... | 0.122195 | 0.092976 |
from django.shortcuts import render
from django.views.generic import View
from mail.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from . import constants
from django.http import HttpResponse,JsonResponse
from mail.utils.response_code import RETCODE
import random
# Create your views h... | mail/apps/verification/views.py | from django.shortcuts import render
from django.views.generic import View
from mail.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from . import constants
from django.http import HttpResponse,JsonResponse
from mail.utils.response_code import RETCODE
import random
# Create your views h... | 0.301465 | 0.062818 |
import numpy as np
import cv2
import json
from utils.imutils import crop
from torchvision.transforms import Normalize
import constants
import torch
def bbox_from_openpose(openpose_file, rescale=1.2, detection_thresh=0.2):
"""Get center and scale for bounding box from openpose detections."""
with open(openpose... | predict_preprocess.py | import numpy as np
import cv2
import json
from utils.imutils import crop
from torchvision.transforms import Normalize
import constants
import torch
def bbox_from_openpose(openpose_file, rescale=1.2, detection_thresh=0.2):
"""Get center and scale for bounding box from openpose detections."""
with open(openpose... | 0.684475 | 0.508666 |
from ctypes import util
import collections
import ctypes
import logging
import numpy
import os
import typing
# Package imports.
from .pynegf import PyNegf
from .version import __version__
class Settings(dict):
"""
A global setting dictionary.
"""
def __init__(self) -> None:
"""
Constru... | pynegf/__init__.py | from ctypes import util
import collections
import ctypes
import logging
import numpy
import os
import typing
# Package imports.
from .pynegf import PyNegf
from .version import __version__
class Settings(dict):
"""
A global setting dictionary.
"""
def __init__(self) -> None:
"""
Constru... | 0.740831 | 0.092852 |
import sys, os, json, time
from feature.cumulativePacket import generateFeature as generateCumulativePacketFeature
from feature.incomingPacketCount import generateFeature as generateIncomingPacketCountFeature
from feature.outgoingPacketCount import generateFeature as generateOutgoingPacketCountFeature
from feature.inc... | script/p1.py | import sys, os, json, time
from feature.cumulativePacket import generateFeature as generateCumulativePacketFeature
from feature.incomingPacketCount import generateFeature as generateIncomingPacketCountFeature
from feature.outgoingPacketCount import generateFeature as generateOutgoingPacketCountFeature
from feature.inc... | 0.111907 | 0.089893 |
# IDA libraries
import idaapi
import ida_kernwin
import ida_nalt
import idc
# Python modules
import os
import sys
class PatchManager(object):
def __init__(self):
self.patched_bytes = []
self.prev_addr = None
def generate(self):
idaapi.visit_patched_bytes(0, idaapi.BADADDR, self.get_... | genpatch.py |
# IDA libraries
import idaapi
import ida_kernwin
import ida_nalt
import idc
# Python modules
import os
import sys
class PatchManager(object):
def __init__(self):
self.patched_bytes = []
self.prev_addr = None
def generate(self):
idaapi.visit_patched_bytes(0, idaapi.BADADDR, self.get_... | 0.268749 | 0.10885 |
from torch import nn, cat
from torch.autograd import Variable
#ZDIMS is the bottleneck dimensions, i.e the dimensions of our latent space
ZDIMS=20
class Autoencoder(nn.Module):
def __init__(self,Zdims,input_dim):
super(Autoencoder, self).__init__()
# ENCODER
self.input_dim=input_dim
... | Groups/Group_ID_40/VCCA/autoencoder.py | from torch import nn, cat
from torch.autograd import Variable
#ZDIMS is the bottleneck dimensions, i.e the dimensions of our latent space
ZDIMS=20
class Autoencoder(nn.Module):
def __init__(self,Zdims,input_dim):
super(Autoencoder, self).__init__()
# ENCODER
self.input_dim=input_dim
... | 0.935729 | 0.488161 |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
import pandas
import time
import argparse
import numpy as np
from optimizationfns import MultiClassLM
from drllib import dynamic_models as models, utils, common
import torch
import torch.optim as optim
import torch.nn.functional a... | simulation/rl_train_ddpg.py | import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
import pandas
import time
import argparse
import numpy as np
from optimizationfns import MultiClassLM
from drllib import dynamic_models as models, utils, common
import torch
import torch.optim as optim
import torch.nn.functional a... | 0.479747 | 0.285496 |
import re, string, urllib.request, urllib.parse, urllib.error
"""
Various patterns I have encountered in looking for the babelfish result.
We try each of them in turn, based on the relative number of times I've
seen each of these patterns. $1.00 to anyone who can provide a heuristic
for knowing which one to use. Th... | tests/data23/recipe-64937.py | import re, string, urllib.request, urllib.parse, urllib.error
"""
Various patterns I have encountered in looking for the babelfish result.
We try each of them in turn, based on the relative number of times I've
seen each of these patterns. $1.00 to anyone who can provide a heuristic
for knowing which one to use. Th... | 0.344885 | 0.313788 |
import pytest
from flexmock import flexmock
from sqlalchemy.orm import Session
from clubelection.committee import Committee, CommitteeError
from clubelection.models import Voter, Ballot, Candidate, Vote
def test_should_not_count_ballot_and_raise_error_if_voter_has_already_voted():
voter: Voter = Voter('code', Tr... | tests/test_committee.py | import pytest
from flexmock import flexmock
from sqlalchemy.orm import Session
from clubelection.committee import Committee, CommitteeError
from clubelection.models import Voter, Ballot, Candidate, Vote
def test_should_not_count_ballot_and_raise_error_if_voter_has_already_voted():
voter: Voter = Voter('code', Tr... | 0.506103 | 0.350922 |
import functools
import json
import math
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import pdb
import random
import sys
import time
import warnings
import bert
import numpy as np
import pkg_resources
import tensorflow as tf
from bert import BertModelLayer
from bert.loader import (StockBertConfig, load_stock_... | cutcut/__init__.py | import functools
import json
import math
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import pdb
import random
import sys
import time
import warnings
import bert
import numpy as np
import pkg_resources
import tensorflow as tf
from bert import BertModelLayer
from bert.loader import (StockBertConfig, load_stock_... | 0.308294 | 0.132374 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Dict, List, Mapping, Optional, Tuple, Union
from .. import _utilities, _tables
from . import outputs
from ._inputs import *
__all__ = ['AccountIamMember']
class AccountIamMember(pulumi.CustomResource):
def __init__(__self__,
... | sdk/python/pulumi_gcp/billing/account_iam_member.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Dict, List, Mapping, Optional, Tuple, Union
from .. import _utilities, _tables
from . import outputs
from ._inputs import *
__all__ = ['AccountIamMember']
class AccountIamMember(pulumi.CustomResource):
def __init__(__self__,
... | 0.796886 | 0.069637 |
from trame.app import get_server
from trame.widgets import trame, vuetify, html, client
from trame.ui.vuetify import SinglePageLayout
from trame.ui.html import DivLayout
# -----------------------------------------------------------------------------
# Trame setup
# -----------------------------------------------------... | examples/validation/core/09_multi_layout.py | from trame.app import get_server
from trame.widgets import trame, vuetify, html, client
from trame.ui.vuetify import SinglePageLayout
from trame.ui.html import DivLayout
# -----------------------------------------------------------------------------
# Trame setup
# -----------------------------------------------------... | 0.358465 | 0.073663 |
from keras import layers
from keras import models
from keras import optimizers
from keras import callbacks
from keras.preprocessing.image import ImageDataGenerator
import os
import matplotlib.pyplot as plt
def make_small_cnn():
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', ... | 03_FineTuning/small_cnn.py | from keras import layers
from keras import models
from keras import optimizers
from keras import callbacks
from keras.preprocessing.image import ImageDataGenerator
import os
import matplotlib.pyplot as plt
def make_small_cnn():
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', ... | 0.857321 | 0.512876 |
import rospy
from geometry_msgs.msg import Wrench
from nav_msgs.msg import Odometry
from sensor_msgs.msg import LaserScan
import numpy as np
import tf
import nav_msgs.msg
class CarController:
def __init__(self):
rospy.init_node('mycar_controller')
self.time_last_plan = rospy.Time.now()
... | ros/src/bswarm/scripts/mycar_controller.py |
import rospy
from geometry_msgs.msg import Wrench
from nav_msgs.msg import Odometry
from sensor_msgs.msg import LaserScan
import numpy as np
import tf
import nav_msgs.msg
class CarController:
def __init__(self):
rospy.init_node('mycar_controller')
self.time_last_plan = rospy.Time.now()
... | 0.295027 | 0.18881 |
import json
import logging
import os
import pathlib
import re
from base64 import b64encode
from datetime import datetime, timedelta
from random import randint
from typing import Optional, Iterable
from urllib import parse
import requests
from platypush.config import Config
from platypush.context import get_backend
fr... | platypush/common/spotify/__init__.py | import json
import logging
import os
import pathlib
import re
from base64 import b64encode
from datetime import datetime, timedelta
from random import randint
from typing import Optional, Iterable
from urllib import parse
import requests
from platypush.config import Config
from platypush.context import get_backend
fr... | 0.705785 | 0.099733 |
import sys
sys.path.append("..")
from sklearn.svm import LinearSVC
from sklearn.feature_extraction.text import TfidfVectorizer as TF
from tesseract import evaluation, temporal, metrics, mock, viz
import CommonModules as CM
import numpy as np
from sklearn.model_selection import GridSearchCV
import pickle
def main():
... | masters/drebin_timeline.py | import sys
sys.path.append("..")
from sklearn.svm import LinearSVC
from sklearn.feature_extraction.text import TfidfVectorizer as TF
from tesseract import evaluation, temporal, metrics, mock, viz
import CommonModules as CM
import numpy as np
from sklearn.model_selection import GridSearchCV
import pickle
def main():
... | 0.194827 | 0.181953 |
members = dir(dict)
[m for m in members if not m.startswith('__')][4]
"""
Defining and iterating
"""
my_dict = {
'one': 1,
'two': 2,
'three': 3,
}
# .items() .keys() .values()
for k, v in my_dict.items():
print('key: ', k)
print('value: ', v)
# .keys() is nice for readability
"""
Handling JSON
"... | examples.py | members = dir(dict)
[m for m in members if not m.startswith('__')][4]
"""
Defining and iterating
"""
my_dict = {
'one': 1,
'two': 2,
'three': 3,
}
# .items() .keys() .values()
for k, v in my_dict.items():
print('key: ', k)
print('value: ', v)
# .keys() is nice for readability
"""
Handling JSON
"... | 0.361954 | 0.245571 |
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import astropy.units
__all__ = ['hide_existing_labels', 'calculate_axis_extent', 'calculate_extent', 'class_cmap']
def hide_existing_labels(plot_settings, axes=None, fig=None):
"""Hides labels for each dictionary provided if label alrea... | src/mcalf/utils/plot.py | import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import astropy.units
__all__ = ['hide_existing_labels', 'calculate_axis_extent', 'calculate_extent', 'class_cmap']
def hide_existing_labels(plot_settings, axes=None, fig=None):
"""Hides labels for each dictionary provided if label alrea... | 0.931898 | 0.848094 |
import logging
import traceback
import threading
import collections
from serial import Serial
from aci.aci_cmd import CommandPacket
from aci.aci_evt import event_deserialize
import queue
EVT_Q_BUF = 128
SEGGER_UART_BYTES_MAX = 63
class Device(object):
def __init__(self, device_name):
self.device_name = ... | nrf5_mesh/scripts/interactive_pyaci/aci/aci_uart.py |
import logging
import traceback
import threading
import collections
from serial import Serial
from aci.aci_cmd import CommandPacket
from aci.aci_evt import event_deserialize
import queue
EVT_Q_BUF = 128
SEGGER_UART_BYTES_MAX = 63
class Device(object):
def __init__(self, device_name):
self.device_name = ... | 0.399226 | 0.07603 |
from evennia.utils import logger
from muddery.server.commands.base_command import BaseCommand
from muddery.server.utils.localized_strings_handler import _
class CmdCombatInfo(BaseCommand):
"""
Get combat info.
Usage:
{"cmd":"combat_info",
"args":""
}
Observes your combat.
... | muddery/server/commands/combat.py | from evennia.utils import logger
from muddery.server.commands.base_command import BaseCommand
from muddery.server.utils.localized_strings_handler import _
class CmdCombatInfo(BaseCommand):
"""
Get combat info.
Usage:
{"cmd":"combat_info",
"args":""
}
Observes your combat.
... | 0.680666 | 0.128061 |
from math import ceil, floor
import numpy as np
import math
import plotly.express as px
import plotly.graph_objects as go
from my_project.global_scheme import template, mapping_dictionary, month_lst
def custom_heatmap(df, global_local, var, time_filter_info, data_filter_info):
"""Return the customizable heatmap.... | my_project/tab_data_explorer/charts_data_explorer.py | from math import ceil, floor
import numpy as np
import math
import plotly.express as px
import plotly.graph_objects as go
from my_project.global_scheme import template, mapping_dictionary, month_lst
def custom_heatmap(df, global_local, var, time_filter_info, data_filter_info):
"""Return the customizable heatmap.... | 0.789071 | 0.187244 |
from collections import abc, OrderedDict
from .line import Unknown, Dialogue, Movie, Command, Sound, Picture, Comment, Style
from .data import _Field
__all__ = (
'LineSection',
'FieldSection',
'EventsSection',
'StylesSection',
'ScriptInfoSection',
)
class LineSection(abc.MutableSequence):
FO... | ass/section.py | from collections import abc, OrderedDict
from .line import Unknown, Dialogue, Movie, Command, Sound, Picture, Comment, Style
from .data import _Field
__all__ = (
'LineSection',
'FieldSection',
'EventsSection',
'StylesSection',
'ScriptInfoSection',
)
class LineSection(abc.MutableSequence):
FO... | 0.705176 | 0.134548 |
import os
import unittest
from unittest.mock import patch, MagicMock, Mock
# Package
from emqxlwm2m.cmd2loop import ispath
import emqxlwm2m.cmd2loop
import emqxlwm2m.__main__ as cli
EP = "urn:imei:123"
TIMEOUT = 60
class TestIsPath(unittest.TestCase):
def test_ispath(self):
self.assertTrue(ispath("123")... | tests/test_cli.py | import os
import unittest
from unittest.mock import patch, MagicMock, Mock
# Package
from emqxlwm2m.cmd2loop import ispath
import emqxlwm2m.cmd2loop
import emqxlwm2m.__main__ as cli
EP = "urn:imei:123"
TIMEOUT = 60
class TestIsPath(unittest.TestCase):
def test_ispath(self):
self.assertTrue(ispath("123")... | 0.44071 | 0.472744 |
from .among import Among
from .basestemmer import BaseStemmer
class MaoriStemmer(BaseStemmer):
a_0 = [
Among(u"a", -1, 1),
Among(u"nga", 0, 1),
Among(u"ia", 0, 1),
Among(u"ngia", 2, 1),
Among(u"hia", 2, 1),
Among(u"whia", 4, 1),
Among(u"kia", 2, 1),
... | py_maori_stemmer/maori.py | from .among import Among
from .basestemmer import BaseStemmer
class MaoriStemmer(BaseStemmer):
a_0 = [
Among(u"a", -1, 1),
Among(u"nga", 0, 1),
Among(u"ia", 0, 1),
Among(u"ngia", 2, 1),
Among(u"hia", 2, 1),
Among(u"whia", 4, 1),
Among(u"kia", 2, 1),
... | 0.264928 | 0.41484 |
import base64
import copy
import mock
from novaclient import exceptions as nova_exception
from oslo_cache import core as cache_core
from oslo_config import cfg
import six
from ec2api import exception
from ec2api.metadata import api
from ec2api.tests.unit import base
from ec2api.tests.unit import fakes
from ec2api.te... | ec2-api-8.0.0/ec2api/tests/unit/test_metadata_api.py |
import base64
import copy
import mock
from novaclient import exceptions as nova_exception
from oslo_cache import core as cache_core
from oslo_config import cfg
import six
from ec2api import exception
from ec2api.metadata import api
from ec2api.tests.unit import base
from ec2api.tests.unit import fakes
from ec2api.te... | 0.334263 | 0.178597 |
data = (
'bols', # 0x00
'bolt', # 0x01
'bolp', # 0x02
'bolh', # 0x03
'bom', # 0x04
'bob', # 0x05
'bobs', # 0x06
'bos', # 0x07
'boss', # 0x08
'bong', # 0x09
'boj', # 0x0a
'boc', # 0x0b
'bok', # 0x0c
'bot', # 0x0d
'bop', # 0x0e
'boh', # 0x0f
'bwa', # 0x10
'bwag', # 0x... | env/lib/python3.8/site-packages/unidecode/x0bd.py | data = (
'bols', # 0x00
'bolt', # 0x01
'bolp', # 0x02
'bolh', # 0x03
'bom', # 0x04
'bob', # 0x05
'bobs', # 0x06
'bos', # 0x07
'boss', # 0x08
'bong', # 0x09
'boj', # 0x0a
'boc', # 0x0b
'bok', # 0x0c
'bot', # 0x0d
'bop', # 0x0e
'boh', # 0x0f
'bwa', # 0x10
'bwag', # 0x... | 0.054468 | 0.307079 |
from future import standard_library
standard_library.install_aliases()
from builtins import next
from builtins import map
from past.builtins import basestring
from .logger import Logger
import gevent
import gevent.pool
import urllib.parse
import time
import pymongo
import traceback
from .utils import LazyObject, load_c... | mrq/context.py | from future import standard_library
standard_library.install_aliases()
from builtins import next
from builtins import map
from past.builtins import basestring
from .logger import Logger
import gevent
import gevent.pool
import urllib.parse
import time
import pymongo
import traceback
from .utils import LazyObject, load_c... | 0.428712 | 0.107578 |
import pytest
from django.core.exceptions import ValidationError
from django.db.utils import IntegrityError
from playthrough.models import (
Guild, MetaRoleConfig, Series, RoleTemplate, Game, User, Channel,
GameConfig, Archive, Alias
)
from . import PlaythroughTestBase
from .utils import get_html_file
class... | playthrough/tests/test_models.py | import pytest
from django.core.exceptions import ValidationError
from django.db.utils import IntegrityError
from playthrough.models import (
Guild, MetaRoleConfig, Series, RoleTemplate, Game, User, Channel,
GameConfig, Archive, Alias
)
from . import PlaythroughTestBase
from .utils import get_html_file
class... | 0.540924 | 0.415254 |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.script import *
from test_framework.mininode import *
from test_framework.qtum import *
from test_framework.blocktools import *
from test_framework.key import *
import io
import time
# TestNode: A pee... | stratiX/stratisx-nothingatstake.py |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.script import *
from test_framework.mininode import *
from test_framework.qtum import *
from test_framework.blocktools import *
from test_framework.key import *
import io
import time
# TestNode: A pee... | 0.47171 | 0.176246 |
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form... | src/data/base.py |
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form... | 0.822082 | 0.090574 |
from __future__ import print_function
from __future__ import absolute_import
import os,sys
import tensorflow as tf
from ultra.ranking_model import BaseRankingModel
## encodr part the transformer is borrowed from https://www.tensorflow.org/tutorials/text/transformer
class MultiHeadAttention(tf.keras.layers.Layer):
... | ultra/ranking_model/Transformer.py | from __future__ import print_function
from __future__ import absolute_import
import os,sys
import tensorflow as tf
from ultra.ranking_model import BaseRankingModel
## encodr part the transformer is borrowed from https://www.tensorflow.org/tutorials/text/transformer
class MultiHeadAttention(tf.keras.layers.Layer):
... | 0.695648 | 0.266978 |
import numpy as np
import src.legendre as legendre
import src.functions as functions
class Quad:
def __init__(self, deg_t):
self.deg_t = deg_t
if deg_t == 0:
self.nodes1d = np.array([(1 - 1 / np.sqrt(3)) / 2., (1 + 1 / np.sqrt(3)) / 2.]) # Order 4
self.weights1d = np.a... | src/quad_legendre.py |
import numpy as np
import src.legendre as legendre
import src.functions as functions
class Quad:
def __init__(self, deg_t):
self.deg_t = deg_t
if deg_t == 0:
self.nodes1d = np.array([(1 - 1 / np.sqrt(3)) / 2., (1 + 1 / np.sqrt(3)) / 2.]) # Order 4
self.weights1d = np.a... | 0.693888 | 0.81812 |
import tensorflow as tf
class Donkey(object):
@staticmethod
def _preprocess(image):
image = tf.image.convert_image_dtype(image, dtype=tf.float32)
image = tf.multiply(tf.subtract(image, 0.5), 2)
image = tf.reshape(image, [64, 64, 3])
image = tf.random_crop(image, [54, 54, 3])
... | donkey.py | import tensorflow as tf
class Donkey(object):
@staticmethod
def _preprocess(image):
image = tf.image.convert_image_dtype(image, dtype=tf.float32)
image = tf.multiply(tf.subtract(image, 0.5), 2)
image = tf.reshape(image, [64, 64, 3])
image = tf.random_crop(image, [54, 54, 3])
... | 0.832509 | 0.414247 |
import sys
from argparse import ArgumentParser
from os import getcwd
from os.path import dirname, basename, join, isdir
import jinja2
from pynini.data import YamlDataLoader
from pynini.exceptions import SetupError
from pynini.utils import auto_str, as_python, as_json, as_yaml, filter_markdown_to_html, SimpleLog
from ... | pynini/setup.py | import sys
from argparse import ArgumentParser
from os import getcwd
from os.path import dirname, basename, join, isdir
import jinja2
from pynini.data import YamlDataLoader
from pynini.exceptions import SetupError
from pynini.utils import auto_str, as_python, as_json, as_yaml, filter_markdown_to_html, SimpleLog
from ... | 0.26322 | 0.084191 |
from googledevices.utils.const import DEFAULT_DEVICE_NAME, CASTPORT, CASTSECPORT, HEADERS
import googledevices.utils.log as log
from googledevices.helpers import gdh_request
class Info(object): # pylint: disable=R0902
"""A class for device info."""
def __init__(self, host, loop, session):
"""Initial... | googledevices/api/cast/info.py | from googledevices.utils.const import DEFAULT_DEVICE_NAME, CASTPORT, CASTSECPORT, HEADERS
import googledevices.utils.log as log
from googledevices.helpers import gdh_request
class Info(object): # pylint: disable=R0902
"""A class for device info."""
def __init__(self, host, loop, session):
"""Initial... | 0.779993 | 0.069668 |
import tempfile
from collections import defaultdict
from pathlib import Path
import os
from os.path import join
import json
import pytest
from unittest.mock import patch
from unittest.mock import MagicMock
import src.superannotate as sa
from src.superannotate.lib.core.entities.utils import CreationTypeEnum
from tests.... | tests/integration/annotations/test_annotations_pre_processing.py | import tempfile
from collections import defaultdict
from pathlib import Path
import os
from os.path import join
import json
import pytest
from unittest.mock import patch
from unittest.mock import MagicMock
import src.superannotate as sa
from src.superannotate.lib.core.entities.utils import CreationTypeEnum
from tests.... | 0.38445 | 0.227823 |
import tempfile
from io import BytesIO
from os import path
from pathlib import Path
from unittest import mock
import apsw
import pytest
from common.tests import factories
from exporter.sqlite import plan
from exporter.sqlite import tasks
from exporter.sqlite.runner import Runner
from workbaskets.validators import Wor... | exporter/tests/test_sqlite.py | import tempfile
from io import BytesIO
from os import path
from pathlib import Path
from unittest import mock
import apsw
import pytest
from common.tests import factories
from exporter.sqlite import plan
from exporter.sqlite import tasks
from exporter.sqlite.runner import Runner
from workbaskets.validators import Wor... | 0.675765 | 0.400222 |
__all__ = ['MLP', 'MLPv2']
# Cell
from typing import Any, Iterable, List, Optional, Tuple, Union, Callable
import os
import torch
from torch import nn
from .bases.common import PointModel
# Cell
class MLP(PairModel):
def __init__(self, n_users, n_items, embedding_dim, dropout=0.1):
super().__init__()
... | recohut/models/mlp.py |
__all__ = ['MLP', 'MLPv2']
# Cell
from typing import Any, Iterable, List, Optional, Tuple, Union, Callable
import os
import torch
from torch import nn
from .bases.common import PointModel
# Cell
class MLP(PairModel):
def __init__(self, n_users, n_items, embedding_dim, dropout=0.1):
super().__init__()
... | 0.963205 | 0.299598 |
from scheduler import KubeHTTPException
from scheduler.tests import TestCase
from scheduler.utils import generate_random_name
class PVCTest(TestCase):
"""Tests scheduler pod calls"""
def create(self, namespace=None, name=generate_random_name(), **kwargs):
"""
Helper function to create and ver... | rootfs/scheduler/tests/test_pvc.py | from scheduler import KubeHTTPException
from scheduler.tests import TestCase
from scheduler.utils import generate_random_name
class PVCTest(TestCase):
"""Tests scheduler pod calls"""
def create(self, namespace=None, name=generate_random_name(), **kwargs):
"""
Helper function to create and ver... | 0.703651 | 0.504883 |
import ctypes
import os
import sys
import numpy as np
import pyqtgraph as pg
import pyqtgraph.exporters
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QIcon, QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUiType
from scipy.integrate import solve_ivp
... | 02 Van der Pol oscilator/Van_der_Pol_Main.py |
import ctypes
import os
import sys
import numpy as np
import pyqtgraph as pg
import pyqtgraph.exporters
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QIcon, QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUiType
from scipy.integrate import solve_ivp
... | 0.374333 | 0.152726 |
import numpy as np
import tensorflow as tf
from tf_agents.agents import tf_agent
from tf_agents.agents.ppo import ppo_agent
from tf_agents.networks import actor_distribution_network
from tf_agents.networks import value_network
from tf_agents.specs import tensor_spec
from tf_agents.trajectories import time_step as ts
f... | tf_agents/train/ppo_learner_test_utils.py | import numpy as np
import tensorflow as tf
from tf_agents.agents import tf_agent
from tf_agents.agents.ppo import ppo_agent
from tf_agents.networks import actor_distribution_network
from tf_agents.networks import value_network
from tf_agents.specs import tensor_spec
from tf_agents.trajectories import time_step as ts
f... | 0.890818 | 0.393239 |
import os
from URL_Matching import URL_Matching_API
class Model_Ensembling:
# convert a file into result from image captioning based model
def cal_caption_result(self, caption_sim_wmd_file):
lines_caption_sim = []
with open(caption_sim_wmd_file) as f:
lines_caption_sim = f.readlines(... | src/Model_Ensembling.py | import os
from URL_Matching import URL_Matching_API
class Model_Ensembling:
# convert a file into result from image captioning based model
def cal_caption_result(self, caption_sim_wmd_file):
lines_caption_sim = []
with open(caption_sim_wmd_file) as f:
lines_caption_sim = f.readlines(... | 0.360489 | 0.392017 |
from .util import (
old_new_new,
DEFAULT_PIN,
DEFAULT_MANAGEMENT_KEY,
NON_DEFAULT_MANAGEMENT_KEY,
)
import re
import pytest
class TestManagementKey:
def test_change_management_key_force_fails_without_generate(self, ykman_cli):
with pytest.raises(SystemExit):
ykman_cli(
... | tests/device/cli/piv/test_management_key.py | from .util import (
old_new_new,
DEFAULT_PIN,
DEFAULT_MANAGEMENT_KEY,
NON_DEFAULT_MANAGEMENT_KEY,
)
import re
import pytest
class TestManagementKey:
def test_change_management_key_force_fails_without_generate(self, ykman_cli):
with pytest.raises(SystemExit):
ykman_cli(
... | 0.52342 | 0.364693 |
from random import choice
from jessy.modules import JessyModule, all_words
class DecisionMaker(JessyModule):
'''
Decision maker
'''
NAME = 'Decision maker'
DESCR = 'You can ask {0} to decide to do something or not'.format(NAME)
IS_SKILL = True
def __init__(self, *args, **kwargs):
... | jessy/modules/decideroulette.py |
from random import choice
from jessy.modules import JessyModule, all_words
class DecisionMaker(JessyModule):
'''
Decision maker
'''
NAME = 'Decision maker'
DESCR = 'You can ask {0} to decide to do something or not'.format(NAME)
IS_SKILL = True
def __init__(self, *args, **kwargs):
... | 0.427516 | 0.134833 |
import os
import sys
import re
import gtk
import keybinder
import ConfigParser
import gconf
try:
import dbus
from dbus.mainloop.glib import DBusGMainLoop
except: pass
class GSDesktop_Helper:
def __init__(self):
self._NAME = "GSDesktop Helper"
self._VERSION = "0.4.4"
self._AUTHORS = [
... | helper.py |
import os
import sys
import re
import gtk
import keybinder
import ConfigParser
import gconf
try:
import dbus
from dbus.mainloop.glib import DBusGMainLoop
except: pass
class GSDesktop_Helper:
def __init__(self):
self._NAME = "GSDesktop Helper"
self._VERSION = "0.4.4"
self._AUTHORS = [
... | 0.259826 | 0.057282 |
from Tkinter import *
import icmpfltr
class icmpfltcnsl:
def show(self,mainfrm):
txtfont=("FreeSerif", 11,"bold")
icmpfltfrm=Frame(mainfrm,relief=SOLID,borderwidth=1,bg="white")
#---------------Information text for ICMP console--------------------------
icmpflttxtfrm=Frame(icmpfltfrm,relief=SOLID,borderwid... | Firewall/icmpconsole.py | from Tkinter import *
import icmpfltr
class icmpfltcnsl:
def show(self,mainfrm):
txtfont=("FreeSerif", 11,"bold")
icmpfltfrm=Frame(mainfrm,relief=SOLID,borderwidth=1,bg="white")
#---------------Information text for ICMP console--------------------------
icmpflttxtfrm=Frame(icmpfltfrm,relief=SOLID,borderwid... | 0.119807 | 0.05921 |
import networkx as nx
import topside as top
def one_component_engine():
states = {
'static': {
(1, 2, 'A1'): 1,
(2, 1, 'A2'): 1
},
}
edges = [(1, 2, 'A1'), (2, 1, 'A2')]
c1 = top.PlumbingComponent('c1', states, edges)
mapping = {'c1': {1: 1, 2: 2}}
pr... | topside/visualization/tests/test_layout.py | import networkx as nx
import topside as top
def one_component_engine():
states = {
'static': {
(1, 2, 'A1'): 1,
(2, 1, 'A2'): 1
},
}
edges = [(1, 2, 'A1'), (2, 1, 'A2')]
c1 = top.PlumbingComponent('c1', states, edges)
mapping = {'c1': {1: 1, 2: 2}}
pr... | 0.614972 | 0.759047 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import src.visualizations.plot_utils as plt_utils
cp = plt_utils.custom_palette(n_colors=6)
init_df = pd.read_csv("data/processed/sf_data_processed.csv")
df = init_df.query("label == 'violent'").query("date >= '2013-01-01'"... | src/visualizations/heatmaps.py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import src.visualizations.plot_utils as plt_utils
cp = plt_utils.custom_palette(n_colors=6)
init_df = pd.read_csv("data/processed/sf_data_processed.csv")
df = init_df.query("label == 'violent'").query("date >= '2013-01-01'"... | 0.420362 | 0.495789 |
import numpy as np
import gym
import matplotlib.pyplot as plt
if __name__ == "__main__":
ENV = gym.make("FrozenLake-v0")
DISCOUNT = 0.9
EPSILON = 0.1
POSSIBLE_ACTIONS = [0, 1, 2, 3]
STATE_SPACE = list(range(16))
ESTIMATES = {}
RETURNS = {}
PAIRS_VISITED = {}
for state in STATE_SPAC... | Unit-6-The-Windy-Gridworld/frozen_lake.py | import numpy as np
import gym
import matplotlib.pyplot as plt
if __name__ == "__main__":
ENV = gym.make("FrozenLake-v0")
DISCOUNT = 0.9
EPSILON = 0.1
POSSIBLE_ACTIONS = [0, 1, 2, 3]
STATE_SPACE = list(range(16))
ESTIMATES = {}
RETURNS = {}
PAIRS_VISITED = {}
for state in STATE_SPAC... | 0.357904 | 0.343562 |
data = {
'slug': 'mimaropa',
'name': 'MIMAROPA',
'description': 'Southwestern Tagalog Region',
'provinces': {
'marinduque': {
'slug': 'marinduque',
'name': 'Marinduque',
'municipalities': {
'boac': {
'slug': 'boac',
... | phgeograpy/data/regions/mimaropa.py | data = {
'slug': 'mimaropa',
'name': 'MIMAROPA',
'description': 'Southwestern Tagalog Region',
'provinces': {
'marinduque': {
'slug': 'marinduque',
'name': 'Marinduque',
'municipalities': {
'boac': {
'slug': 'boac',
... | 0.315209 | 0.205197 |
import numpy as np
import csv
import ALL_REDUCTION_FACTORS_IRR as crop_P_IRR
import ALL_REDUCTION_FACTORS_RAIN as crop_P_RAIN
class SoilConstraints(object):
'''functions for soil qualities'''
def soil_qty_1_top(self, TXT_val, OC_val, pH_val, TEB_val):
TXT_intp = self.crop_P.TXT1_factor[... | code/SoilConstraints.py | import numpy as np
import csv
import ALL_REDUCTION_FACTORS_IRR as crop_P_IRR
import ALL_REDUCTION_FACTORS_RAIN as crop_P_RAIN
class SoilConstraints(object):
'''functions for soil qualities'''
def soil_qty_1_top(self, TXT_val, OC_val, pH_val, TEB_val):
TXT_intp = self.crop_P.TXT1_factor[... | 0.380183 | 0.128936 |
import socket
from typing import Any
class RedisTCPClient:
def __init__(self,
host: str,
port: int,
buffer_size: int=4096,
coding: str='utf-8') -> None:
self.host, self.port = host, port
self.buffer_size = buffer_size
sel... | RedisTCPClient.py |
import socket
from typing import Any
class RedisTCPClient:
def __init__(self,
host: str,
port: int,
buffer_size: int=4096,
coding: str='utf-8') -> None:
self.host, self.port = host, port
self.buffer_size = buffer_size
sel... | 0.708515 | 0.178848 |
from pyESController import *
import json
from dmonPerfMon import jsonToPerfMon
def asyncQuery(request, query, myIndex, ftype, fileName):
fileLoc = os.path.join(outDir, fileName)
if 'metrics' not in request.json['DMON'] or request.json['DMON']['metrics'] == " ":
start = time.time()
try:
... | src/dmonasyncquery.py | from pyESController import *
import json
from dmonPerfMon import jsonToPerfMon
def asyncQuery(request, query, myIndex, ftype, fileName):
fileLoc = os.path.join(outDir, fileName)
if 'metrics' not in request.json['DMON'] or request.json['DMON']['metrics'] == " ":
start = time.time()
try:
... | 0.190084 | 0.141726 |
import pytest
from hydra_slayer.registry import Registry
from .foobar import foo
from . import foobar as module
def test_add_function():
r = Registry()
r.add(foo)
assert "foo" in r._factories
def test_add_function_name_override():
r = Registry()
r.add(foo, name="bar")
assert "bar" in r.... | tests/test_registry.py | import pytest
from hydra_slayer.registry import Registry
from .foobar import foo
from . import foobar as module
def test_add_function():
r = Registry()
r.add(foo)
assert "foo" in r._factories
def test_add_function_name_override():
r = Registry()
r.add(foo, name="bar")
assert "bar" in r.... | 0.710327 | 0.574395 |
# Python Built-Ins:
import os
import subprocess
import threading
import time
# External Dependencies:
import boto3
from IPython.display import display, HTML
import ipywidgets as widgets
s3 = boto3.client("s3")
def upload_in_background(local_path: str, s3_uri: str, n_procs: int=0):
"""Utility function to asynchr... | migration_challenge_keras_image/util/nb.py |
# Python Built-Ins:
import os
import subprocess
import threading
import time
# External Dependencies:
import boto3
from IPython.display import display, HTML
import ipywidgets as widgets
s3 = boto3.client("s3")
def upload_in_background(local_path: str, s3_uri: str, n_procs: int=0):
"""Utility function to asynchr... | 0.369088 | 0.19521 |
import inspect
from enum import Enum
from typing import Callable, Dict, Iterable, List, Union
from .process import SimulationStage
def runtime_hook(stage, level="model", trigger="post"):
"""Decorator that allows to call a function or a method
at one or more specific times during a simulation.
The decora... | xsimlab/hook.py | import inspect
from enum import Enum
from typing import Callable, Dict, Iterable, List, Union
from .process import SimulationStage
def runtime_hook(stage, level="model", trigger="post"):
"""Decorator that allows to call a function or a method
at one or more specific times during a simulation.
The decora... | 0.89991 | 0.563978 |
from __future__ import unicode_literals
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 ... | operaQuizbot/migrations/0001_initial.py | from __future__ import unicode_literals
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 ... | 0.579281 | 0.12692 |
import musdb
import os
import numpy as np
import glob
from data.utils import load, write_wav
def get_musdbhq(database_path):
'''
Retrieve audio file paths for MUSDB HQ dataset
:param database_path: MUSDB HQ root directory
:return: dictionary with train and test keys, each containing list of samples, ... | data/musdb.py | import musdb
import os
import numpy as np
import glob
from data.utils import load, write_wav
def get_musdbhq(database_path):
'''
Retrieve audio file paths for MUSDB HQ dataset
:param database_path: MUSDB HQ root directory
:return: dictionary with train and test keys, each containing list of samples, ... | 0.406862 | 0.274364 |
import logging
import numpy
from pandas import DataFrame, Series, pivot_table
from scipy.spatial.distance import pdist, squareform
from scipy.cluster.hierarchy import *
from matplotlib import pyplot
from pylie.methods.methods import hlinkage_to_treematrix
from pylie.plotting import plot_matrix
from pylie.model.lieda... | pylie/model/scandataframe.py |
import logging
import numpy
from pandas import DataFrame, Series, pivot_table
from scipy.spatial.distance import pdist, squareform
from scipy.cluster.hierarchy import *
from matplotlib import pyplot
from pylie.methods.methods import hlinkage_to_treematrix
from pylie.plotting import plot_matrix
from pylie.model.lieda... | 0.909068 | 0.538498 |
import sys
import numpy as np
from scipy.stats import norm
import scipy.linalg
import setigen as stg
from setigen.funcs import func_utils
from . import factors
from . import ts_statistics
def find_nearest(arr, val):
"""
Return index of closest value.
"""
idx = (np.abs(np.array(arr) - val)).argmin()
... | blscint/gen_pdf.py | import sys
import numpy as np
from scipy.stats import norm
import scipy.linalg
import setigen as stg
from setigen.funcs import func_utils
from . import factors
from . import ts_statistics
def find_nearest(arr, val):
"""
Return index of closest value.
"""
idx = (np.abs(np.array(arr) - val)).argmin()
... | 0.321886 | 0.434941 |
import os
import requests
from bs4 import BeautifulSoup
defaultURL = "https://arca.live/"
placeHolder = {
"emoji": "body > div > div.content-wrapper.clearfix > article > div > div.article-wrapper > div.article-body",
"info": "body > div > div.content-wrapper.clearfix > article > div > div.article-wrapper > div... | main.py | import os
import requests
from bs4 import BeautifulSoup
defaultURL = "https://arca.live/"
placeHolder = {
"emoji": "body > div > div.content-wrapper.clearfix > article > div > div.article-wrapper > div.article-body",
"info": "body > div > div.content-wrapper.clearfix > article > div > div.article-wrapper > div... | 0.174938 | 0.172694 |
import requests
import re
import json
import os
from bs4 import BeautifulSoup
from scrap_urls import download_image
from os.path import join
protocol_and_domain = "http://www.fish.gov.au"
def scrape_urls(urls):
species_urls = get_species_urls(urls)
print("Number of species", len(species_urls))
return lis... | scraping/scrap_fish_gov_au.py | import requests
import re
import json
import os
from bs4 import BeautifulSoup
from scrap_urls import download_image
from os.path import join
protocol_and_domain = "http://www.fish.gov.au"
def scrape_urls(urls):
species_urls = get_species_urls(urls)
print("Number of species", len(species_urls))
return lis... | 0.244183 | 0.174498 |
import sqlite3
import pathlib
import os
DATABASE_PATH = pathlib.Path(__file__).parents[2].resolve().joinpath('database/')
def open_connection():
if not os.path.exists(DATABASE_PATH):
os.makedirs(DATABASE_PATH)
connection = sqlite3.connect(DATABASE_PATH.joinpath('missing_persons.db'))
cursor = co... | desaparecidos/handlers/database_handler.py | import sqlite3
import pathlib
import os
DATABASE_PATH = pathlib.Path(__file__).parents[2].resolve().joinpath('database/')
def open_connection():
if not os.path.exists(DATABASE_PATH):
os.makedirs(DATABASE_PATH)
connection = sqlite3.connect(DATABASE_PATH.joinpath('missing_persons.db'))
cursor = co... | 0.224395 | 0.063599 |
import contextlib
import os
import pathlib
import platform
import shutil
import stat
import sys
import time
import typing
from os import PathLike
from pathlib import Path
from typing import IO, Iterator, Optional, Union
import appdirs
import click
import requests
is_windows = platform.system() == "Windows"
site_path ... | ensureconda/cli.py | import contextlib
import os
import pathlib
import platform
import shutil
import stat
import sys
import time
import typing
from os import PathLike
from pathlib import Path
from typing import IO, Iterator, Optional, Union
import appdirs
import click
import requests
is_windows = platform.system() == "Windows"
site_path ... | 0.382257 | 0.092319 |
import datetime
import pytest
import univention.testing.udm as udm_test
from univention.admin.uexceptions import noObject
from univention.admin.uldap import access, getMachineConnection
from univention.config_registry import ConfigRegistry
ucr = ConfigRegistry()
ucr.load()
def test_license_acl_machine(create_lice... | udm-bildungslogin/ucs-test/97_bildungslogin_udm/004_acls.py |
import datetime
import pytest
import univention.testing.udm as udm_test
from univention.admin.uexceptions import noObject
from univention.admin.uldap import access, getMachineConnection
from univention.config_registry import ConfigRegistry
ucr = ConfigRegistry()
ucr.load()
def test_license_acl_machine(create_lice... | 0.294925 | 0.30641 |
# http://pytest.org/
# run py.test to run the tests (it magically finds things
# called test_blah and runs them)
from gsp import GSP
def test_mechanism():
num_slots = 4
slot_clicks = [1] * 4 # don't actually matter for gsp
bids = zip(range(1,6), [10, 12, 18, 14, 20])
reserve = 0
(alloc, payme... | pset5_code/test_gsp.py |
# http://pytest.org/
# run py.test to run the tests (it magically finds things
# called test_blah and runs them)
from gsp import GSP
def test_mechanism():
num_slots = 4
slot_clicks = [1] * 4 # don't actually matter for gsp
bids = zip(range(1,6), [10, 12, 18, 14, 20])
reserve = 0
(alloc, payme... | 0.571527 | 0.742678 |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('orderbasic', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(auto_creat... | orderbasic/migrations/0002_order.py |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('orderbasic', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(auto_creat... | 0.673943 | 0.281088 |
from django.conf import settings
DEFAULT_MEDIA_FILTERS = getattr(settings, 'DEFAULT_MEDIA_FILTERS', {
'ccss': 'mediagenerator.filters.clever.CleverCSS',
'coffee': 'mediagenerator.filters.coffeescript.CoffeeScript',
'css': (
'mediagenerator.filters.urlfix.UrlFixFilter',
'mediagenerator.filte... | mediagenerator/generators/bundles/settings.py | from django.conf import settings
DEFAULT_MEDIA_FILTERS = getattr(settings, 'DEFAULT_MEDIA_FILTERS', {
'ccss': 'mediagenerator.filters.clever.CleverCSS',
'coffee': 'mediagenerator.filters.coffeescript.CoffeeScript',
'css': (
'mediagenerator.filters.urlfix.UrlFixFilter',
'mediagenerator.filte... | 0.353986 | 0.083068 |
from Item import *
from Defense import *
import random
import string
def testAssignname_Defense(defense,name,numberofsum,num):
if(len(name) >= 5 and len(name) <= 32):
try:
#print (defense.getDefense())
assert defense.getDefense() == numberofsum
try:
assert defense.getName() == name
except (Asserti... | tests/test_Defense.py | from Item import *
from Defense import *
import random
import string
def testAssignname_Defense(defense,name,numberofsum,num):
if(len(name) >= 5 and len(name) <= 32):
try:
#print (defense.getDefense())
assert defense.getDefense() == numberofsum
try:
assert defense.getName() == name
except (Asserti... | 0.103211 | 0.382718 |
from authorship_unmasking.features.interfaces import ChunkSampler
from authorship_unmasking.input.interfaces import SamplePair
import random
from typing import Iterable, Tuple
class RandomOversampler(ChunkSampler):
"""
ChunkSampler for generating chunk pairs by random oversampling.
The larger set will b... | authorship_unmasking/features/sampling.py |
from authorship_unmasking.features.interfaces import ChunkSampler
from authorship_unmasking.input.interfaces import SamplePair
import random
from typing import Iterable, Tuple
class RandomOversampler(ChunkSampler):
"""
ChunkSampler for generating chunk pairs by random oversampling.
The larger set will b... | 0.737347 | 0.573469 |
import json
import os.path
import Biblioteca
from reportlab.pdfgen import canvas
# Grupo: <NAME>
# <NAME>
def main():
##lOGIN DO SISTEMA - id = admin / senha = <PASSWORD>
print("• Morais Lybrary •")
statusLogin = Biblioteca.loginSistema()
while True:
if statusLogin == True:
... | projetoBiblioteca/Main.py | import json
import os.path
import Biblioteca
from reportlab.pdfgen import canvas
# Grupo: <NAME>
# <NAME>
def main():
##lOGIN DO SISTEMA - id = admin / senha = <PASSWORD>
print("• Morais Lybrary •")
statusLogin = Biblioteca.loginSistema()
while True:
if statusLogin == True:
... | 0.067512 | 0.144571 |
# pylint: disable=unused-import, wrong-import-order
import neuralmonkey.checkpython
# pylint: enable=unused-import, wrong-import-order
import argparse
import os
import shlex
from shutil import copyfile
import sys
import traceback
from neuralmonkey.logging import log, debug
from neuralmonkey.experiment import Experim... | neuralmonkey/train.py |
# pylint: disable=unused-import, wrong-import-order
import neuralmonkey.checkpython
# pylint: enable=unused-import, wrong-import-order
import argparse
import os
import shlex
from shutil import copyfile
import sys
import traceback
from neuralmonkey.logging import log, debug
from neuralmonkey.experiment import Experim... | 0.236781 | 0.099077 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss, BCELoss
from transformers.models.bert.modeling_bert import BertModel
from transformers.models.bert.modeling_bert import BertPreTrainedModel
from transformers.models.roberta.modeling_roberta import RobertaModel
from... | models/model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss, BCELoss
from transformers.models.bert.modeling_bert import BertModel
from transformers.models.bert.modeling_bert import BertPreTrainedModel
from transformers.models.roberta.modeling_roberta import RobertaModel
from... | 0.914346 | 0.24044 |
from __future__ import print_function
import numpy as np
import math
import matplotlib.pyplot as plt
import pprint
def dijkstras(occupancy_map, x_spacing, y_spacing, start, goal):
"""
Implements Dijkstra's shortest path algorithm
Input:
occupancy_map - an N by M numpy array of boolean values (represent... | pathplanning/dijkstra.py | from __future__ import print_function
import numpy as np
import math
import matplotlib.pyplot as plt
import pprint
def dijkstras(occupancy_map, x_spacing, y_spacing, start, goal):
"""
Implements Dijkstra's shortest path algorithm
Input:
occupancy_map - an N by M numpy array of boolean values (represent... | 0.511229 | 0.701654 |