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 |
|---|---|---|---|---|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ..tensors import Tensor
def add_test():
a = Tensor([1,2,3,4,5], auto_grad=True)
b = Tensor([2,2,2,2,2], auto_grad=True)
# c = Tensor([5,4,3,2,1], auto_grad=True)
c = a + b
print('Tenso... | unit_test/tensors_unit_test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ..tensors import Tensor
def add_test():
a = Tensor([1,2,3,4,5], auto_grad=True)
b = Tensor([2,2,2,2,2], auto_grad=True)
# c = Tensor([5,4,3,2,1], auto_grad=True)
c = a + b
print('Tenso... | 0.288669 | 0.619874 |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from unittest import TestCase
from idlk import base41
class Base41Test(TestCase):
DATA = (
# First 48.
(0x00, "000000"),
(0x01, "000001"),
(0x02, "000002"),
(0x03,... | idlk/test/test_base41.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from unittest import TestCase
from idlk import base41
class Base41Test(TestCase):
DATA = (
# First 48.
(0x00, "000000"),
(0x01, "000001"),
(0x02, "000002"),
(0x03,... | 0.564699 | 0.286958 |
import os
import shutil
from apex import amp
import torch
from torch.utils.tensorboard import SummaryWriter
class Trainer:
def __init__(
self, model,
optimizer,
scheduler,
pad_token_id,
device=None,
logdir=None,
opt_lev... | utils/classification/train.py | import os
import shutil
from apex import amp
import torch
from torch.utils.tensorboard import SummaryWriter
class Trainer:
def __init__(
self, model,
optimizer,
scheduler,
pad_token_id,
device=None,
logdir=None,
opt_lev... | 0.821152 | 0.158695 |
import tkinter as tk
class AskDialog(tk.Toplevel):
"""AskDialog class opens a popup window"""
# * toplevel - popup confirmation window
# * a window with text for a question/request, an okay and cancel button
def __init__(self, parent, controller, text):
"""run __init__ section at class insta... | Core/View/Dialogs/ask_dialog.py | import tkinter as tk
class AskDialog(tk.Toplevel):
"""AskDialog class opens a popup window"""
# * toplevel - popup confirmation window
# * a window with text for a question/request, an okay and cancel button
def __init__(self, parent, controller, text):
"""run __init__ section at class insta... | 0.660391 | 0.146697 |
import numpy as np
import plotly.io as pio
from core import models
from core import fitting
from core import utils
from core import plot
from core import resources
pio.renderers.default = "browser"
xdata, ydata = resources.test_file2[0], resources.test_file2[1:]
xdata = [xdata] * len(ydata)
N0s = (55e12, 164e12, 51... | core/tests.py |
import numpy as np
import plotly.io as pio
from core import models
from core import fitting
from core import utils
from core import plot
from core import resources
pio.renderers.default = "browser"
xdata, ydata = resources.test_file2[0], resources.test_file2[1:]
xdata = [xdata] * len(ydata)
N0s = (55e12, 164e12, 51... | 0.429908 | 0.546799 |
import os
import json
import socket
import getpass
from utils.ui import color, __clear__
def configMenu(__configPath__):
__clear__()
if True:
while True:
config = json.load(open(__configPath__))
a = u'\u001b[32mY\u001b[0m' if config['clearEachCommand'] else '\u001b[31mN... | utils/configMenu.py | import os
import json
import socket
import getpass
from utils.ui import color, __clear__
def configMenu(__configPath__):
__clear__()
if True:
while True:
config = json.load(open(__configPath__))
a = u'\u001b[32mY\u001b[0m' if config['clearEachCommand'] else '\u001b[31mN... | 0.037108 | 0.069858 |
import zipfile as zf
import os
import shutil
from createFolder import createFolder
from progressBar import progressBar
"""
----------------------------------------------------------------------------------------
Functions
----------------------------------------------------------------------------------------
"""
#A ... | CameraOF_files/Decompressor.py | import zipfile as zf
import os
import shutil
from createFolder import createFolder
from progressBar import progressBar
"""
----------------------------------------------------------------------------------------
Functions
----------------------------------------------------------------------------------------
"""
#A ... | 0.141341 | 0.11427 |
from typing import NamedTuple, List, Type, Callable, Tuple
import numpy as np
import torch.nn as nn
import torch
class Features(NamedTuple):
"""
Holds information regarding features in a feature file
"""
feature_file: str
arg_names: List[str] = ['X', 'y']
embed_size: int = 0
vector_count:... | utility/utilities.py | from typing import NamedTuple, List, Type, Callable, Tuple
import numpy as np
import torch.nn as nn
import torch
class Features(NamedTuple):
"""
Holds information regarding features in a feature file
"""
feature_file: str
arg_names: List[str] = ['X', 'y']
embed_size: int = 0
vector_count:... | 0.955981 | 0.750141 |
import logging
import os
from box import Box
from dataclasses import dataclass
from datetime import datetime
from typing import Tuple
import tensorflow as tf
from src.utils import render_images
from src.data_loader import ImageDataLoader
from src.models.architectures import CycleGAN
from src.models.losses import get_... | src/models/train.py | import logging
import os
from box import Box
from dataclasses import dataclass
from datetime import datetime
from typing import Tuple
import tensorflow as tf
from src.utils import render_images
from src.data_loader import ImageDataLoader
from src.models.architectures import CycleGAN
from src.models.losses import get_... | 0.877372 | 0.254648 |
from unittest.mock import patch, PropertyMock
from fastapi.testclient import TestClient
from laa_court_data_api_app.internal.oauth_client import OauthClient
from laa_court_data_api_app.main import app
from laa_court_data_api_app.models.defendants.defendants_response import DefendantsResponse
from ..routers.fixtures i... | test/routers/defendants_test.py | from unittest.mock import patch, PropertyMock
from fastapi.testclient import TestClient
from laa_court_data_api_app.internal.oauth_client import OauthClient
from laa_court_data_api_app.main import app
from laa_court_data_api_app.models.defendants.defendants_response import DefendantsResponse
from ..routers.fixtures i... | 0.623033 | 0.114715 |
from datetime import datetime, timezone
import logging
import os
from pathlib import Path
import subprocess
import sys
import tarfile
import time
import boto3
from boto3.exceptions import S3UploadFailedError
from botocore.client import ClientError
from botocore.exceptions import NoCredentialsError
from .utils import ... | src/bits3/core.py | from datetime import datetime, timezone
import logging
import os
from pathlib import Path
import subprocess
import sys
import tarfile
import time
import boto3
from boto3.exceptions import S3UploadFailedError
from botocore.client import ClientError
from botocore.exceptions import NoCredentialsError
from .utils import ... | 0.549882 | 0.096068 |
import numpy as np
import pandas as pd
import math
import operator
from pyspark.sql import SparkSession
warehouse_location = 'spark-warehouse'
spark = SparkSession.builder.appName("Python Spark SQL Hive integration example").config("spark.sql.warehouse.dir", warehouse_location).enableHiveSupport().getOrCreate()
# sqlD... | collection/uid_positioning_2.py | import numpy as np
import pandas as pd
import math
import operator
from pyspark.sql import SparkSession
warehouse_location = 'spark-warehouse'
spark = SparkSession.builder.appName("Python Spark SQL Hive integration example").config("spark.sql.warehouse.dir", warehouse_location).enableHiveSupport().getOrCreate()
# sqlD... | 0.355551 | 0.348784 |
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from octopyclient.utils import *
from octopyclient.common import CommonPanel, Singleton, BackgroundTask
from octopyclient.igtk import *
from .temperature import TemperaturePanel, EXTRUDE_MIN_TEMP
class ExtrudePanel(CommonPanel, metaclass=Singl... | octopyclient/panels/extrude.py |
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from octopyclient.utils import *
from octopyclient.common import CommonPanel, Singleton, BackgroundTask
from octopyclient.igtk import *
from .temperature import TemperaturePanel, EXTRUDE_MIN_TEMP
class ExtrudePanel(CommonPanel, metaclass=Singl... | 0.519034 | 0.189746 |
from http import HTTPStatus
import requests
from flask import session, current_app
from requests.exceptions import SSLError, ConnectionError
from api.errors import (
CriticalResponseError, GraphSSLError, GraphConnectionError,
AuthorizationError
)
# The Graph Security API accepts the 'User-Agent'
# header in ... | code/api/client.py | from http import HTTPStatus
import requests
from flask import session, current_app
from requests.exceptions import SSLError, ConnectionError
from api.errors import (
CriticalResponseError, GraphSSLError, GraphConnectionError,
AuthorizationError
)
# The Graph Security API accepts the 'User-Agent'
# header in ... | 0.688364 | 0.054399 |
import binascii
from binascii import Error
import json
import pprint
import iroha.primitive_pb2 as iroha_primitive
import iroha.queries_pb2 as queries_pb2
from google.protobuf.json_format import MessageToDict, MessageToJson, ParseDict
from iroha import Iroha, IrohaGrpc
from iroha import IrohaCrypto as ic
from cli impor... | iroha_cli/iroha_tools/client.py | import binascii
from binascii import Error
import json
import pprint
import iroha.primitive_pb2 as iroha_primitive
import iroha.queries_pb2 as queries_pb2
from google.protobuf.json_format import MessageToDict, MessageToJson, ParseDict
from iroha import Iroha, IrohaGrpc
from iroha import IrohaCrypto as ic
from cli impor... | 0.363421 | 0.148757 |
import numpy as np
"""# N x N Grid world"""
class Environment:
actions = ['left', 'right', 'up', 'down']
def __init__(self, grid_size=(4,4)):
self.grid_size = grid_size
self.s = np.arange(self.grid_size[0] * self.grid_size[1])
self.v = np.zeros(self.grid_size)
self.terminal_state_indices... | Results/Jupyter/ML/ML_SoSe19/ML_SoSe19-master/ex08.py | import numpy as np
"""# N x N Grid world"""
class Environment:
actions = ['left', 'right', 'up', 'down']
def __init__(self, grid_size=(4,4)):
self.grid_size = grid_size
self.s = np.arange(self.grid_size[0] * self.grid_size[1])
self.v = np.zeros(self.grid_size)
self.terminal_state_indices... | 0.580114 | 0.605682 |
import os
import random
class RandomTextGenerator(object):
def __init__(self, limit=20):
self.limit = limit # limit of word counts
self.brain = {"**": {"**": 0}}
self.file_flag = True
def train(self, filename):
titles = []
if self.read_file(filename, titles):
... | RTG.py | import os
import random
class RandomTextGenerator(object):
def __init__(self, limit=20):
self.limit = limit # limit of word counts
self.brain = {"**": {"**": 0}}
self.file_flag = True
def train(self, filename):
titles = []
if self.read_file(filename, titles):
... | 0.158012 | 0.12536 |
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from objects import models_pb2 as objects_dot_models__pb2
class MruVObjectModelsServiceStub(object):
"""The MruV objects service provides procedures for game object models.
"""
def __init__(self, channel):
""... | objects/models_pb2_grpc.py | """Client and server classes corresponding to protobuf-defined services."""
import grpc
from objects import models_pb2 as objects_dot_models__pb2
class MruVObjectModelsServiceStub(object):
"""The MruV objects service provides procedures for game object models.
"""
def __init__(self, channel):
""... | 0.716615 | 0.153422 |
import numpy as np
import pyorb_core.algebraic_utils as alg_ut
class ProperOrthogonalDecompostion( ):
def __init__( self ):
return
def perform_pod( self, _snapshots_matrix, _tol = 10**(-5) ):
self.M_snapshots_matrix = _snapshots_matrix
self.M_ns = self.M_snapshots_matrix... | pyorb_core/rb_library/proper_orthogonal_decomposition.py | import numpy as np
import pyorb_core.algebraic_utils as alg_ut
class ProperOrthogonalDecompostion( ):
def __init__( self ):
return
def perform_pod( self, _snapshots_matrix, _tol = 10**(-5) ):
self.M_snapshots_matrix = _snapshots_matrix
self.M_ns = self.M_snapshots_matrix... | 0.520496 | 0.499756 |
import itertools
import random
from .game import Game
from ..utility import Logger
class Tournament(object):
'''
Manages a tournament.
A tournament is a number of games between a collection of players.
You specify:
- The collection of player AIs.
- The maximum number of players in each game.... | monopyly/game/tournament.py | import itertools
import random
from .game import Game
from ..utility import Logger
class Tournament(object):
'''
Manages a tournament.
A tournament is a number of games between a collection of players.
You specify:
- The collection of player AIs.
- The maximum number of players in each game.... | 0.657868 | 0.355188 |
from spider.driver.base.field import Fieldlist,Field,FieldName
from spider.driver.base.tabsetup import TabSetup
from spider.driver.base.page import Page
from spider.driver.base.listcssselector import ListCssSelector
from spider.driver.base.mongodb import Mongodb
from spider.driver.travel.core.traveldriver import Trave... | spider/driver/travel/fliggyhotelspider.py |
from spider.driver.base.field import Fieldlist,Field,FieldName
from spider.driver.base.tabsetup import TabSetup
from spider.driver.base.page import Page
from spider.driver.base.listcssselector import ListCssSelector
from spider.driver.base.mongodb import Mongodb
from spider.driver.travel.core.traveldriver import Trave... | 0.266548 | 0.051415 |
import pytest
from timeouts import timeouts
from base_client_tests import BaseClientTests
from telemetry_tests import TelemetryTests
from twin_tests import TwinTests
from input_output_tests import InputOutputTests
from method_tests import (
ReceiveMethodCallFromServiceTests,
ReceiveMethodCallFromModuleTests,
... | test-runner/test_edgehub_module.py |
import pytest
from timeouts import timeouts
from base_client_tests import BaseClientTests
from telemetry_tests import TelemetryTests
from twin_tests import TwinTests
from input_output_tests import InputOutputTests
from method_tests import (
ReceiveMethodCallFromServiceTests,
ReceiveMethodCallFromModuleTests,
... | 0.469277 | 0.210259 |
from __future__ import unicode_literals
import logging
import os
import string
import urllib
import urlparse
import glib
logger = logging.getLogger(__name__)
XDG_DIRS = {
'XDG_CACHE_DIR': glib.get_user_cache_dir(),
'XDG_CONFIG_DIR': glib.get_user_config_dir(),
'XDG_DATA_DIR': glib.get_user_data_dir(),... | mopidy/utils/path.py | from __future__ import unicode_literals
import logging
import os
import string
import urllib
import urlparse
import glib
logger = logging.getLogger(__name__)
XDG_DIRS = {
'XDG_CACHE_DIR': glib.get_user_cache_dir(),
'XDG_CONFIG_DIR': glib.get_user_config_dir(),
'XDG_DATA_DIR': glib.get_user_data_dir(),... | 0.558327 | 0.117699 |
# builtin
import sys
import json
import collections
# external
import lxml.etree
from mixbox.vendor.six import iteritems, itervalues
# internal
import sdv
import sdv.codes as codes
import sdv.utils as utils
import sdv.validators.base as base
_QUIET = False
class ValidationOptions(object):
"""Collection of vali... | sdv/scripts/__init__.py |
# builtin
import sys
import json
import collections
# external
import lxml.etree
from mixbox.vendor.six import iteritems, itervalues
# internal
import sdv
import sdv.codes as codes
import sdv.utils as utils
import sdv.validators.base as base
_QUIET = False
class ValidationOptions(object):
"""Collection of vali... | 0.673729 | 0.419529 |
# In[7]:
import cv2
import os
import glob
import shutil
import matplotlib.pyplot as plt
# In[11]:
dir_tree = os.walk('DATA/train')
base_outpth = 'FilteredDataALL/train'
os.makedirs(base_outpth,exist_ok=True)
see_mods = ['FLAIR','T1W','T2W','T1WCE']
see_label = 1
limit = 15*len(see_mods)
with open('train_labels.c... | filter_frames.py |
# In[7]:
import cv2
import os
import glob
import shutil
import matplotlib.pyplot as plt
# In[11]:
dir_tree = os.walk('DATA/train')
base_outpth = 'FilteredDataALL/train'
os.makedirs(base_outpth,exist_ok=True)
see_mods = ['FLAIR','T1W','T2W','T1WCE']
see_label = 1
limit = 15*len(see_mods)
with open('train_labels.c... | 0.077596 | 0.158369 |
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import zip
from io import open
import sys
import os, shutil
import urllib.request
import logging, logging.handlers
from datetime import datetime
import time
import json
# Data sources
FIREFILE = 'blmfir... | blmfire.py | from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import zip
from io import open
import sys
import os, shutil
import urllib.request
import logging, logging.handlers
from datetime import datetime
import time
import json
# Data sources
FIREFILE = 'blmfir... | 0.321993 | 0.119768 |
from functional_tests.base import FunctionalTest
from selenium import webdriver
class NewVisitorTest(FunctionalTest):
def test_can_start_a_list_and_retrieve_it_later(self):
# Mark has heard of a new lists app and goes to the website to check it out
self.browser.get(self.live_server_url)
# ... | functional_tests/test_simple_list_creation.py | from functional_tests.base import FunctionalTest
from selenium import webdriver
class NewVisitorTest(FunctionalTest):
def test_can_start_a_list_and_retrieve_it_later(self):
# Mark has heard of a new lists app and goes to the website to check it out
self.browser.get(self.live_server_url)
# ... | 0.240418 | 0.262227 |
import asyncio
import inspect
import typing
from copy import deepcopy
from . import handler
from . import intents
from . import websocket
class Client:
def __init__(self, *, intents: typing.Optional[intents.Intents] = intents.Intents.default(), respond_self: typing.Optional[bool] = False, loop: typing.Optional[a... | discord/client.py | import asyncio
import inspect
import typing
from copy import deepcopy
from . import handler
from . import intents
from . import websocket
class Client:
def __init__(self, *, intents: typing.Optional[intents.Intents] = intents.Intents.default(), respond_self: typing.Optional[bool] = False, loop: typing.Optional[a... | 0.552057 | 0.12213 |
import logging
from typing import Callable, Dict, Any, List, Union
import pandas as pd
from dgraphpandas.config import get_from_config
from dgraphpandas.strategies.vertical_helpers import (_expand_csv_edges, _join_key_fields, _add_dgraph_type_records,
_break_up_in... | dgraphpandas/strategies/vertical.py | import logging
from typing import Callable, Dict, Any, List, Union
import pandas as pd
from dgraphpandas.config import get_from_config
from dgraphpandas.strategies.vertical_helpers import (_expand_csv_edges, _join_key_fields, _add_dgraph_type_records,
_break_up_in... | 0.645902 | 0.107484 |
import wx
from infertile.inferrer.generator import TilesetGenerator, Box
ABOUT_DIALOG = """InferTile {version}
InferTile is a simple utility for generating (inferring ;)) an entire, 47-part, perfectly tiling tileset from just two \
sprites.
""".format(
version="0.0"
)
class InfertileFrame(wx.Frame):
def _... | infertile/ui/gui.py |
import wx
from infertile.inferrer.generator import TilesetGenerator, Box
ABOUT_DIALOG = """InferTile {version}
InferTile is a simple utility for generating (inferring ;)) an entire, 47-part, perfectly tiling tileset from just two \
sprites.
""".format(
version="0.0"
)
class InfertileFrame(wx.Frame):
def _... | 0.494629 | 0.120387 |
import os
import shutil
import logging
import codecs
import sys
import _thread
from ruamel import yaml
from ..utils.utils import start_pcap_capture, stop_pcap_capture
from ..scenario import Scenario
class Testbed(object):
"""Generic Testbed"""
def __init__(self, scenario: Scenario) -> None:
self.scen... | code/source/testbed/testbed.py | import os
import shutil
import logging
import codecs
import sys
import _thread
from ruamel import yaml
from ..utils.utils import start_pcap_capture, stop_pcap_capture
from ..scenario import Scenario
class Testbed(object):
"""Generic Testbed"""
def __init__(self, scenario: Scenario) -> None:
self.scen... | 0.303525 | 0.228329 |
import abc
import logging
import warnings
import pathlib
import os
from abc import abstractmethod
from enum import IntEnum
import json
import sys
import ssl
import platform
import posixpath
from enum import Enum
import argparse
import urllib.request
import datetime
import time
import traceback
curdir = pathlib.Path(_... | gen_config.py | import abc
import logging
import warnings
import pathlib
import os
from abc import abstractmethod
from enum import IntEnum
import json
import sys
import ssl
import platform
import posixpath
from enum import Enum
import argparse
import urllib.request
import datetime
import time
import traceback
curdir = pathlib.Path(_... | 0.356895 | 0.098339 |
from __future__ import annotations
from typing import Type, Optional
from asyncio import AbstractEventLoop
from .utils import _executor_function
from .template import Template, Any
class BaseManager:
"""This class is the base class for `Manager` or other.
Parameters are same as `Manager`."""
def __... | miko/manager.py |
from __future__ import annotations
from typing import Type, Optional
from asyncio import AbstractEventLoop
from .utils import _executor_function
from .template import Template, Any
class BaseManager:
"""This class is the base class for `Manager` or other.
Parameters are same as `Manager`."""
def __... | 0.955899 | 0.370254 |
from thortils.constants import SCENE_TYPES
from thortils.scene import SceneDataset, ithor_scene_names
import pandas as pd
import scipy.spatial as ss
import numpy as np
def compute_volume(bbox3D):
"""bbox3D: object oriented bounding box"""
hull = ss.ConvexHull(bbox3D)
return hull.volume
SCENE_DATA_PATH = "... | scripts/list_objects_and_properties.py | from thortils.constants import SCENE_TYPES
from thortils.scene import SceneDataset, ithor_scene_names
import pandas as pd
import scipy.spatial as ss
import numpy as np
def compute_volume(bbox3D):
"""bbox3D: object oriented bounding box"""
hull = ss.ConvexHull(bbox3D)
return hull.volume
SCENE_DATA_PATH = "... | 0.461017 | 0.278205 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import collections
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.level = logging.WARNING
class Symbol: pass
class AcceptSymbol(Symbol... | sly/yacc.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import collections
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.level = logging.WARNING
class Symbol: pass
class AcceptSymbol(Symbol... | 0.36625 | 0.129073 |
from requests_html import AsyncHTMLSession
import requests
import json
import os
import asyncio
import pause
from datetime import datetime, date
import argparse
import aiohttp
import asyncio
import time
from twitchAPI.twitch import Twitch
async def get_viewers(session, streamer):
async with session.get(f"https:... | api_req_streams.py | from requests_html import AsyncHTMLSession
import requests
import json
import os
import asyncio
import pause
from datetime import datetime, date
import argparse
import aiohttp
import asyncio
import time
from twitchAPI.twitch import Twitch
async def get_viewers(session, streamer):
async with session.get(f"https:... | 0.117623 | 0.066873 |
from fastai.basics import *
from fastai.data.all import *
from fastai.vision.all import *
from fastai.callback.all import *
from fastai.metrics import *
from fastai.callback.wandb import *
from pathlib import Path
from tqdm import tqdm
from math import ceil
import wandb
# wandb.login()
path = Path("/scratch/rc4499/... | 1-seg_apply.py | from fastai.basics import *
from fastai.data.all import *
from fastai.vision.all import *
from fastai.callback.all import *
from fastai.metrics import *
from fastai.callback.wandb import *
from pathlib import Path
from tqdm import tqdm
from math import ceil
import wandb
# wandb.login()
path = Path("/scratch/rc4499/... | 0.478529 | 0.265148 |
import numpy as np
from sklearn.manifold import TSNE
import torch
import torch.nn as nn
from data import word_sequence_from_korp_dataset
import matplotlib.pyplot as plt
def input_word(vocab):
while True:
word = input()
try:
word_idx = vocab.index(word)
return word_idx
... | src/word2vec_test.py | import numpy as np
from sklearn.manifold import TSNE
import torch
import torch.nn as nn
from data import word_sequence_from_korp_dataset
import matplotlib.pyplot as plt
def input_word(vocab):
while True:
word = input()
try:
word_idx = vocab.index(word)
return word_idx
... | 0.809238 | 0.369514 |
from dpkt.ip import IP, IP_PROTO_TCP
from dpkt.ip6 import IP6
from dpkt.tcp import TCP
from .mod import Mod, recalculate_checksums
class TcpOpt(Mod):
name = "tcp_opt"
usage = "tcp_opt mss|wscale size"
description = """Add TCP options to every TCP packet, to set the
maximum segment size ... | fragroutepluspy/modules/mod_tcp_opt.py | from dpkt.ip import IP, IP_PROTO_TCP
from dpkt.ip6 import IP6
from dpkt.tcp import TCP
from .mod import Mod, recalculate_checksums
class TcpOpt(Mod):
name = "tcp_opt"
usage = "tcp_opt mss|wscale size"
description = """Add TCP options to every TCP packet, to set the
maximum segment size ... | 0.633977 | 0.214013 |
import zdt3
import random
import numpy as np
import parsing
class MOEC:
# Evaluaciones: N x G <= 4000 ó 10000
# N: n_sp
# G: generations
def __init__(self,n_sp,generations,neighbourhood,de_F,de_CR,de_SIG,crossover_mode,path_to_file,const_mode=None,problem=zdt3.ZDT3(),weights=False):
self.n_sp =... | algorithm.py | import zdt3
import random
import numpy as np
import parsing
class MOEC:
# Evaluaciones: N x G <= 4000 ó 10000
# N: n_sp
# G: generations
def __init__(self,n_sp,generations,neighbourhood,de_F,de_CR,de_SIG,crossover_mode,path_to_file,const_mode=None,problem=zdt3.ZDT3(),weights=False):
self.n_sp =... | 0.196788 | 0.296272 |
import numpy as np
from sklearn.model_selection import train_test_split
import sklearn.metrics as metrics
np.random.seed(42)
"""
BGD needs much more iterations than SGD/MBGD.
"""
class LinearRegression:
def __init__(self, learning_rate=0.001, epoch=300, batch_size=150):
self.lr = learning_rate
... | linear_regression/linear_regression.py | import numpy as np
from sklearn.model_selection import train_test_split
import sklearn.metrics as metrics
np.random.seed(42)
"""
BGD needs much more iterations than SGD/MBGD.
"""
class LinearRegression:
def __init__(self, learning_rate=0.001, epoch=300, batch_size=150):
self.lr = learning_rate
... | 0.880656 | 0.501404 |
from botocore.vendored import requests
import base64
import json
import csv
def lambda_handler(event, context):
buyingPlaces = ['Starbucks', 'Bloomingdales', 'Century21', 'Zara', 'H&M', 'Panera', 'Chipotle', 'Supreme']
items1 = ['Tshirt', 'Coffee', 'Bread', 'Rice', 'Jeans', 'Pefume']
items2 = ['Jacket... | lambdas/lambda_topics.py | from botocore.vendored import requests
import base64
import json
import csv
def lambda_handler(event, context):
buyingPlaces = ['Starbucks', 'Bloomingdales', 'Century21', 'Zara', 'H&M', 'Panera', 'Chipotle', 'Supreme']
items1 = ['Tshirt', 'Coffee', 'Bread', 'Rice', 'Jeans', 'Pefume']
items2 = ['Jacket... | 0.326164 | 0.225342 |
import logging
logger = logging.getLogger()
import subprocess
import time
import hostapd
import hwsim_utils
def get_rfkill_id(dev):
try:
cmd = subprocess.Popen(["rfkill", "list"], stdout=subprocess.PIPE)
except Exception, e:
logger.info("No rfkill available: " + str(e))
return None
... | tests/hwsim/test_rfkill.py |
import logging
logger = logging.getLogger()
import subprocess
import time
import hostapd
import hwsim_utils
def get_rfkill_id(dev):
try:
cmd = subprocess.Popen(["rfkill", "list"], stdout=subprocess.PIPE)
except Exception, e:
logger.info("No rfkill available: " + str(e))
return None
... | 0.243822 | 0.08698 |
import aiohttp
import asyncio
import bs4
import inflect
import signal
import sys
from .main import DomiOwned
class HashDump(DomiOwned):
def dump(self):
"""
Dump Domino account hashes.
"""
# Check if the user can access names.nsf
if self.check_access(self.username, self.password)['names.nsf']:
if self... | domi_owned/hashdump.py | import aiohttp
import asyncio
import bs4
import inflect
import signal
import sys
from .main import DomiOwned
class HashDump(DomiOwned):
def dump(self):
"""
Dump Domino account hashes.
"""
# Check if the user can access names.nsf
if self.check_access(self.username, self.password)['names.nsf']:
if self... | 0.147955 | 0.109753 |
from __future__ import (
annotations,
)
from contextlib import (
suppress,
)
from copy import (
deepcopy,
)
from typing import (
TYPE_CHECKING,
Any,
Union,
)
from ..exceptions import (
MinosConfigException,
)
from ..importlib import (
import_module,
)
from .abc import (
Config,
)
... | packages/core/minos-microservice-common/minos/common/config/v2.py | from __future__ import (
annotations,
)
from contextlib import (
suppress,
)
from copy import (
deepcopy,
)
from typing import (
TYPE_CHECKING,
Any,
Union,
)
from ..exceptions import (
MinosConfigException,
)
from ..importlib import (
import_module,
)
from .abc import (
Config,
)
... | 0.691393 | 0.163012 |
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import unittest
from compiler.consts import CO_GENERATOR
#-----------------------------------------------------------------------------
# Classes and... | IPython/testing/_paramtestpy2.py |
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import unittest
from compiler.consts import CO_GENERATOR
#-----------------------------------------------------------------------------
# Classes and... | 0.542621 | 0.242991 |
from nova import db
from nova import exception
from nova import objects
from nova.objects import base
from nova.objects import fields
from nova import utils
def determine_migration_type(migration):
if migration['old_instance_type_id'] != migration['new_instance_type_id']:
return 'resize'
else:
... | nova/objects/migration.py |
from nova import db
from nova import exception
from nova import objects
from nova.objects import base
from nova.objects import fields
from nova import utils
def determine_migration_type(migration):
if migration['old_instance_type_id'] != migration['new_instance_type_id']:
return 'resize'
else:
... | 0.435181 | 0.159512 |
import asyncio
import datetime
import logging
import aiohttp
import async_timeout
from homeassistant.components.camera import SUPPORT_STREAM, Camera
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.util.dt as dt_util
from . import DOMAIN as DOORBIRD_DOMAIN
_CAMERA_LAST_V... | homeassistant/components/doorbird/camera.py | import asyncio
import datetime
import logging
import aiohttp
import async_timeout
from homeassistant.components.camera import SUPPORT_STREAM, Camera
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.util.dt as dt_util
from . import DOMAIN as DOORBIRD_DOMAIN
_CAMERA_LAST_V... | 0.758779 | 0.1015 |
import os
import re
from typing import Optional
from .core._imperative_rt.common import CompNode, DeviceType
from .core._imperative_rt.common import (
get_cuda_compute_capability as _get_cuda_compute_capability,
)
from .core._imperative_rt.common import set_prealloc_config as _set_prealloc_config
from .core._imper... | imperative/python/megengine/device.py | import os
import re
from typing import Optional
from .core._imperative_rt.common import CompNode, DeviceType
from .core._imperative_rt.common import (
get_cuda_compute_capability as _get_cuda_compute_capability,
)
from .core._imperative_rt.common import set_prealloc_config as _set_prealloc_config
from .core._imper... | 0.8288 | 0.326593 |
import logging
from collections.abc import Iterable
import numpy as np
from os.path import splitext, isfile, join, dirname
__all__ = ['invert_dictionary',
'invert_dictionary_with_iterables',
'amfeti_dir']
def invert_dictionary(dict_map):
"""
Invert a dictionary-mapping such that values... | amfeti/tools.py | import logging
from collections.abc import Iterable
import numpy as np
from os.path import splitext, isfile, join, dirname
__all__ = ['invert_dictionary',
'invert_dictionary_with_iterables',
'amfeti_dir']
def invert_dictionary(dict_map):
"""
Invert a dictionary-mapping such that values... | 0.75985 | 0.388096 |
import sensor, image, time, machine, pyb, nn
barCol = 0
def DrawPgsBar(img, barLen, loopCnt, startTick, width=5):
global barCol
lnLen = (barLen * (loopCnt - (time.ticks() - startTick))) // loopCnt
if (barCol & 0x80) == 0:
c = barCol & 0x7F
else:
c = 128 - (barCol & 0x7F)
img.draw_re... | examples/rocky_test/multi_demos.py | import sensor, image, time, machine, pyb, nn
barCol = 0
def DrawPgsBar(img, barLen, loopCnt, startTick, width=5):
global barCol
lnLen = (barLen * (loopCnt - (time.ticks() - startTick))) // loopCnt
if (barCol & 0x80) == 0:
c = barCol & 0x7F
else:
c = 128 - (barCol & 0x7F)
img.draw_re... | 0.433981 | 0.224438 |
import logging
from typing import Optional, Tuple
from haversine import haversine
from .xml_parser.geometry import BoundingBox, Geometry, Point, Polygon
_LOGGER = logging.getLogger(__name__)
class GeoRssDistanceHelper:
"""Helper to calculate distances between GeoRSS geometries."""
def __init__(self):
... | aio_georss_client/geo_rss_distance_helper.py | import logging
from typing import Optional, Tuple
from haversine import haversine
from .xml_parser.geometry import BoundingBox, Geometry, Point, Polygon
_LOGGER = logging.getLogger(__name__)
class GeoRssDistanceHelper:
"""Helper to calculate distances between GeoRSS geometries."""
def __init__(self):
... | 0.959819 | 0.636141 |
from lpd.enums import Phase, State, MonitorType, MonitorMode, StatsType
from lpd.callbacks.callback_base import CallbackBase
from lpd.callbacks.callback_context import CallbackContext
from lpd.callbacks.callback_monitor import CallbackMonitorResult
from lpd.utils.torch_utils import get_lrs_from_optimizer
from typing im... | lpd/callbacks/scheduler_step.py | from lpd.enums import Phase, State, MonitorType, MonitorMode, StatsType
from lpd.callbacks.callback_base import CallbackBase
from lpd.callbacks.callback_context import CallbackContext
from lpd.callbacks.callback_monitor import CallbackMonitorResult
from lpd.utils.torch_utils import get_lrs_from_optimizer
from typing im... | 0.855625 | 0.13925 |
import netaddr
from tempest import clients
from tempest.common.utils import data_utils
from tempest import config
from tempest import exceptions
from tempest.openstack.common import log as logging
import tempest.test
CONF = config.CONF
LOG = logging.getLogger(__name__)
class BaseNetworkTest(tempest.test.BaseTestC... | tempest/api/network/base.py |
import netaddr
from tempest import clients
from tempest.common.utils import data_utils
from tempest import config
from tempest import exceptions
from tempest.openstack.common import log as logging
import tempest.test
CONF = config.CONF
LOG = logging.getLogger(__name__)
class BaseNetworkTest(tempest.test.BaseTestC... | 0.546738 | 0.212681 |
Based on the OpenAPI 3.0.2 Specification:
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md
Inspired by FastAPI:
https://github.com/tiangolo/fastapi
"""
from enum import Enum
from typing import Any, Dict, List, Optional, Sequence, Union
from pydantic import AnyUrl, Field
from inmanta.data.mod... | src/inmanta/protocol/openapi/model.py | Based on the OpenAPI 3.0.2 Specification:
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md
Inspired by FastAPI:
https://github.com/tiangolo/fastapi
"""
from enum import Enum
from typing import Any, Dict, List, Optional, Sequence, Union
from pydantic import AnyUrl, Field
from inmanta.data.mod... | 0.936677 | 0.583797 |
import copy
import pytest
import typing
import argparse
from mitmproxy import options
from mitmproxy import optmanager
from mitmproxy import exceptions
class TO(optmanager.OptManager):
def __init__(self):
super().__init__()
self.add_option("one", typing.Optional[int], None, "help")
self.a... | test/mitmproxy/test_optmanager.py | import copy
import pytest
import typing
import argparse
from mitmproxy import options
from mitmproxy import optmanager
from mitmproxy import exceptions
class TO(optmanager.OptManager):
def __init__(self):
super().__init__()
self.add_option("one", typing.Optional[int], None, "help")
self.a... | 0.64232 | 0.329742 |
from ...layers import *
def conv_2d(ni, nf, ks, stride): return nn.Conv2d(ni, nf, kernel_size=ks, stride=stride, padding=ks//2, bias=False)
def bn(ni, init_zero=False):
m = nn.BatchNorm2d(ni)
m.weight.data.fill_(0 if init_zero else 1)
m.bias.data.zero_()
return m
def bn_relu_conv(ni, nf, ks, stride,... | code_summarization_transfer_learning/fastai/tutorials/fastai/models/cifar10/wideresnet.py |
from ...layers import *
def conv_2d(ni, nf, ks, stride): return nn.Conv2d(ni, nf, kernel_size=ks, stride=stride, padding=ks//2, bias=False)
def bn(ni, init_zero=False):
m = nn.BatchNorm2d(ni)
m.weight.data.fill_(0 if init_zero else 1)
m.bias.data.zero_()
return m
def bn_relu_conv(ni, nf, ks, stride,... | 0.926777 | 0.409162 |
from typing import (Any, Callable, Iterable, Sequence, TypeVar, Union, Tuple,
FrozenSet, TYPE_CHECKING, Iterator)
from cirq import protocols
from cirq.ops import raw_types
if TYPE_CHECKING:
import cirq
TSelf_Moment = TypeVar('TSelf_Moment', bound='Moment')
class Moment:
"""A simplified t... | cirq/ops/moment.py | from typing import (Any, Callable, Iterable, Sequence, TypeVar, Union, Tuple,
FrozenSet, TYPE_CHECKING, Iterator)
from cirq import protocols
from cirq.ops import raw_types
if TYPE_CHECKING:
import cirq
TSelf_Moment = TypeVar('TSelf_Moment', bound='Moment')
class Moment:
"""A simplified t... | 0.966584 | 0.54256 |
def add(x, y):
"""
Adds two Galois field arrays element-wise.
References
----------
* https://numpy.org/doc/stable/reference/generated/numpy.add.html
Examples
--------
.. ipython:: python
GF = galois.GF(31)
x = GF.Random(10); x
y = GF.Random(10); y
np.a... | np/arithmetic.py | def add(x, y):
"""
Adds two Galois field arrays element-wise.
References
----------
* https://numpy.org/doc/stable/reference/generated/numpy.add.html
Examples
--------
.. ipython:: python
GF = galois.GF(31)
x = GF.Random(10); x
y = GF.Random(10); y
np.a... | 0.950261 | 0.624122 |
from datetime import datetime
from vnpy.api.sopt import (
MdApi,
TdApi,
THOST_FTDC_OAS_Submitted,
THOST_FTDC_OAS_Accepted,
THOST_FTDC_OAS_Rejected,
THOST_FTDC_OST_NoTradeQueueing,
THOST_FTDC_OST_PartTradedQueueing,
THOST_FTDC_OST_AllTraded,
THOST_FTDC_OST_Canceled,
THOST_FTDC_D_... | vnpy/gateway/sopt/sopt_gateway.py | from datetime import datetime
from vnpy.api.sopt import (
MdApi,
TdApi,
THOST_FTDC_OAS_Submitted,
THOST_FTDC_OAS_Accepted,
THOST_FTDC_OAS_Rejected,
THOST_FTDC_OST_NoTradeQueueing,
THOST_FTDC_OST_PartTradedQueueing,
THOST_FTDC_OST_AllTraded,
THOST_FTDC_OST_Canceled,
THOST_FTDC_D_... | 0.521471 | 0.083292 |
from neutron.common import constants
from neutron.db import external_net_db
from neutron.plugins.ml2 import db as db_ml2
from neutron.plugins.ml2 import driver_api as api
from oslo_config import cfg
from oslo_log import log as logging
from sqlalchemy.orm import exc as sa_exc
from networking_nec.nwa.common import util... | networking_nec/nwa/l2/utils.py |
from neutron.common import constants
from neutron.db import external_net_db
from neutron.plugins.ml2 import db as db_ml2
from neutron.plugins.ml2 import driver_api as api
from oslo_config import cfg
from oslo_log import log as logging
from sqlalchemy.orm import exc as sa_exc
from networking_nec.nwa.common import util... | 0.379378 | 0.054399 |
from nose.tools import *
from networkx import *
from networkx.generators.bipartite import *
"""Generators - Bipartite
----------------------
"""
class TestGeneratorsBipartite():
def test_configuration_model(self):
aseq=[3,3,3,3]
bseq=[2,2,2,2,2]
assert_raises(networkx.exception.NetworkXEr... | networkx/generators/tests/test_bipartite.py |
from nose.tools import *
from networkx import *
from networkx.generators.bipartite import *
"""Generators - Bipartite
----------------------
"""
class TestGeneratorsBipartite():
def test_configuration_model(self):
aseq=[3,3,3,3]
bseq=[2,2,2,2,2]
assert_raises(networkx.exception.NetworkXEr... | 0.687315 | 0.785987 |
from future import standard_library
standard_library.install_aliases()
import logging
import threading
from urllib.parse import urlparse
from hadoop.fs.webhdfs import WebHdfs as HadoopWebHdfs
from hadoop.fs.exceptions import WebHdfsException
from hadoop.hdfs_site import get_umask_mode
from desktop.lib.rest import ht... | desktop/libs/azure/src/azure/adls/webhdfs.py | from future import standard_library
standard_library.install_aliases()
import logging
import threading
from urllib.parse import urlparse
from hadoop.fs.webhdfs import WebHdfs as HadoopWebHdfs
from hadoop.fs.exceptions import WebHdfsException
from hadoop.hdfs_site import get_umask_mode
from desktop.lib.rest import ht... | 0.44071 | 0.054049 |
import json
import discord
from .modal import Modal
from discord.utils import MISSING
from discord.http import Route
from .enums import ApplicationCommandType, PermissionType
from typing import List, Optional, Union, Dict
from typing import Optional, Any, Union, Sequence, Iterable, NamedTuple, List, Dict
class Applic... | src/app_util/app.py | import json
import discord
from .modal import Modal
from discord.utils import MISSING
from discord.http import Route
from .enums import ApplicationCommandType, PermissionType
from typing import List, Optional, Union, Dict
from typing import Optional, Any, Union, Sequence, Iterable, NamedTuple, List, Dict
class Applic... | 0.724968 | 0.107063 |
from decimal import Decimal
import itertools
from test_framework.test_framework import XSNTestFramework
from test_framework.util import (
assert_equal,
assert_greater_than,
assert_raises_rpc_error,
connect_nodes_bi,
sync_blocks,
sync_mempools,
)
class AddressTypeTest(XSNTestFramework):
def... | test/functional/wallet_address_types.py | from decimal import Decimal
import itertools
from test_framework.test_framework import XSNTestFramework
from test_framework.util import (
assert_equal,
assert_greater_than,
assert_raises_rpc_error,
connect_nodes_bi,
sync_blocks,
sync_mempools,
)
class AddressTypeTest(XSNTestFramework):
def... | 0.66356 | 0.495117 |
from __future__ import absolute_import, division, print_function, unicode_literals
from test_framework.mininode import CTransaction, CTxOut, hash256
import sys
bchr = chr
bord = ord
if sys.version > '3':
long = int
bchr = lambda x: bytes([x])
bord = lambda x: x
import copy
import struct
import test_fram... | qa/rpc-tests/test_framework/script.py | from __future__ import absolute_import, division, print_function, unicode_literals
from test_framework.mininode import CTransaction, CTxOut, hash256
import sys
bchr = chr
bord = ord
if sys.version > '3':
long = int
bchr = lambda x: bytes([x])
bord = lambda x: x
import copy
import struct
import test_fram... | 0.400163 | 0.215598 |
__all__ = ['CIFARPyramidNet', 'pyramidnet110_a48_cifar10', 'pyramidnet110_a48_cifar100', 'pyramidnet110_a84_cifar10',
'pyramidnet110_a84_cifar100', 'pyramidnet110_a270_cifar10', 'pyramidnet110_a270_cifar100',
'pyramidnet164_a270_bn_cifar10', 'pyramidnet164_a270_bn_cifar100', 'pyramidnet200_a240_bn... | chainer_/chainercv2/models/pyramidnet_cifar.py | __all__ = ['CIFARPyramidNet', 'pyramidnet110_a48_cifar10', 'pyramidnet110_a48_cifar100', 'pyramidnet110_a84_cifar10',
'pyramidnet110_a84_cifar100', 'pyramidnet110_a270_cifar10', 'pyramidnet110_a270_cifar100',
'pyramidnet164_a270_bn_cifar10', 'pyramidnet164_a270_bn_cifar100', 'pyramidnet200_a240_bn... | 0.846006 | 0.347205 |
from django.db import connection
from django.contrib.gis.gdal import GDAL_VERSION
from django.contrib.gis.tests.utils import mysql, no_mysql, oracle, postgis, spatialite
from django.utils import unittest
test_srs = ({'srid' : 4326,
'auth_name' : ('EPSG', True),
'auth_srid' : 4326,
... | src/django-nonrel/django/contrib/gis/tests/test_spatialrefsys.py | from django.db import connection
from django.contrib.gis.gdal import GDAL_VERSION
from django.contrib.gis.tests.utils import mysql, no_mysql, oracle, postgis, spatialite
from django.utils import unittest
test_srs = ({'srid' : 4326,
'auth_name' : ('EPSG', True),
'auth_srid' : 4326,
... | 0.459561 | 0.210827 |
import msrest.serialization
class AccountSasParameters(msrest.serialization.Model):
"""The parameters to list SAS credentials of a storage account.
All required parameters must be populated in order to send to Azure.
:param services: Required. The signed services accessible with the account SAS. Possib... | sdk/storage/azure-mgmt-storage/azure/mgmt/storage/v2018_02_01/models/_models.py |
import msrest.serialization
class AccountSasParameters(msrest.serialization.Model):
"""The parameters to list SAS credentials of a storage account.
All required parameters must be populated in order to send to Azure.
:param services: Required. The signed services accessible with the account SAS. Possib... | 0.835484 | 0.389082 |
import logging
import time
from sakuraio.hardware.rpi import SakuraIOSMBus
logger = logging.getLogger(__name__)
def upload(filename):
logger.info("start upload %s", filename)
data = None
with open(filename, "rb") as f:
data = f.read()
sakuraio = SakuraIOSMBus()
# Check online
if no... | fileupload/raspberrypi/sakuraio-upload.py | import logging
import time
from sakuraio.hardware.rpi import SakuraIOSMBus
logger = logging.getLogger(__name__)
def upload(filename):
logger.info("start upload %s", filename)
data = None
with open(filename, "rb") as f:
data = f.read()
sakuraio = SakuraIOSMBus()
# Check online
if no... | 0.404155 | 0.17522 |
import random
import re
from selenium import webdriver
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from yahooquery.ut... | yahooquery/login.py | import random
import re
from selenium import webdriver
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from yahooquery.ut... | 0.216508 | 0.041037 |
import ast
import functools
import inspect
import textwrap
import types
from contextlib import contextmanager
from typing import Any, Dict, Union
from pyccolo.ast_rewriter import AstRewriter
from pyccolo.emit_event import _TRACER_STACK, allow_reentrant_event_handling, SkipAll
from pyccolo.extra_builtins import make_gua... | pyccolo/__init__.py | import ast
import functools
import inspect
import textwrap
import types
from contextlib import contextmanager
from typing import Any, Dict, Union
from pyccolo.ast_rewriter import AstRewriter
from pyccolo.emit_event import _TRACER_STACK, allow_reentrant_event_handling, SkipAll
from pyccolo.extra_builtins import make_gua... | 0.621081 | 0.061565 |
import os
import re
from thefuck.utils import get_closest, replace_command
from thefuck.specific.brew import get_brew_path_prefix, brew_available
BREW_CMD_PATH = '/Library/Homebrew/cmd'
TAP_PATH = '/Library/Taps'
TAP_CMD_PATH = '/%s/%s/cmd'
enabled_by_default = brew_available
def _get_brew_commands(brew_path_prefix... | thefuck/rules/brew_unknown_command.py | import os
import re
from thefuck.utils import get_closest, replace_command
from thefuck.specific.brew import get_brew_path_prefix, brew_available
BREW_CMD_PATH = '/Library/Homebrew/cmd'
TAP_PATH = '/Library/Taps'
TAP_CMD_PATH = '/%s/%s/cmd'
enabled_by_default = brew_available
def _get_brew_commands(brew_path_prefix... | 0.341363 | 0.084455 |
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration, ThisLaunchFileDir
def generate_launch_description():
# Declare argument... | ur_bringup/launch/ur10.launch.py |
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration, ThisLaunchFileDir
def generate_launch_description():
# Declare argument... | 0.755817 | 0.349616 |
import requests
from pprint import pprint
CMR_OPS = 'https://cmr.earthdata.nasa.gov/search'
collection_url = 'https://cmr.earthdata.nasa.gov/search/collections'
var_url = "https://cmr.earthdata.nasa.gov/search/variables"
def find_dataset(provider='podaac',
keywords=['swot','level-2']):
"""
Fin... | notebooks/meetings_workshops/20220330_ASAP_SWG/utils.py | import requests
from pprint import pprint
CMR_OPS = 'https://cmr.earthdata.nasa.gov/search'
collection_url = 'https://cmr.earthdata.nasa.gov/search/collections'
var_url = "https://cmr.earthdata.nasa.gov/search/variables"
def find_dataset(provider='podaac',
keywords=['swot','level-2']):
"""
Fin... | 0.394551 | 0.17434 |
import collections
import datetime
import enum
import hashlib
import logging
import re
import time
import uuid
from concurrent.futures import as_completed
import six
from azure.graphrbac.models import DirectoryObject, GetObjectsParameters
from azure.mgmt.managementgroups import ManagementGroupsAPI
from azure.mgmt.web.... | tools/c7n_azure/c7n_azure/utils.py | import collections
import datetime
import enum
import hashlib
import logging
import re
import time
import uuid
from concurrent.futures import as_completed
import six
from azure.graphrbac.models import DirectoryObject, GetObjectsParameters
from azure.mgmt.managementgroups import ManagementGroupsAPI
from azure.mgmt.web.... | 0.638385 | 0.083404 |
class Baker:
"""
In certain situations it is necessary to serialize transforms into
a variety of application specific LUT formats. The Baker can be
used to create lut formats that OCIO supports for writing.
**Usage Example:** *Bake a houdini sRGB viewer LUT*
.. code-block:: python
im... | src/bindings/python/DocStrings/Baker.py |
class Baker:
"""
In certain situations it is necessary to serialize transforms into
a variety of application specific LUT formats. The Baker can be
used to create lut formats that OCIO supports for writing.
**Usage Example:** *Bake a houdini sRGB viewer LUT*
.. code-block:: python
im... | 0.950434 | 0.614278 |
from torchvision.transforms.functional import *
def batch_denormalize(tensor, mean, std, inplace=False):
"""Normalize a tensor image with mean and standard deviation.
.. note::
This transform acts out_testset of place by default, i.e., it does not mutates the input tensor.
See :class:`~torchvisi... | utils/func.py | from torchvision.transforms.functional import *
def batch_denormalize(tensor, mean, std, inplace=False):
"""Normalize a tensor image with mean and standard deviation.
.. note::
This transform acts out_testset of place by default, i.e., it does not mutates the input tensor.
See :class:`~torchvisi... | 0.949704 | 0.770594 |
import copy
import os
import queue
from time import sleep
import click
import gui
from dots.interpreter import AsciiDotsInterpreter
from dots.environment import Env
from dots.callbacks import IOCallbacksStorage
class CallbacksRelay(IOCallbacksStorage):
"""Stores the outputs of the interpreter untill processed.... | debugger.py |
import copy
import os
import queue
from time import sleep
import click
import gui
from dots.interpreter import AsciiDotsInterpreter
from dots.environment import Env
from dots.callbacks import IOCallbacksStorage
class CallbacksRelay(IOCallbacksStorage):
"""Stores the outputs of the interpreter untill processed.... | 0.538741 | 0.122839 |
findreplace = [
('materialVersion','2.0.0-rc01'),
('core_commonVersion','2.0.0-rc01'),
('coreVersion','2.0.0-rc01'),
('core_testingVersion','2.0.0-rc01'),
('core_runtimeVersion','2.0.0-rc01'),
('lifecycle_commonVersion','2.0.0-rc01'),
('lifecycle_common_java8Version','2.0.0-rc01'),
('lifecycle_compilerVersion'... | AndroidXMigration/dependency_lib_version.py |
findreplace = [
('materialVersion','2.0.0-rc01'),
('core_commonVersion','2.0.0-rc01'),
('coreVersion','2.0.0-rc01'),
('core_testingVersion','2.0.0-rc01'),
('core_runtimeVersion','2.0.0-rc01'),
('lifecycle_commonVersion','2.0.0-rc01'),
('lifecycle_common_java8Version','2.0.0-rc01'),
('lifecycle_compilerVersion'... | 0.187951 | 0.052814 |
import speech_recognition as sr
from pydub import AudioSegment, silence
import pandas as pd
import os
import shutil
import time
import json
import traceback
# Wav file correction
def export_corrected_wav(file):
audio = AudioSegment.from_file(file, format="wav")
return audio
# Channels split
def split_channels... | app.py | import speech_recognition as sr
from pydub import AudioSegment, silence
import pandas as pd
import os
import shutil
import time
import json
import traceback
# Wav file correction
def export_corrected_wav(file):
audio = AudioSegment.from_file(file, format="wav")
return audio
# Channels split
def split_channels... | 0.26588 | 0.110136 |
import numpy as np
def TM_fluid(layer, kx, om):
"""
TM_fluid returns the 2x2 Transfer Matrix of a fluid layer
Parameters
----------
layer : Layer
kx : transversal wave number
om : circular frequency
Returns
-------
2x2 numpy array
"""
h = layer.d
rho = layer.medi... | pyPLANES/pw/transfert_matrices.py |
import numpy as np
def TM_fluid(layer, kx, om):
"""
TM_fluid returns the 2x2 Transfer Matrix of a fluid layer
Parameters
----------
layer : Layer
kx : transversal wave number
om : circular frequency
Returns
-------
2x2 numpy array
"""
h = layer.d
rho = layer.medi... | 0.855746 | 0.789761 |
import Tkinter
from Tkinter import Button, Canvas, Entry, Frame, Scrollbar
import tkFileDialog
import tkMessageBox
from Tix import Control
from PIL import Image, ImageTk
import math
import os
class ImageSelectWindow(object):
def __init__(self):
self.image_Wid = 300
self.image_Hei = 300
... | Python/AI-ToolBox/preprocess ToolBox/data_annotation_tool/image_select_tool.py | import Tkinter
from Tkinter import Button, Canvas, Entry, Frame, Scrollbar
import tkFileDialog
import tkMessageBox
from Tix import Control
from PIL import Image, ImageTk
import math
import os
class ImageSelectWindow(object):
def __init__(self):
self.image_Wid = 300
self.image_Hei = 300
... | 0.182462 | 0.091099 |
class Matrice:
"""La Matrice est l'objet qui contient tous les chiffres du Sudoku dans un tableau de 9x9"""
def __init__(self, init : [] = None) -> None:
"""Constructeur de l'instance qui initialise la matrice 9*9 à partir d'un tableau existant,
s'il est transmis, à vide sinon."""
... | matrice.py |
class Matrice:
"""La Matrice est l'objet qui contient tous les chiffres du Sudoku dans un tableau de 9x9"""
def __init__(self, init : [] = None) -> None:
"""Constructeur de l'instance qui initialise la matrice 9*9 à partir d'un tableau existant,
s'il est transmis, à vide sinon."""
... | 0.468791 | 0.679445 |
from discord import Message, Embed
from distest.exceptions import ResponseDidNotMatchError
import re
async def assert_embed_equals(
message: Message, matches: Embed, attributes_to_prove: list = None,
):
"""If ``matches`` doesn't match the embed of ``message``, fail the test.
Checks only the attributes ... | distest/TestInterface/_embeds.py | from discord import Message, Embed
from distest.exceptions import ResponseDidNotMatchError
import re
async def assert_embed_equals(
message: Message, matches: Embed, attributes_to_prove: list = None,
):
"""If ``matches`` doesn't match the embed of ``message``, fail the test.
Checks only the attributes ... | 0.828141 | 0.355831 |
from runner.koan import *
class AboutStrings(Koan):
def test_double_quoted_strings_are_strings(self):
string = "Hello, world."
self.assertEqual(True, isinstance(string, str))
def test_single_quoted_strings_are_also_strings(self):
string = 'Goodbye, world.'
self.assertEqual(Tr... | python3/koans/about_strings.py |
from runner.koan import *
class AboutStrings(Koan):
def test_double_quoted_strings_are_strings(self):
string = "Hello, world."
self.assertEqual(True, isinstance(string, str))
def test_single_quoted_strings_are_also_strings(self):
string = 'Goodbye, world.'
self.assertEqual(Tr... | 0.539954 | 0.403567 |
"""Module containing class for Snowflake EDW service resource hosted on AWS."""
import copy
import json
from typing import Any, Dict, List
from absl import flags
from perfkitbenchmarker import edw_service
from perfkitbenchmarker.providers import aws
FLAGS = flags.FLAGS
def GetSnowflakeClientInterface(warehouse: st... | perfkitbenchmarker/providers/aws/snowflake.py | """Module containing class for Snowflake EDW service resource hosted on AWS."""
import copy
import json
from typing import Any, Dict, List
from absl import flags
from perfkitbenchmarker import edw_service
from perfkitbenchmarker.providers import aws
FLAGS = flags.FLAGS
def GetSnowflakeClientInterface(warehouse: st... | 0.881063 | 0.287618 |
__docformat__ = 'restructuredtext'
import os
from os.path import join as opj
from ...api import (
clone,
download_url,
Dataset,
)
from ...utils import (
chpwd,
Path,
)
from ...downloaders.tests.utils import get_test_providers
from ...tests.utils import (
assert_cwd_unchanged,
assert_false,... | datalad/interface/tests/test_download_url.py | __docformat__ = 'restructuredtext'
import os
from os.path import join as opj
from ...api import (
clone,
download_url,
Dataset,
)
from ...utils import (
chpwd,
Path,
)
from ...downloaders.tests.utils import get_test_providers
from ...tests.utils import (
assert_cwd_unchanged,
assert_false,... | 0.486819 | 0.310511 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import gin
from tensor2tensor.envs import gym_env_problem
from tensor2tensor.rl import gym_utils
from tensorflow import test
from trax import models
from trax.rl import envs # pylint: disabl... | trax/rl/simple_trainer_test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import gin
from tensor2tensor.envs import gym_env_problem
from tensor2tensor.rl import gym_utils
from tensorflow import test
from trax import models
from trax.rl import envs # pylint: disabl... | 0.690246 | 0.113481 |
from config_models.models import ConfigurationModel
from django.db import models
from . import utils
from .mobile_platform import PLATFORM_CLASSES
class MobileApiConfig(ConfigurationModel):
"""
Configuration for the video upload feature.
The order in which the comma-separated list of names of profiles ... | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/mobile_api/models.py | from config_models.models import ConfigurationModel
from django.db import models
from . import utils
from .mobile_platform import PLATFORM_CLASSES
class MobileApiConfig(ConfigurationModel):
"""
Configuration for the video upload feature.
The order in which the comma-separated list of names of profiles ... | 0.751101 | 0.205834 |
import base64
import contextlib
import logging
import os
import random
import string
import yaml
from teuthology import misc as teuthology
from teuthology import contextutil
from teuthology.config import config as teuth_config
from teuthology.orchestra import run
from teuthology.orchestra.connection import split_user
... | qa/tasks/s3readwrite.py | import base64
import contextlib
import logging
import os
import random
import string
import yaml
from teuthology import misc as teuthology
from teuthology import contextutil
from teuthology.config import config as teuth_config
from teuthology.orchestra import run
from teuthology.orchestra.connection import split_user
... | 0.284775 | 0.161999 |
from django.dispatch import receiver
from django.urls import resolve, reverse
from django.utils.translation import gettext_lazy as _
from pretix.base.signals import logentry_display
from pretix.control.signals import nav_event
@receiver(nav_event, dispatch_uid="sendmail_nav")
def control_nav_import(sender, request=N... | src/pretix/plugins/sendmail/signals.py | from django.dispatch import receiver
from django.urls import resolve, reverse
from django.utils.translation import gettext_lazy as _
from pretix.base.signals import logentry_display
from pretix.control.signals import nav_event
@receiver(nav_event, dispatch_uid="sendmail_nav")
def control_nav_import(sender, request=N... | 0.47171 | 0.084568 |
import os
import re
import shutil
import tempfile
import xml.etree.ElementTree as ET
import zipfile
from typing import BinaryIO, Dict, Optional, TextIO
from haoda import util
from haoda.backend import xilinx as backend
__all__ = (
'ReportDirUtil',
'ReportXoUtil',
'RtlHlsInfo',
)
REPORT_UTIL_COMMANDS = r'... | haoda/report/xilinx/rtl/generator.py | import os
import re
import shutil
import tempfile
import xml.etree.ElementTree as ET
import zipfile
from typing import BinaryIO, Dict, Optional, TextIO
from haoda import util
from haoda.backend import xilinx as backend
__all__ = (
'ReportDirUtil',
'ReportXoUtil',
'RtlHlsInfo',
)
REPORT_UTIL_COMMANDS = r'... | 0.67854 | 0.11187 |
from typing import Tuple, List
from pathlib import Path
from itertools import chain
from functools import reduce
import cv2
import numpy as np
import tensorflow.keras as keras
from utils.transform import Transform
class Eval:
def __init__(self, filename: str):
self.image = np.expand_dims(cv2.imread(file... | ImageDenoising/utils/data.py | from typing import Tuple, List
from pathlib import Path
from itertools import chain
from functools import reduce
import cv2
import numpy as np
import tensorflow.keras as keras
from utils.transform import Transform
class Eval:
def __init__(self, filename: str):
self.image = np.expand_dims(cv2.imread(file... | 0.893135 | 0.318591 |
import os
import functools
from enum import IntEnum
from PyQt5.QtWidgets import QSplitter, QFrame, QVBoxLayout, QDialogButtonBox, \
QToolBar, QTabBar, QWidget, QDialog, QGroupBox, QFormLayout, QSpinBox, QAction, \
QGraphicsView, QGraphicsScene, QAbstractItemView, QActionGroup, \
QDesktopWidget, QFil... | app/editor/tilemap_editor.py | import os
import functools
from enum import IntEnum
from PyQt5.QtWidgets import QSplitter, QFrame, QVBoxLayout, QDialogButtonBox, \
QToolBar, QTabBar, QWidget, QDialog, QGroupBox, QFormLayout, QSpinBox, QAction, \
QGraphicsView, QGraphicsScene, QAbstractItemView, QActionGroup, \
QDesktopWidget, QFil... | 0.512937 | 0.122444 |
[
{
'date': '2018-01-01',
'description': 'Nýársdagur',
'locale': 'is-IS',
'notes': '',
'region': '',
'type': 'NRF'
},
{
'date': '2018-03-29',
'description': 'Skírdagur',
'locale': 'is-IS',
'notes': '',
'region': '',
... | tests/snapshots/snap_test_holidata/test_holidata_produces_holidays_for_locale_and_year[is_IS-2018] 1.py | [
{
'date': '2018-01-01',
'description': 'Nýársdagur',
'locale': 'is-IS',
'notes': '',
'region': '',
'type': 'NRF'
},
{
'date': '2018-03-29',
'description': 'Skírdagur',
'locale': 'is-IS',
'notes': '',
'region': '',
... | 0.373304 | 0.162912 |
import pickle
from pathlib import Path
from CountryClass import *
def initCountryStruct():
dataFile = Path("./data.bin")
if not dataFile.is_file():
print("Generating map data...")
listOfCountries = set([])
# We define each country name and continent. Then, we add the to o... | DataInit.py | import pickle
from pathlib import Path
from CountryClass import *
def initCountryStruct():
dataFile = Path("./data.bin")
if not dataFile.is_file():
print("Generating map data...")
listOfCountries = set([])
# We define each country name and continent. Then, we add the to o... | 0.159446 | 0.205456 |
from __future__ import annotations
import ipaddress
import logging
import re
from typing import Any, Final
from pdunehd import DuneHDPlayer
import voluptuous as vol
from openpeerpower import config_entries, exceptions
from openpeerpower.const import CONF_HOST
from openpeerpower.data_entry_flow import FlowResult
fro... | openpeerpower/components/dunehd/config_flow.py | from __future__ import annotations
import ipaddress
import logging
import re
from typing import Any, Final
from pdunehd import DuneHDPlayer
import voluptuous as vol
from openpeerpower import config_entries, exceptions
from openpeerpower.const import CONF_HOST
from openpeerpower.data_entry_flow import FlowResult
fro... | 0.860193 | 0.127435 |
import pandas as pd
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
import numpy as np
class Preprocessor:
def __init__(self):
pass
def normalize(self, df, columns):
min_max_scaler = preprocessing.MinMaxScaler()
df[columns] = min_max_scaler.fit_t... | src/util/Preprocessor.py | import pandas as pd
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
import numpy as np
class Preprocessor:
def __init__(self):
pass
def normalize(self, df, columns):
min_max_scaler = preprocessing.MinMaxScaler()
df[columns] = min_max_scaler.fit_t... | 0.815453 | 0.444505 |
from Jumpscale import j
builder_method = j.baseclasses.builder_method
class BuilderARDB(j.baseclasses.builder):
__jslocation__ = "j.builders.db.ardb"
def _init(self, **kwargs):
# forest db (backend engine) paths
self.CODE_DIR_FDB = self._replace("{DIR_BUILD}/github/couchbase/forestdb")
... | JumpscaleBuildersExtra/db/BuilderARDB.py | from Jumpscale import j
builder_method = j.baseclasses.builder_method
class BuilderARDB(j.baseclasses.builder):
__jslocation__ = "j.builders.db.ardb"
def _init(self, **kwargs):
# forest db (backend engine) paths
self.CODE_DIR_FDB = self._replace("{DIR_BUILD}/github/couchbase/forestdb")
... | 0.60054 | 0.088426 |