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 random
import torch
import pickle
import os
import numpy as np
import matplotlib.pyplot as plt
from collections import deque
from World import World
from dqn_agent import Agent
def main():
env = World()
agents = [Agent(state_size=env.observation_space, action_size=env.action_space, seed=0) for i in rang... | multiagent/train.py | import random
import torch
import pickle
import os
import numpy as np
import matplotlib.pyplot as plt
from collections import deque
from World import World
from dqn_agent import Agent
def main():
env = World()
agents = [Agent(state_size=env.observation_space, action_size=env.action_space, seed=0) for i in rang... | 0.498779 | 0.271306 |
import py, tempfile
from hippy.objspace import getspace
from hippy.phpcompiler import compile_php
from hippy.bytecode import unserialize
from hippy.bytecode_cache import BytecodeCache
from hippy.interpreter import get_printable_location
from testing.test_interpreter import MockInterpreter, BaseTestInterpreter
class T... | testing/test_bytecode.py | import py, tempfile
from hippy.objspace import getspace
from hippy.phpcompiler import compile_php
from hippy.bytecode import unserialize
from hippy.bytecode_cache import BytecodeCache
from hippy.interpreter import get_printable_location
from testing.test_interpreter import MockInterpreter, BaseTestInterpreter
class T... | 0.309128 | 0.421969 |
from __future__ import absolute_import
import re
# python 2 and python 3 compatibility library
import six
from typing import List, Optional
from .. import models
class SupportApi(object):
def __init__(self, api_client):
self.api_client = api_client
def api23_support_get_with_http_info(
sel... | pypureclient/flashblade/FB_2_3/api/support_api.py | from __future__ import absolute_import
import re
# python 2 and python 3 compatibility library
import six
from typing import List, Optional
from .. import models
class SupportApi(object):
def __init__(self, api_client):
self.api_client = api_client
def api23_support_get_with_http_info(
sel... | 0.886862 | 0.114171 |
from __future__ import absolute_import
import datetime
import re
import importlib
import six
from huaweicloudsdkcore.client import Client, ClientBuilder
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkcore.utils import http_utils
from huaweicloudsdkcore.sdk_stream_request import SdkStreamReq... | huaweicloud-sdk-osm/huaweicloudsdkosm/v2/osm_client.py |
from __future__ import absolute_import
import datetime
import re
import importlib
import six
from huaweicloudsdkcore.client import Client, ClientBuilder
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkcore.utils import http_utils
from huaweicloudsdkcore.sdk_stream_request import SdkStreamReq... | 0.556641 | 0.061819 |
from flask_restful import Resource, reqparse
from flask_jwt_extended import jwt_required
from ..models.order_model import order_obj
class FoodListResource(Resource):
parser = reqparse.RequestParser()
parser.add_argument("name",type=str,
required=True)
parser.add_argument("price",type=int,
req... | app/api/v1/resource/food.py | from flask_restful import Resource, reqparse
from flask_jwt_extended import jwt_required
from ..models.order_model import order_obj
class FoodListResource(Resource):
parser = reqparse.RequestParser()
parser.add_argument("name",type=str,
required=True)
parser.add_argument("price",type=int,
req... | 0.477798 | 0.091382 |
import hashlib
import io
import itertools
import os
import struct
from typing import Iterator, Tuple
def extract_object_files(archive_file: io.BufferedIOBase,
dest_dir: str) -> None:
"""Extracts object files from the archive path to the destination directory.
Extracts object files from t... | tensorflow/lite/ios/extract_object_files.py | import hashlib
import io
import itertools
import os
import struct
from typing import Iterator, Tuple
def extract_object_files(archive_file: io.BufferedIOBase,
dest_dir: str) -> None:
"""Extracts object files from the archive path to the destination directory.
Extracts object files from t... | 0.803714 | 0.293474 |
from cast.analysers import log
class SimpleInfoPrint:
"""
Interpreter showing how to collect statistical data
for the entire project.
The interpreter has to include the following
elements at least:
- An '__init__' method accepting a 'module' parameter. This 'module'
essentially r... | samples/analyzer_level/python/python.quality_rule/interpreters.py | from cast.analysers import log
class SimpleInfoPrint:
"""
Interpreter showing how to collect statistical data
for the entire project.
The interpreter has to include the following
elements at least:
- An '__init__' method accepting a 'module' parameter. This 'module'
essentially r... | 0.659295 | 0.540499 |
import dataclasses
import datetime
import pathlib
import sqlite3
import jinja2
import pandas
INDEX_TEMPLATE= "index.html"
@dataclasses.dataclass
class Record:
uid: int
name: str
time: str
bikes_available_to_rent: int
@dataclasses.dataclass
class Chart:
uid: int
name: str
labels: str
... | publisher.py | import dataclasses
import datetime
import pathlib
import sqlite3
import jinja2
import pandas
INDEX_TEMPLATE= "index.html"
@dataclasses.dataclass
class Record:
uid: int
name: str
time: str
bikes_available_to_rent: int
@dataclasses.dataclass
class Chart:
uid: int
name: str
labels: str
... | 0.439026 | 0.320768 |
import sys
import time
import random
import argparse
import matplotlib.pyplot as plt
import numpy as np
import onnxds.read_dataset as helper
import tenncor as tc
prog_description = 'Demo rbm trainer'
def mse_errfunc(x, visible_sample_):
return tc.api.reduce_mean(tc.api.square(x - visible_sample_))
def show_di... | demo/rbm_demo.py | import sys
import time
import random
import argparse
import matplotlib.pyplot as plt
import numpy as np
import onnxds.read_dataset as helper
import tenncor as tc
prog_description = 'Demo rbm trainer'
def mse_errfunc(x, visible_sample_):
return tc.api.reduce_mean(tc.api.square(x - visible_sample_))
def show_di... | 0.31216 | 0.299163 |
from typing import Optional, List
import numpy as np
import torch
from model.losses import CombinedNoisyLoss
def prepare_fp_targets(data_class, device):
targets = data_class.reshape((-1, 2, data_class.shape[-1] // 2))
ones = torch.ones(targets.shape)
present_targets = torch.where(targets > 0, ones, targ... | model/forward_passes.py | from typing import Optional, List
import numpy as np
import torch
from model.losses import CombinedNoisyLoss
def prepare_fp_targets(data_class, device):
targets = data_class.reshape((-1, 2, data_class.shape[-1] // 2))
ones = torch.ones(targets.shape)
present_targets = torch.where(targets > 0, ones, targ... | 0.937397 | 0.553385 |
from dataclasses import dataclass
import libkol
from .request import Request
from ..util import parsing
from ..Error import (
NotEnoughMeatError,
ItemNotFoundError,
UserIsIgnoringError,
LimitReachedError,
UnknownError,
)
@dataclass
class Response:
item: "libkol.Item"
quantity: int
mea... | libkol/request/mall_purchase.py | from dataclasses import dataclass
import libkol
from .request import Request
from ..util import parsing
from ..Error import (
NotEnoughMeatError,
ItemNotFoundError,
UserIsIgnoringError,
LimitReachedError,
UnknownError,
)
@dataclass
class Response:
item: "libkol.Item"
quantity: int
mea... | 0.626238 | 0.197909 |
import sys
from time import time
from typing import List, Tuple, Type
from .._scenario import Scenario
from ..events import (
ExceptionRaisedEvent,
ScenarioFailedEvent,
ScenarioPassedEvent,
ScenarioRunEvent,
ScenarioSkippedEvent,
StepFailedEvent,
StepPassedEvent,
StepRunEvent,
)
from ._... | vedro/core/_runner.py | import sys
from time import time
from typing import List, Tuple, Type
from .._scenario import Scenario
from ..events import (
ExceptionRaisedEvent,
ScenarioFailedEvent,
ScenarioPassedEvent,
ScenarioRunEvent,
ScenarioSkippedEvent,
StepFailedEvent,
StepPassedEvent,
StepRunEvent,
)
from ._... | 0.421314 | 0.194425 |
import argparse
UNK_IDX = 0
UNK_WORD = "UUUNKKK"
EVAL_YEAR = "2017"
BOS_IDX = 1
EOS_IDX = 2
MAX_GEN_LEN = 40
METEOR_JAR = 'evaluation/meteor-1.5.jar'
METEOR_DATA = 'evaluation/data/paraphrase-en.gz'
MULTI_BLEU_PERL = 'evaluation/multi-bleu.perl'
STANFORD_CORENLP = 'evaluation/stanford-corenlp-full-2018-10-05'
def st... | config.py | import argparse
UNK_IDX = 0
UNK_WORD = "UUUNKKK"
EVAL_YEAR = "2017"
BOS_IDX = 1
EOS_IDX = 2
MAX_GEN_LEN = 40
METEOR_JAR = 'evaluation/meteor-1.5.jar'
METEOR_DATA = 'evaluation/data/paraphrase-en.gz'
MULTI_BLEU_PERL = 'evaluation/multi-bleu.perl'
STANFORD_CORENLP = 'evaluation/stanford-corenlp-full-2018-10-05'
def st... | 0.486575 | 0.080033 |
from django.db import models
# Create your models here.
from django.contrib.auth.models import User
from tinymce.models import HTMLField
from pyuploadcare.dj.models import ImageField
class Profile(models.Model):
prof_pic = ImageField(blank=True, manual_crop='800x800')
bio = HTMLField()
user = models.OneTo... | neighbours/models.py | from django.db import models
# Create your models here.
from django.contrib.auth.models import User
from tinymce.models import HTMLField
from pyuploadcare.dj.models import ImageField
class Profile(models.Model):
prof_pic = ImageField(blank=True, manual_crop='800x800')
bio = HTMLField()
user = models.OneTo... | 0.590897 | 0.119562 |
import contextlib
import importlib
import os
import pathlib
import platform
import unittest
from unittest.mock import patch
import warnings
# Local imports ...
import glymur
from glymur import Jp2k
from . import fixtures
@contextlib.contextmanager
def chdir(dirname=None):
"""
This context manager restores th... | tests/test_config.py | import contextlib
import importlib
import os
import pathlib
import platform
import unittest
from unittest.mock import patch
import warnings
# Local imports ...
import glymur
from glymur import Jp2k
from . import fixtures
@contextlib.contextmanager
def chdir(dirname=None):
"""
This context manager restores th... | 0.468304 | 0.301208 |
from flask.ext.wtf import Form
from wtforms import (
BooleanField,
TextField,
PasswordField,
validators,
TextAreaField,
BooleanField,
SelectMultipleField,
widgets
)
from wtfrecaptcha.fields import RecaptchaField
from pani import app
from pani.forms.gvalidators import ValidPassword
fro... | pani/forms/__init__.py | from flask.ext.wtf import Form
from wtforms import (
BooleanField,
TextField,
PasswordField,
validators,
TextAreaField,
BooleanField,
SelectMultipleField,
widgets
)
from wtfrecaptcha.fields import RecaptchaField
from pani import app
from pani.forms.gvalidators import ValidPassword
fro... | 0.724773 | 0.130562 |
import unittest
import code
from code.baseline_network import BaselineNetwork
from code.network_utils import build_mlp, np2torch
from code.policy_gradient import PolicyGradient
from code.config import get_config
import gym
import numpy as np
import torch
import builtins
# Suppress unnecessary logging
# gym.logging.dis... | assignments/assignment3/starter_code_torch/tests/test_basic.py | import unittest
import code
from code.baseline_network import BaselineNetwork
from code.network_utils import build_mlp, np2torch
from code.policy_gradient import PolicyGradient
from code.config import get_config
import gym
import numpy as np
import torch
import builtins
# Suppress unnecessary logging
# gym.logging.dis... | 0.710929 | 0.422624 |
import roslib
import rospy
import tf
import cv2
from geometry_msgs.msg import Pose
from libs import *
import numpy as np
#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import String
import sys
import roslib
import rospy
import tf
import tf2_ros
import cv2
from geometry_... | tfbroadcasterstub.py | import roslib
import rospy
import tf
import cv2
from geometry_msgs.msg import Pose
from libs import *
import numpy as np
#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import String
import sys
import roslib
import rospy
import tf
import tf2_ros
import cv2
from geometry_... | 0.171234 | 0.063978 |
"""ROS Node to convert ranges to comprehensive laser scans."""
# Standard Imports
from math import radians
from functools import partial
# ROS imports
import rospy
from sensor_msgs.msg import Range, LaserScan
SENSOR_PREFIX = "navigation/proximity/"
RANGE_SENSORS = {
"short_range_ir/4": radians(-135),
"long... | src/pi_puck_driver/src/pi_puck_interoperability/range_merger.py | """ROS Node to convert ranges to comprehensive laser scans."""
# Standard Imports
from math import radians
from functools import partial
# ROS imports
import rospy
from sensor_msgs.msg import Range, LaserScan
SENSOR_PREFIX = "navigation/proximity/"
RANGE_SENSORS = {
"short_range_ir/4": radians(-135),
"long... | 0.90311 | 0.457985 |
import numpy as np
import matplotlib.pyplot as plt
import sdeint
from scipy.integrate import odeint
from mocu.utils.utils import *
from mocu.utils.costfunctions import *
from mocu.src.experimentaldesign import *
from mocu.src.mocu_utils import *
from mocu.scripts.visualizetoysystem import plot_points_in_full_space
from... | mocu/graphical_model/mocu/scripts/example_scaling.py | import numpy as np
import matplotlib.pyplot as plt
import sdeint
from scipy.integrate import odeint
from mocu.utils.utils import *
from mocu.utils.costfunctions import *
from mocu.src.experimentaldesign import *
from mocu.src.mocu_utils import *
from mocu.scripts.visualizetoysystem import plot_points_in_full_space
from... | 0.686475 | 0.483831 |
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from swagger_server.models.base_model_ import Model
from swagger_server import util
class LineupOverview(Model):
"""NOTE: This class is auto generated by the swagger code generat... | server/src/swagger_server/models/lineup_overview.py |
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from swagger_server.models.base_model_ import Model
from swagger_server import util
class LineupOverview(Model):
"""NOTE: This class is auto generated by the swagger code generat... | 0.798226 | 0.101189 |
from abc import ABC, abstractmethod
import re
from typing import List, Dict, get_type_hints
from pydoc import locate
from enum import Enum
from copy import deepcopy
class _DcopyCore(ABC):
_handlers = list()
SRC_ANNOTATION_ARG = 'src_annotation'
TGT_ANNOTATION_ARG = 'tgt_annotation'
@staticmethod
... | journey11/src/lib/dcopy/dccopy.py | from abc import ABC, abstractmethod
import re
from typing import List, Dict, get_type_hints
from pydoc import locate
from enum import Enum
from copy import deepcopy
class _DcopyCore(ABC):
_handlers = list()
SRC_ANNOTATION_ARG = 'src_annotation'
TGT_ANNOTATION_ARG = 'tgt_annotation'
@staticmethod
... | 0.7641 | 0.331214 |
import fpgrowth
import apriori
from time import time
from replace import Replace
try:
fhand = open("adult.data")
#fhand = open("adult.data")
except:
print('File cannot be open:', "adult.data")
quit()
while True:
print("1: Apriori")
print("2: Apriori-Improved")
print("3: FP-Growth")
... | run.py | import fpgrowth
import apriori
from time import time
from replace import Replace
try:
fhand = open("adult.data")
#fhand = open("adult.data")
except:
print('File cannot be open:', "adult.data")
quit()
while True:
print("1: Apriori")
print("2: Apriori-Improved")
print("3: FP-Growth")
... | 0.080199 | 0.228124 |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("marketing", "0001_initial"),
]
state_operations = [
migrations.CreateModel(
name="Messages",
fields=[
(
... | pyjobs/marketing/migrations/0002_auto_20191101_0912.py | from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("marketing", "0001_initial"),
]
state_operations = [
migrations.CreateModel(
name="Messages",
fields=[
(
... | 0.598899 | 0.156169 |
import os
from pywps import Process
from pywps import ComplexInput, ComplexOutput
from pywps import FORMATS
from pywps.app.Common import Metadata
from pywps.app.exceptions import ProcessError
from hummingbird.processing import ncdump, ncgen
import logging
LOGGER = logging.getLogger("PYWPS")
class NCDump(Process):
... | hummingbird/processes/wps_ncdump.py | import os
from pywps import Process
from pywps import ComplexInput, ComplexOutput
from pywps import FORMATS
from pywps.app.Common import Metadata
from pywps.app.exceptions import ProcessError
from hummingbird.processing import ncdump, ncgen
import logging
LOGGER = logging.getLogger("PYWPS")
class NCDump(Process):
... | 0.615897 | 0.140307 |
import numpy as np
from cs import CanonicalSystem
class TdwFormulation(object):
def __init__(self, ay=None, by=None):
# Parameters as defined in Schaal 2012
if ay is None: ay = 25.
self.ay = ay
if by is None: by = ay/4.
self.by = by
def acceleration(self, x, dx, ... | dmp_4.py | import numpy as np
from cs import CanonicalSystem
class TdwFormulation(object):
def __init__(self, ay=None, by=None):
# Parameters as defined in Schaal 2012
if ay is None: ay = 25.
self.ay = ay
if by is None: by = ay/4.
self.by = by
def acceleration(self, x, dx, ... | 0.767951 | 0.437824 |
import argparse
from pprint import pprint
import re
from typing import Dict
# 3rd party libs
from deepdiff import DeepDiff
import requests
from selenium import webdriver
NUM_ERRORS = 0
REGEX_N = re.compile(r"((\\n)|\s){1,5}")
MSG_CARD_HEAD = '//div[@id="root"]/main/section/div/div[5]/div/div/div['
MSG_CARD_TAIL = (
... | frontend/test/test_messages.py | import argparse
from pprint import pprint
import re
from typing import Dict
# 3rd party libs
from deepdiff import DeepDiff
import requests
from selenium import webdriver
NUM_ERRORS = 0
REGEX_N = re.compile(r"((\\n)|\s){1,5}")
MSG_CARD_HEAD = '//div[@id="root"]/main/section/div/div[5]/div/div/div['
MSG_CARD_TAIL = (
... | 0.285671 | 0.123736 |
import base64
from os import path
from docusign_click import AccountsApi, ClickwrapRequest, DisplaySettings, \
Document
from flask import session, request
from ....consts import demo_docs_path
from ....ds_config import DS_CONFIG
from ...utils import create_click_api_client
class Eg001Controller:
@staticmeth... | app/click/examples/eg001_create_clickwrap/controller.py | import base64
from os import path
from docusign_click import AccountsApi, ClickwrapRequest, DisplaySettings, \
Document
from flask import session, request
from ....consts import demo_docs_path
from ....ds_config import DS_CONFIG
from ...utils import create_click_api_client
class Eg001Controller:
@staticmeth... | 0.591369 | 0.116991 |
import json
import os
import sys
import csv
if len(sys.argv) <= 1:
print("Usage: python3 to_csv_one_label.py <label_name>")
print("sample usage: python3 to_csv_one_label.py math")
sys.exit(-1)
label_name = sys.argv[1]
features = [
"branch-misses_FEATURE_CONFIG",
"branch-misses_FEATURE_TYPE",
... | dataset/perf/small_to_csv_one_label.py | import json
import os
import sys
import csv
if len(sys.argv) <= 1:
print("Usage: python3 to_csv_one_label.py <label_name>")
print("sample usage: python3 to_csv_one_label.py math")
sys.exit(-1)
label_name = sys.argv[1]
features = [
"branch-misses_FEATURE_CONFIG",
"branch-misses_FEATURE_TYPE",
... | 0.126515 | 0.153169 |
import os
import os.path
import glob
import shutil
import pandas as pd
import torch
from torchsenti.datasets.utils import download_and_extract_archive
class TripAdvisor:
""" Trip Advisor <http://times.cs.uiuc.edu/~wang296/Data/> Dataset
Args:
root (string): Root directory of dataset where ``TripAd... | torchsenti/datasets/trip_advisor.py | import os
import os.path
import glob
import shutil
import pandas as pd
import torch
from torchsenti.datasets.utils import download_and_extract_archive
class TripAdvisor:
""" Trip Advisor <http://times.cs.uiuc.edu/~wang296/Data/> Dataset
Args:
root (string): Root directory of dataset where ``TripAd... | 0.483405 | 0.345823 |
import click
from .github import Organization, Repository, PullRequest
from .github.pull_request import print_pulls_table
@click.group(invoke_without_command=True)
@click.argument('organization')
@click.pass_context
def organization(ctx, organization):
"""Interactively work through an organization's pull request... | sweep/cli.py | import click
from .github import Organization, Repository, PullRequest
from .github.pull_request import print_pulls_table
@click.group(invoke_without_command=True)
@click.argument('organization')
@click.pass_context
def organization(ctx, organization):
"""Interactively work through an organization's pull request... | 0.275812 | 0.065965 |
from allennlp.predictors.predictor import Predictor
from util.message import message
import util.utilities as ut
from knowledge.knowledge_base import CKnowledgeBase
from NLP.agent import CAgent
# ------------------------------------------------------------------
INITIAL_MESSAGE = "What would you like to know about ... | NLP/query_engine.py |
from allennlp.predictors.predictor import Predictor
from util.message import message
import util.utilities as ut
from knowledge.knowledge_base import CKnowledgeBase
from NLP.agent import CAgent
# ------------------------------------------------------------------
INITIAL_MESSAGE = "What would you like to know about ... | 0.651355 | 0.153232 |
from collections import OrderedDict
from torch import nn
from maskrcnn_benchmark.modeling import registry
from maskrcnn_benchmark.modeling.make_layers import conv_with_kaiming_uniform
from . import fpn as fpn_module
from . import resnet
@registry.BACKBONES.register("R-50-C4")
@registry.BACKBONES.register("R-50-C5")... | examples/pytorch/fx/object_detection/maskrcnn/pytorch/maskrcnn_benchmark/modeling/backbone/backbone.py | from collections import OrderedDict
from torch import nn
from maskrcnn_benchmark.modeling import registry
from maskrcnn_benchmark.modeling.make_layers import conv_with_kaiming_uniform
from . import fpn as fpn_module
from . import resnet
@registry.BACKBONES.register("R-50-C4")
@registry.BACKBONES.register("R-50-C5")... | 0.840128 | 0.114492 |
import ibm_fn_helper as ifh
import argparse
from datetime import datetime
from ibm_botocore.exceptions import ClientError
import json
import os
from requests import HTTPError
import sys
OUTPUT_DIR_DESC=f'a directory to which output files will be written'
def cos_handle_file(cos_bucket, cos_file, batch_dir):
fi... | transient_vs_nwchem/python_clients/nwchem_cloud_output.py | import ibm_fn_helper as ifh
import argparse
from datetime import datetime
from ibm_botocore.exceptions import ClientError
import json
import os
from requests import HTTPError
import sys
OUTPUT_DIR_DESC=f'a directory to which output files will be written'
def cos_handle_file(cos_bucket, cos_file, batch_dir):
fi... | 0.217338 | 0.109801 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from ._enums import *
__all__ = [
'ActionArgs',
'ConditionArgs',
'ConditionFailingPeriodsArgs',
'DimensionArgs',
'ScheduledQueryRuleCriteriaArgs',
]
... | sdk/python/pulumi_azure_native/insights/v20210201preview/_inputs.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from ._enums import *
__all__ = [
'ActionArgs',
'ConditionArgs',
'ConditionFailingPeriodsArgs',
'DimensionArgs',
'ScheduledQueryRuleCriteriaArgs',
]
... | 0.912235 | 0.091626 |
apr = 206269.43 #radians to arcsec
def Dc(z, unit, cosmo):
"""
Input:
z: redshift
unit: distance unit in kpc, Mpc, ...
cosmo: dicitonary of cosmology parameters
Output:
res: comoving distance in unit as defined by variable 'unit'
"""
res = cosmo.comoving_distance(z... | src/astrild/rays/skys/lm_cfuncs.py |
apr = 206269.43 #radians to arcsec
def Dc(z, unit, cosmo):
"""
Input:
z: redshift
unit: distance unit in kpc, Mpc, ...
cosmo: dicitonary of cosmology parameters
Output:
res: comoving distance in unit as defined by variable 'unit'
"""
res = cosmo.comoving_distance(z... | 0.480479 | 0.568416 |
import json
import yaml
import torch
import wandb
import argparse
import numpy as np
from pathlib import Path
from pydantic import BaseSettings as _BaseSettings
from typing import TypeVar, Type, Union, Optional, Dict, Any
PathLike = Union[str, Path]
_T = TypeVar("_T")
def parse_args() -> argparse.Namespace:
pars... | mdlearn/utils.py | import json
import yaml
import torch
import wandb
import argparse
import numpy as np
from pathlib import Path
from pydantic import BaseSettings as _BaseSettings
from typing import TypeVar, Type, Union, Optional, Dict, Any
PathLike = Union[str, Path]
_T = TypeVar("_T")
def parse_args() -> argparse.Namespace:
pars... | 0.913919 | 0.297132 |
import random
import numpy as np
import gym
import revenius.gymenvs as gymenvs
from revenius.gymenvs.util import get_possible_acts
def random_walk(env, n_episode=5):
"""Execute random walk."""
env.reset()
for i_episode in range(n_episode):
observation = env.reset()
for t in range(100):
... | revenius/execute.py | import random
import numpy as np
import gym
import revenius.gymenvs as gymenvs
from revenius.gymenvs.util import get_possible_acts
def random_walk(env, n_episode=5):
"""Execute random walk."""
env.reset()
for i_episode in range(n_episode):
observation = env.reset()
for t in range(100):
... | 0.497803 | 0.411879 |
__________________________________________________________________________________________________
sample 468 ms submission
import math
class Solution:
def imageSmoother(self, M):
if not M:
return
row = len(M)
col = 0
if M[0]:
col = len(M[0])
copy = [... | Python3/661.py | __________________________________________________________________________________________________
sample 468 ms submission
import math
class Solution:
def imageSmoother(self, M):
if not M:
return
row = len(M)
col = 0
if M[0]:
col = len(M[0])
copy = [... | 0.314471 | 0.158956 |
import sys
from time import ticks_ms, ticks_diff, ticks_add
import logging
_logger = logging.getLogger("xasync")
# ============================================================================
# ===( XClosedReason )========================================================
# ========================================... | lib/micro_web_srv_2/libs/xasync_sockets.py |
import sys
from time import ticks_ms, ticks_diff, ticks_add
import logging
_logger = logging.getLogger("xasync")
# ============================================================================
# ===( XClosedReason )========================================================
# ========================================... | 0.441071 | 0.071203 |
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from future.builtins import * # noqa pylint: disable=W0401, W0614
from future.builtins.disabled import * # noqa pylint: disable=W0401, W0614
# === End Python 2/3 compatibility
import math
import numpy as np... | cora/util/cosmology.py | from __future__ import (absolute_import, division,
print_function, unicode_literals)
from future.builtins import * # noqa pylint: disable=W0401, W0614
from future.builtins.disabled import * # noqa pylint: disable=W0401, W0614
# === End Python 2/3 compatibility
import math
import numpy as np... | 0.938548 | 0.588475 |
import pandas as pd
class BayesNet():
"""
This class represents a Bayesian network.
It can read files in a .bif format (if the formatting is
along the lines of http://www.bnlearn.com/bnrepository/)
Uses pandas DataFrames for representing conditional probability tables
"""
def __init__(sel... | read_bayesnet.py | import pandas as pd
class BayesNet():
"""
This class represents a Bayesian network.
It can read files in a .bif format (if the formatting is
along the lines of http://www.bnlearn.com/bnrepository/)
Uses pandas DataFrames for representing conditional probability tables
"""
def __init__(sel... | 0.776326 | 0.484929 |
import textwrap
import pytest
import libqtile.config
import libqtile.widget.bluetooth
from libqtile.bar import Bar
from libqtile.config import Screen
from test.helpers import Retry
@Retry(ignore_exceptions=(AssertionError,))
def clipboard_cleared(widget):
assert widget.info()["text"] == ""
@pytest.fixture
def... | test/widgets/test_clipboard.py | import textwrap
import pytest
import libqtile.config
import libqtile.widget.bluetooth
from libqtile.bar import Bar
from libqtile.config import Screen
from test.helpers import Retry
@Retry(ignore_exceptions=(AssertionError,))
def clipboard_cleared(widget):
assert widget.info()["text"] == ""
@pytest.fixture
def... | 0.643553 | 0.355132 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Chapter',
fields=[
('id', models.AutoField(auto_created=Tr... | chapter/migrations/0001_initial.py |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Chapter',
fields=[
('id', models.AutoField(auto_created=Tr... | 0.574275 | 0.158109 |
import os
from argparse import ArgumentParser, Namespace
from random import shuffle
from typing import Any, Dict, Generator, List, Tuple
from PIL import Image
from tqdm import tqdm
from composer.datasets.webdataset import create_webdataset
def parse_args() -> Namespace:
args = ArgumentParser()
args.add_argu... | composer/datasets/create/tinyimagenet200.py | import os
from argparse import ArgumentParser, Namespace
from random import shuffle
from typing import Any, Dict, Generator, List, Tuple
from PIL import Image
from tqdm import tqdm
from composer.datasets.webdataset import create_webdataset
def parse_args() -> Namespace:
args = ArgumentParser()
args.add_argu... | 0.553264 | 0.174656 |
__docformat__ = "reStructuredText"
import zope.interface
from zope.schema.fieldproperty import FieldProperty
from z3c.form.interfaces import INPUT_MODE
from z3c.form.interfaces import IFieldWidget
from z3c.form.browser import interfaces
try:
unicode
except NameError:
# Py3: Define unicode.
unicode = str
... | src/z3c/form/browser/widget.py | __docformat__ = "reStructuredText"
import zope.interface
from zope.schema.fieldproperty import FieldProperty
from z3c.form.interfaces import INPUT_MODE
from z3c.form.interfaces import IFieldWidget
from z3c.form.browser import interfaces
try:
unicode
except NameError:
# Py3: Define unicode.
unicode = str
... | 0.593727 | 0.128307 |
import diskord
from diskord.ext import commands, tasks
import datetime
from utils.functions import *
class events(commands.Cog):
def __init__(self, client):
self.client = client
@tasks.loop(hours=3)
async def check(self):
guilds = db.settings.find({"premium.status": True, "guild_i... | bumpy/cogs/events.py | import diskord
from diskord.ext import commands, tasks
import datetime
from utils.functions import *
class events(commands.Cog):
def __init__(self, client):
self.client = client
@tasks.loop(hours=3)
async def check(self):
guilds = db.settings.find({"premium.status": True, "guild_i... | 0.207938 | 0.053502 |
import os
import nibabel as nib
import numpy as np
from overlay_ims import overlay_image, save_overlay_im
from PIL import Image
def make_montage(sname_ims, sname_mont='montage.png', crop=None):
"""
Make images
Args:
sname_ims (list): list of image names
sname_mont (str): name of output fi... | Utilities/show_segmentations.py | import os
import nibabel as nib
import numpy as np
from overlay_ims import overlay_image, save_overlay_im
from PIL import Image
def make_montage(sname_ims, sname_mont='montage.png', crop=None):
"""
Make images
Args:
sname_ims (list): list of image names
sname_mont (str): name of output fi... | 0.617513 | 0.266265 |
import datetime
from unittest.mock import MagicMock
from dateutil.tz import tzutc
from exasol_script_languages_container_ci_setup.lib.run_start_build import run_start_test_release_build
REPO_NAME = "script-languages-repo"
BRANCH = "main"
GITHUB_TOKEN = "<PASSWORD>"
RELEASE_TITLE = "test-release"
#Original resources... | test/test_start_test_release_build.py | import datetime
from unittest.mock import MagicMock
from dateutil.tz import tzutc
from exasol_script_languages_container_ci_setup.lib.run_start_build import run_start_test_release_build
REPO_NAME = "script-languages-repo"
BRANCH = "main"
GITHUB_TOKEN = "<PASSWORD>"
RELEASE_TITLE = "test-release"
#Original resources... | 0.549157 | 0.113432 |
from getpass import getuser
from os import getenv, path, SEEK_END
from raven import Client
from subprocess import call
from tempfile import TemporaryFile
from argparse import ArgumentParser
import argparse
from sys import argv, stderr
from time import time
from .version import VERSION
MAX_MESSAGE_SIZE = 4096
parser =... | raven_cron/runner.py | from getpass import getuser
from os import getenv, path, SEEK_END
from raven import Client
from subprocess import call
from tempfile import TemporaryFile
from argparse import ArgumentParser
import argparse
from sys import argv, stderr
from time import time
from .version import VERSION
MAX_MESSAGE_SIZE = 4096
parser =... | 0.38885 | 0.069954 |
import serial
import json
import requests
from datetime import datetime
def extract_value(message):
temperature_measurment = '%00&'
light_measurment = '%01&'
distance_measurment = '%02&'
humidity_measurment = '%03&'
lpg_measurment = '%04&'
co_measurment = '%05&'
... | embeded_dev/raspberry_dev/menu.py | import serial
import json
import requests
from datetime import datetime
def extract_value(message):
temperature_measurment = '%00&'
light_measurment = '%01&'
distance_measurment = '%02&'
humidity_measurment = '%03&'
lpg_measurment = '%04&'
co_measurment = '%05&'
... | 0.191517 | 0.126326 |
from __future__ import annotations
from typing import ClassVar
from abc import ABC, abstractmethod
from mautrix.types import Event, EventType, Membership, StateEvent
from . import syncer
class Dispatcher(ABC):
client: syncer.Syncer
def __init__(self, client: syncer.Syncer) -> None:
self.client = c... | mautrix/client/dispatcher.py | from __future__ import annotations
from typing import ClassVar
from abc import ABC, abstractmethod
from mautrix.types import Event, EventType, Membership, StateEvent
from . import syncer
class Dispatcher(ABC):
client: syncer.Syncer
def __init__(self, client: syncer.Syncer) -> None:
self.client = c... | 0.775477 | 0.160266 |
from django import forms
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms_foundation.layout import Layout, Row, Column, Fieldset, Field, HTML, Submit
class NewListAjaxForm(forms.Form):
title = forms.CharField(label='Title', max_length=80)
description = ... | resrc/list/forms.bak.py | from django import forms
from django.core.urlresolvers import reverse
from crispy_forms.helper import FormHelper
from crispy_forms_foundation.layout import Layout, Row, Column, Fieldset, Field, HTML, Submit
class NewListAjaxForm(forms.Form):
title = forms.CharField(label='Title', max_length=80)
description = ... | 0.539469 | 0.075619 |
from __future__ import absolute_import, division, print_function
import logging
import os
import numpy as np
import pandas as pd
from . import rna
def do_import_rna(gene_count_fnames, in_format, gene_resource_fname,
correlations_fname=None, normal_fnames=(),
do_gc=True, do_txlen=... | cnvlib/import_rna.py | from __future__ import absolute_import, division, print_function
import logging
import os
import numpy as np
import pandas as pd
from . import rna
def do_import_rna(gene_count_fnames, in_format, gene_resource_fname,
correlations_fname=None, normal_fnames=(),
do_gc=True, do_txlen=... | 0.7641 | 0.402451 |
__author__ = '<NAME>'
import visa
from .conf import INSTR, LOGLEVEL, FUNC
from labtools.log import create_logger
from labtools.utils.instr import BaseDevice, InstrError, process_if_initialized
logger = create_logger(__name__, LOGLEVEL)
class Rigol(BaseDevice):
"""
Class for Rigol function generator
"""
... | rigol/rigol.py | __author__ = '<NAME>'
import visa
from .conf import INSTR, LOGLEVEL, FUNC
from labtools.log import create_logger
from labtools.utils.instr import BaseDevice, InstrError, process_if_initialized
logger = create_logger(__name__, LOGLEVEL)
class Rigol(BaseDevice):
"""
Class for Rigol function generator
"""
... | 0.386532 | 0.202897 |
import copy
import json
from datetime import datetime
import requests
headers = {
'app_version': '3',
'platform': 'ios',
}
# super LIKE '/like/' + likedUserId + '/super'
class User(object):
def __init__(self, data_dict):
self.d = data_dict
@property
def user_id(self):
return s... | tinder_api.py | import copy
import json
from datetime import datetime
import requests
headers = {
'app_version': '3',
'platform': 'ios',
}
# super LIKE '/like/' + likedUserId + '/super'
class User(object):
def __init__(self, data_dict):
self.d = data_dict
@property
def user_id(self):
return s... | 0.359814 | 0.102664 |
import smtplib
import sys
from os import system
def artwork():
print("\n")
print("##########################################################")
print("# #")
print("# \||/ #")
print("# ... | hack-gmail.py | import smtplib
import sys
from os import system
def artwork():
print("\n")
print("##########################################################")
print("# #")
print("# \||/ #")
print("# ... | 0.028061 | 0.060696 |
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier,AdaBoostClassifier
import cPickle... | learn1.py | import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier,AdaBoostClassifier
import cPickle... | 0.260954 | 0.352007 |
import pandas as pd
get_ipython().system('pip install pymystem3')
import re
import numpy as np
from wordcloud import WordCloud, STOPWORDS
import nltk
nltk.download("stopwords")
from nltk.corpus import stopwords
from pymystem3 import Mystem
from string import punctuation
from nltk.stem import PorterStemmer, WordNetLemm... | insta_preprocess.py |
import pandas as pd
get_ipython().system('pip install pymystem3')
import re
import numpy as np
from wordcloud import WordCloud, STOPWORDS
import nltk
nltk.download("stopwords")
from nltk.corpus import stopwords
from pymystem3 import Mystem
from string import punctuation
from nltk.stem import PorterStemmer, WordNetLemm... | 0.240061 | 0.134293 |
import json
import os
from pathlib import Path
import pytest
from mock import AsyncMock
from pytest_mock import MockerFixture
from checkov.sca_package.scanner import Scanner, CHECKOV_SEC_IN_WEEK
def test_should_download_new_twistcli(tmp_path: Path):
# given
scanner = Scanner()
twistcli_path = tmp_path /... | tests/sca_package/test_scanner.py | import json
import os
from pathlib import Path
import pytest
from mock import AsyncMock
from pytest_mock import MockerFixture
from checkov.sca_package.scanner import Scanner, CHECKOV_SEC_IN_WEEK
def test_should_download_new_twistcli(tmp_path: Path):
# given
scanner = Scanner()
twistcli_path = tmp_path /... | 0.458106 | 0.321407 |
from data import BayStars, Dragons, Eagles, Hawks, Carp, Tigers, Marines, Buffaloes, Swallows, Giants, Lions
# Set alias of each team's name
Buffaloes_name=["オリックス","おりっくす","バファローズ","ばふぁろーず","オリックスバファローズ","おりっくすばふぁろーず"]
Swallows_name=["ヤクルト","やくると","スワローズ","すわろーず","ヤクルトスワローズ","やくるとすわろーず","東京ヤクルトスワローズ","とうきょうやくるとすわろーず"... | search.py | from data import BayStars, Dragons, Eagles, Hawks, Carp, Tigers, Marines, Buffaloes, Swallows, Giants, Lions
# Set alias of each team's name
Buffaloes_name=["オリックス","おりっくす","バファローズ","ばふぁろーず","オリックスバファローズ","おりっくすばふぁろーず"]
Swallows_name=["ヤクルト","やくると","スワローズ","すわろーず","ヤクルトスワローズ","やくるとすわろーず","東京ヤクルトスワローズ","とうきょうやくるとすわろーず"... | 0.111555 | 0.421969 |
from gensim.models import Word2Vec
import numpy as np
from poems.poems import getVowel, getTune
from itertools import product
import re
skiptoken = "_((《[E{"
class Rater:
sml_model = None
tune_patterns: np.ndarray
def __init__(self, model_name, substr_len):
self.model = model_name
assert ... | comment.py | from gensim.models import Word2Vec
import numpy as np
from poems.poems import getVowel, getTune
from itertools import product
import re
skiptoken = "_((《[E{"
class Rater:
sml_model = None
tune_patterns: np.ndarray
def __init__(self, model_name, substr_len):
self.model = model_name
assert ... | 0.458834 | 0.419499 |
import argparse
import concurrent.futures
import functools
import gzip
import itertools
import logging
import numpy as np
import operator
import os
import os.path as osp
from queue import Queue
import time
import torch
from tqdm import tqdm
from helper import read_gz_file, setup_logger
from sklearn.decomposition import... | baseline_ac/activation_clustering.py | import argparse
import concurrent.futures
import functools
import gzip
import itertools
import logging
import numpy as np
import operator
import os
import os.path as osp
from queue import Queue
import time
import torch
from tqdm import tqdm
from helper import read_gz_file, setup_logger
from sklearn.decomposition import... | 0.379263 | 0.174656 |
import warnings
from typing import Optional, Sequence, List
import torch
from torch import Tensor
from torch.nn import CrossEntropyLoss
from torch.nn.modules.batchnorm import _NormBase
from torch.optim import SGD
from torch.utils.data import DataLoader
from avalanche.models import MobilenetV1
from avalanche.models.ba... | avalanche/training/supervised/ar1.py | import warnings
from typing import Optional, Sequence, List
import torch
from torch import Tensor
from torch.nn import CrossEntropyLoss
from torch.nn.modules.batchnorm import _NormBase
from torch.optim import SGD
from torch.utils.data import DataLoader
from avalanche.models import MobilenetV1
from avalanche.models.ba... | 0.980812 | 0.568595 |
import glob
from typing import List, Optional, Sequence, Tuple, Union
import pathlib
import pickle
import numpy as np
import torch
from ahrens_wbo.data_processing import generate_torch_dataset
from ahrens_wbo.data_processing import load_and_preprocess_data
from ahrens_wbo.data_processing import SegmentTable
from jan... | probabilistic_model_synthesis/gnlr_ahrens_tools.py | import glob
from typing import List, Optional, Sequence, Tuple, Union
import pathlib
import pickle
import numpy as np
import torch
from ahrens_wbo.data_processing import generate_torch_dataset
from ahrens_wbo.data_processing import load_and_preprocess_data
from ahrens_wbo.data_processing import SegmentTable
from jan... | 0.911483 | 0.578865 |
import numpy as np
import pandas as pd
import sample_functions
from sklearn import svm
import matplotlib.pyplot as plt
ocsvm_nu = 0.003 # OCSVM における ν。トレーニングデータにおけるサンプル数に対する、サポートベクターの数の下限の割合
ocsvm_gammas = 2 ** np.arange(-20, 11, dtype=float) # γ の候補
x_train = pd.read_csv('tep_0.csv', index_col=0)
x_test = ... | sample_program_7_4_1_3_4.py | import numpy as np
import pandas as pd
import sample_functions
from sklearn import svm
import matplotlib.pyplot as plt
ocsvm_nu = 0.003 # OCSVM における ν。トレーニングデータにおけるサンプル数に対する、サポートベクターの数の下限の割合
ocsvm_gammas = 2 ** np.arange(-20, 11, dtype=float) # γ の候補
x_train = pd.read_csv('tep_0.csv', index_col=0)
x_test = ... | 0.32146 | 0.536131 |
import requests
from requests.auth import HTTPBasicAuth
from ..resources.resource import Resource
class Picklists(Resource):
def __init__(self):
super().__init__("picklists")
def close_picklist(self, id):
return requests.post(self.config.base_url + self.path + "/" + str(id) + "/close", verify... | picqer_client_python/resources/picklists.py | import requests
from requests.auth import HTTPBasicAuth
from ..resources.resource import Resource
class Picklists(Resource):
def __init__(self):
super().__init__("picklists")
def close_picklist(self, id):
return requests.post(self.config.base_url + self.path + "/" + str(id) + "/close", verify... | 0.34798 | 0.044287 |
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('projects', '0004_project_project_type'),
]
operations = [
migrations.CreateModel(
name='Script',
field... | modules/projects/migrations/0005_automatedcase_script_scriptfunction.py |
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('projects', '0004_project_project_type'),
]
operations = [
migrations.CreateModel(
name='Script',
field... | 0.527073 | 0.120853 |
import logging
import traceback
from myuw.dao import log_err
from myuw.dao.exceptions import IndeterminateCampusException
from myuw.dao.enrollment import (
get_main_campus, get_class_level, is_registered_current_quarter)
from myuw.dao.gws import (
is_clinician, is_staff_employee, is_student_employee,
is_alu... | myuw/dao/affiliation.py | import logging
import traceback
from myuw.dao import log_err
from myuw.dao.exceptions import IndeterminateCampusException
from myuw.dao.enrollment import (
get_main_campus, get_class_level, is_registered_current_quarter)
from myuw.dao.gws import (
is_clinician, is_staff_employee, is_student_employee,
is_alu... | 0.266548 | 0.209389 |
from util.math import transpose
from util.decorators import type_check
TABLE_SEPERATOR = "\\\\\n "
# TABLE_TEXT%(<column_layout>, <num_columns>, <contents>)
TABLE_TEXT = """\\begin{table}
\centering
\\begin{tabular}{%s}
\hline
%s
\hline
\end{tabular}
\caption{}
\label{table:}
\end{table}"""
TA... | util/misc/paper.py | from util.math import transpose
from util.decorators import type_check
TABLE_SEPERATOR = "\\\\\n "
# TABLE_TEXT%(<column_layout>, <num_columns>, <contents>)
TABLE_TEXT = """\\begin{table}
\centering
\\begin{tabular}{%s}
\hline
%s
\hline
\end{tabular}
\caption{}
\label{table:}
\end{table}"""
TA... | 0.570092 | 0.338706 |
import typing
from typing import List, Dict
from xml.etree.ElementTree import Element
if typing.TYPE_CHECKING:
from timelime.src.datamodel.ecb_plus.document import Document
from timeline.src.datamodel.ecb_plus.context import Context
class Sentence():
def __init__(self, id: str, document: 'Document') -> No... | src/datamodel/ecb_plus/text.py | import typing
from typing import List, Dict
from xml.etree.ElementTree import Element
if typing.TYPE_CHECKING:
from timelime.src.datamodel.ecb_plus.document import Document
from timeline.src.datamodel.ecb_plus.context import Context
class Sentence():
def __init__(self, id: str, document: 'Document') -> No... | 0.688573 | 0.302932 |
import unittest
from src.main.data_structure.dictionary_exercise import *
class DictTest(unittest.TestCase):
def test_add_element(self):
_dict = Dict({"a": 1, "b": 2, "c": 3})
self.assertEqual(_dict.add_element("d", 4), {"a": 1, "b": 2, "c": 3, "d": 4})
def test_get_element_by_key(self):
... | src/test/data_structure/dictionary_exercise_test.py | import unittest
from src.main.data_structure.dictionary_exercise import *
class DictTest(unittest.TestCase):
def test_add_element(self):
_dict = Dict({"a": 1, "b": 2, "c": 3})
self.assertEqual(_dict.add_element("d", 4), {"a": 1, "b": 2, "c": 3, "d": 4})
def test_get_element_by_key(self):
... | 0.4917 | 0.627694 |
__all__ = ["require_auth", "handle_auth", "update_auth", "call_api"]
import time
from functools import partial, wraps
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Optional, Tuple
import aiohttp_session
from aiohttp import web
from aiohttp_spotify import SpotifyAuth, SpotifyResponse
if TYPE_CHECKING:
... | src/spotify_party/auth.py | __all__ = ["require_auth", "handle_auth", "update_auth", "call_api"]
import time
from functools import partial, wraps
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Optional, Tuple
import aiohttp_session
from aiohttp import web
from aiohttp_spotify import SpotifyAuth, SpotifyResponse
if TYPE_CHECKING:
... | 0.851259 | 0.075346 |
from collections import namedtuple
from twisted.python import failure
from vumi.transports.parlayx_ussd.client import format_address
from vumi.transports.parlayx.soaputil import soap_envelope
from vumi.transports.parlayx_ussd.server import NOTIFICATION_NS, normalize_address
from vumi.transports.parlayx.xmlutil import... | vumi/transports/parlayx_ussd/tests/utils.py | from collections import namedtuple
from twisted.python import failure
from vumi.transports.parlayx_ussd.client import format_address
from vumi.transports.parlayx.soaputil import soap_envelope
from vumi.transports.parlayx_ussd.server import NOTIFICATION_NS, normalize_address
from vumi.transports.parlayx.xmlutil import... | 0.793306 | 0.210097 |
from datetime import datetime, tzinfo
import email
from email.header import decode_header
from email.utils import parsedate_tz, mktime_tz
import re
from tempfile import TemporaryFile
import unicodedata
from trac.attachment import Attachment
from trac.db import Table, Column, Index
from trac.mimeview.api import KNOWN_... | mailarchive/model.py |
from datetime import datetime, tzinfo
import email
from email.header import decode_header
from email.utils import parsedate_tz, mktime_tz
import re
from tempfile import TemporaryFile
import unicodedata
from trac.attachment import Attachment
from trac.db import Table, Column, Index
from trac.mimeview.api import KNOWN_... | 0.493164 | 0.160135 |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable
from . import keyword_addon
from .create import Addon, CoreAttribute
if TYPE_CHECKING:
from voiceassistant.core import VoiceAssistant
_INTERNAL_ADDONS = [
keyword_addon.react_to_keyword,
]
class AddonsCompo... | src/voiceassistant/addons/__init__.py | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable
from . import keyword_addon
from .create import Addon, CoreAttribute
if TYPE_CHECKING:
from voiceassistant.core import VoiceAssistant
_INTERNAL_ADDONS = [
keyword_addon.react_to_keyword,
]
class AddonsCompo... | 0.817028 | 0.052014 |
import os
import unittest
import pytest
import numpy as np
import tensorflow as tf
from tfsnippet.scaffold import EarlyStopping
from tfsnippet.utils import TemporaryDirectory, get_default_session_or_error
def get_variable_values(variables):
sess = get_default_session_or_error()
return sess.run(variables)
... | tests/scaffold/test_early_stopping.py | import os
import unittest
import pytest
import numpy as np
import tensorflow as tf
from tfsnippet.scaffold import EarlyStopping
from tfsnippet.utils import TemporaryDirectory, get_default_session_or_error
def get_variable_values(variables):
sess = get_default_session_or_error()
return sess.run(variables)
... | 0.594198 | 0.596316 |
import random
class Plugin:
def __init__(self):
pass
def quote(self):
quotes = [
"You know you’re in love when you can’t fall asleep because reality is finally better than your dreams.",
"Life is what happens when you’re busy making other plans.",
"Get busy... | honeybot/plugins/downloaded/quote/main.py | import random
class Plugin:
def __init__(self):
pass
def quote(self):
quotes = [
"You know you’re in love when you can’t fall asleep because reality is finally better than your dreams.",
"Life is what happens when you’re busy making other plans.",
"Get busy... | 0.183265 | 0.373076 |
import argparse
import ast
import os
import warnings
from dataclasses import asdict
from os import path
from pathlib import Path
from pprint import pformat
from typing import Callable, Iterable, List, Optional, Type
import torchx.specs as specs
import yaml
from torchx.cli.cmd_base import SubCommand
from torchx.cli.co... | torchx/cli/cmd_run.py |
import argparse
import ast
import os
import warnings
from dataclasses import asdict
from os import path
from pathlib import Path
from pprint import pformat
from typing import Callable, Iterable, List, Optional, Type
import torchx.specs as specs
import yaml
from torchx.cli.cmd_base import SubCommand
from torchx.cli.co... | 0.685739 | 0.167151 |
import os
import json
import hashlib
from itertools import product, chain
from config import DataConfig, ExtractorConfig, ModelConfig, ExperimentConfig
PROBLEM_TYPE = 'multilabel'
CLASSIC_BATCH_SIZE = 500000
CLASSIC_EXTRACTOR_TYPES = ['bow', 'tfidf']
BERT_BATCH_SIZE = 64
FASTTEXT_BATCH_SIZE = 2048
CONFIG_ROOT = 'con... | emotion-classification/src/create_experiments_vent_full.py | import os
import json
import hashlib
from itertools import product, chain
from config import DataConfig, ExtractorConfig, ModelConfig, ExperimentConfig
PROBLEM_TYPE = 'multilabel'
CLASSIC_BATCH_SIZE = 500000
CLASSIC_EXTRACTOR_TYPES = ['bow', 'tfidf']
BERT_BATCH_SIZE = 64
FASTTEXT_BATCH_SIZE = 2048
CONFIG_ROOT = 'con... | 0.403214 | 0.20266 |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import time
import pylab as pl
from IPython import display
# Save data in DATAFRAME--------------------------------------------------------------
df_m = pd.read_csv(r'/home/learner/Order-Book-Plotting/order_book_depth30/MSFT_2012-06-21_34200000_3... | read_order_book_data_v2.py |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import time
import pylab as pl
from IPython import display
# Save data in DATAFRAME--------------------------------------------------------------
df_m = pd.read_csv(r'/home/learner/Order-Book-Plotting/order_book_depth30/MSFT_2012-06-21_34200000_3... | 0.405566 | 0.726262 |
import logging
import os
import json
import azure.functions as func
from google.cloud import datastore
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.dirname(os.path.realpath(__file__)) + '/SC-credentials.json'
DS_KIND = 'FX'
DS_CLIENT = datastore.Client()
def main(req: func.HttpRequest) -> func.Htt... | fx-azure-test-space/fx-functions/gcp-cf-api/__init__.py | import logging
import os
import json
import azure.functions as func
from google.cloud import datastore
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.dirname(os.path.realpath(__file__)) + '/SC-credentials.json'
DS_KIND = 'FX'
DS_CLIENT = datastore.Client()
def main(req: func.HttpRequest) -> func.Htt... | 0.154535 | 0.099164 |
from __future__ import absolute_import
import unittest
import datetime
import kubernetes.client
from kubernetes.client.models.com_coreos_monitoring_v1_alertmanager_spec_containers import ComCoreosMonitoringV1AlertmanagerSpecContainers # noqa: E501
from kubernetes.client.rest import ApiException
class TestComCoreosM... | kubernetes/test/test_com_coreos_monitoring_v1_alertmanager_spec_containers.py | from __future__ import absolute_import
import unittest
import datetime
import kubernetes.client
from kubernetes.client.models.com_coreos_monitoring_v1_alertmanager_spec_containers import ComCoreosMonitoringV1AlertmanagerSpecContainers # noqa: E501
from kubernetes.client.rest import ApiException
class TestComCoreosM... | 0.439026 | 0.061621 |
import argparse
import os
import sys
import time
from subprocess import DEVNULL, Popen
parser = argparse.ArgumentParser('dodobox')
subparsers = parser.add_subparsers(help='Action to perform', dest='action', required=True)
actions = {}
def action(name, help=None, **kwargs):
p = subparsers.add_parser(name, help=he... | dodobox.py | import argparse
import os
import sys
import time
from subprocess import DEVNULL, Popen
parser = argparse.ArgumentParser('dodobox')
subparsers = parser.add_subparsers(help='Action to perform', dest='action', required=True)
actions = {}
def action(name, help=None, **kwargs):
p = subparsers.add_parser(name, help=he... | 0.442637 | 0.135204 |
from __future__ import division
from __future__ import absolute_import
#typing
import pytest
from allennlp.data.dataset_readers import ConllCorefReader
from allennlp.common.util import ensure_list
from allennlp.common.testing import AllenNlpTestCase
try:
from itertools import izip
except:
izip = zip
class... | pymagnitude/third_party/allennlp/tests/data/dataset_readers/coreference/coref_reader_test.py |
from __future__ import division
from __future__ import absolute_import
#typing
import pytest
from allennlp.data.dataset_readers import ConllCorefReader
from allennlp.common.util import ensure_list
from allennlp.common.testing import AllenNlpTestCase
try:
from itertools import izip
except:
izip = zip
class... | 0.655226 | 0.273335 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the ... | pyzx/routing/steiner.py |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the ... | 0.803559 | 0.568356 |
from librosa.util import pad_center, tiny
from scipy.io.wavfile import write
from scipy.signal import get_window
from torch import Tensor
from torch.autograd import Variable
from typing import Optional, Tuple
import librosa
import librosa.util as librosa_util
import math
import numpy as np
import scipy
import torch
im... | audio.py | from librosa.util import pad_center, tiny
from scipy.io.wavfile import write
from scipy.signal import get_window
from torch import Tensor
from torch.autograd import Variable
from typing import Optional, Tuple
import librosa
import librosa.util as librosa_util
import math
import numpy as np
import scipy
import torch
im... | 0.943958 | 0.393968 |
"""A WORKSPACE macro for Google open-source libraries to use"""
def google_common_workspace_rules():
"""Defines WORKSPACE rules for Google open-source libraries.
Call this once at the top of your WORKSPACE file to load all of the repositories. Note that you
should not refer to these repositories directly and in... | workspace_defs.bzl | """A WORKSPACE macro for Google open-source libraries to use"""
def google_common_workspace_rules():
"""Defines WORKSPACE rules for Google open-source libraries.
Call this once at the top of your WORKSPACE file to load all of the repositories. Note that you
should not refer to these repositories directly and in... | 0.492676 | 0.235614 |
import tornado.escape
def trim(c, text):
return text.strip()
def nl2br(c, text, escape=True, break_tag='<br />'):
if not text:
return ''
text = tornado.escape.xhtml_escape(text) if escape else text
return text.replace('\r\n', break_tag).replace('\r', break_tag).replace('\n', break_tag)
... | dp_tornado/engine/plugin/ui_methods.py |
import tornado.escape
def trim(c, text):
return text.strip()
def nl2br(c, text, escape=True, break_tag='<br />'):
if not text:
return ''
text = tornado.escape.xhtml_escape(text) if escape else text
return text.replace('\r\n', break_tag).replace('\r', break_tag).replace('\n', break_tag)
... | 0.540924 | 0.14259 |
from PyQt4 import Qt, QtGui, QtCore
from input_parsers import DataCurve, InputParser
import re
import itertools
import color_picker
import time
class InputParserEditDialog(QtGui.QDialog):
ColorRole = Qt.Qt.UserRole + 1
def __init__(self, parent=None):
super(InputParserEditDialog, self).__init__(paren... | plot_window/input_parsers_gui.py | from PyQt4 import Qt, QtGui, QtCore
from input_parsers import DataCurve, InputParser
import re
import itertools
import color_picker
import time
class InputParserEditDialog(QtGui.QDialog):
ColorRole = Qt.Qt.UserRole + 1
def __init__(self, parent=None):
super(InputParserEditDialog, self).__init__(paren... | 0.497803 | 0.094218 |
import re
import time
import subprocess
import log
class AdbException(Exception):
def __init__(self, message):
Exception.__init__(self, message+'\n')
RETRY_CONNECTION_TIMES = 5
RETRY_CONNECTION_BETWEEN = 10
class ADB(object):
def __init__(self, id):
self.id = id.rstrip()
log.debug('ta... | connect.py | import re
import time
import subprocess
import log
class AdbException(Exception):
def __init__(self, message):
Exception.__init__(self, message+'\n')
RETRY_CONNECTION_TIMES = 5
RETRY_CONNECTION_BETWEEN = 10
class ADB(object):
def __init__(self, id):
self.id = id.rstrip()
log.debug('ta... | 0.255622 | 0.073863 |
import inspect
import logging
from foxylib.tools.collections.collections_tool import lchain
from foxylib.tools.function.function_tool import FunctionTool
from foxylib.tools.log.foxylib_logger import FoxylibLogger
from foxylib.tools.native.module.module_tool import ModuleTool
class Warmer:
def __init__(self, mod... | foxylib/tools/function/warmer.py | import inspect
import logging
from foxylib.tools.collections.collections_tool import lchain
from foxylib.tools.function.function_tool import FunctionTool
from foxylib.tools.log.foxylib_logger import FoxylibLogger
from foxylib.tools.native.module.module_tool import ModuleTool
class Warmer:
def __init__(self, mod... | 0.551332 | 0.114245 |
import unittest
from collections import OrderedDict
import couler.argo as couler
from couler.tests.argo_yaml_test import ArgoYamlTest
_test_data_dir = "test_data"
couler.config_workflow(name="pytest")
def random_code():
import random
result = "heads" if random.randint(0, 1) == 0 else "tails"
print(res... | couler/tests/workflow_basic_test.py |
import unittest
from collections import OrderedDict
import couler.argo as couler
from couler.tests.argo_yaml_test import ArgoYamlTest
_test_data_dir = "test_data"
couler.config_workflow(name="pytest")
def random_code():
import random
result = "heads" if random.randint(0, 1) == 0 else "tails"
print(res... | 0.574634 | 0.481881 |
import gzip
import json
from collections import OrderedDict
import pytest
import demistomock
from SecurityIntelligenceServicesFeed import Client, botocore, MESSAGES
ACCESS_KEY = 'access key'
SECRET_KEY = 'secret key'
CLIENT = Client(ACCESS_KEY, SECRET_KEY, False, True)
CLIENT.set_s3_client(region_name='region')
d... | Packs/SecurityIntelligenceServicesFeed/Integrations/SecurityIntelligenceServicesFeed/SecurityIntelligenceServicesFeed_test.py | import gzip
import json
from collections import OrderedDict
import pytest
import demistomock
from SecurityIntelligenceServicesFeed import Client, botocore, MESSAGES
ACCESS_KEY = 'access key'
SECRET_KEY = 'secret key'
CLIENT = Client(ACCESS_KEY, SECRET_KEY, False, True)
CLIENT.set_s3_client(region_name='region')
d... | 0.541166 | 0.277626 |
import os
import pandas as pd
from urllib.parse import urlparse
import sys
def check_match():
ORIGIN_LINK_CORPUS="Corpus4.csv"
data_path="newdata/"
df_corpus = pd.read_csv(os.path.join(data_path,ORIGIN_LINK_CORPUS) ,encoding="utf8")
evidence_match_num=0
news_match_num=0
total_news_num=0
t... | corpus4_construction/pick_match.py | import os
import pandas as pd
from urllib.parse import urlparse
import sys
def check_match():
ORIGIN_LINK_CORPUS="Corpus4.csv"
data_path="newdata/"
df_corpus = pd.read_csv(os.path.join(data_path,ORIGIN_LINK_CORPUS) ,encoding="utf8")
evidence_match_num=0
news_match_num=0
total_news_num=0
t... | 0.021277 | 0.070624 |
import re
import string
import numpy
import numpoly
def symbols(names=None, asarray=False, dtype="i8"):
"""
Construct symbol variables.
Most directly be providing a list of string names. But a set of shorthands
also exists:
* ``,`` and `` `` (space) can be used as a variable delimiter.
* ``... | numpoly/poly_function/symbols.py | import re
import string
import numpy
import numpoly
def symbols(names=None, asarray=False, dtype="i8"):
"""
Construct symbol variables.
Most directly be providing a list of string names. But a set of shorthands
also exists:
* ``,`` and `` `` (space) can be used as a variable delimiter.
* ``... | 0.884139 | 0.689016 |
import json
import logging
import asyncio
import websockets
from sqlalchemy.orm import joinedload
from .. import db
from .. import models
from ..ob_analyser import OrderBookAnalyser
def get_exchanges():
exchanges = db.session.query(models.Exchange).options(joinedload("markets_with_data")).all()
return [exc... | antalla/web/websocket_handler.py | import json
import logging
import asyncio
import websockets
from sqlalchemy.orm import joinedload
from .. import db
from .. import models
from ..ob_analyser import OrderBookAnalyser
def get_exchanges():
exchanges = db.session.query(models.Exchange).options(joinedload("markets_with_data")).all()
return [exc... | 0.368974 | 0.147156 |
from contextlib import contextmanager
from collections import namedtuple
from scipy import weave
import numpy as np
from twisted.internet import defer
from mcmandelbrot import valuer
from mcmandelbrot.test.testbase import TestCase
class TestMandelbrotValuer(TestCase):
verbose = True
class Yielded:
... | mcmandelbrot/test/test_valuer.py | from contextlib import contextmanager
from collections import namedtuple
from scipy import weave
import numpy as np
from twisted.internet import defer
from mcmandelbrot import valuer
from mcmandelbrot.test.testbase import TestCase
class TestMandelbrotValuer(TestCase):
verbose = True
class Yielded:
... | 0.532911 | 0.194158 |
import numpy as np
import random
from copy import copy, deepcopy
from numba import njit
import time
from tiles import IDS
#@njit
def predict_board(symbols, nodes, layers):
returned = []
for _ in range(nodes):
out = predict_thread(symbols, layers)
returned.append(sum(out) / len(out))
ret... | src/simulator.py | import numpy as np
import random
from copy import copy, deepcopy
from numba import njit
import time
from tiles import IDS
#@njit
def predict_board(symbols, nodes, layers):
returned = []
for _ in range(nodes):
out = predict_thread(symbols, layers)
returned.append(sum(out) / len(out))
ret... | 0.246352 | 0.342517 |
from collections import OrderedDict
from numbers import Real
import abc
import math
import copy
import pandas
import json
from up.utils.general.log_helper import default_logger as logger
from up.utils.general.registry_factory import EVALUATOR_REGISTRY
__all__ = ['Metric', 'Evaluator', 'EvaluatorResp']
class NumMet... | up/data/metrics/base_evaluator.py | from collections import OrderedDict
from numbers import Real
import abc
import math
import copy
import pandas
import json
from up.utils.general.log_helper import default_logger as logger
from up.utils.general.registry_factory import EVALUATOR_REGISTRY
__all__ = ['Metric', 'Evaluator', 'EvaluatorResp']
class NumMet... | 0.805364 | 0.147463 |