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 argparse
import json
import os
import sys
import base64
import requests
def get_header(tenant, user, password):
"""Return an authorzation header"""
auth = bytes(f"{tenant}/{user}:{password}", "utf-8")
return {b"Authorization": b"Basic " + base64.b64encode(auth)}
def get_id(header, device, url, v... | ci/find_device_id.py | import argparse
import json
import os
import sys
import base64
import requests
def get_header(tenant, user, password):
"""Return an authorzation header"""
auth = bytes(f"{tenant}/{user}:{password}", "utf-8")
return {b"Authorization": b"Basic " + base64.b64encode(auth)}
def get_id(header, device, url, v... | 0.29798 | 0.104798 |
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
import sys
import os
from pathlib import Path
src_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "src")
sys.path.append(s... | server_main.py | from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
import sys
import os
from pathlib import Path
src_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "src")
sys.path.append(s... | 0.285173 | 0.049681 |
import typing
from ucloud.core.client import Client
from ucloud.services.cube.schemas import apis
class CubeClient(Client):
def __init__(
self, config: dict, transport=None, middleware=None, logger=None
):
super(CubeClient, self).__init__(config, transport, middleware, logger)
def crea... | ucloud/services/cube/client.py |
import typing
from ucloud.core.client import Client
from ucloud.services.cube.schemas import apis
class CubeClient(Client):
def __init__(
self, config: dict, transport=None, middleware=None, logger=None
):
super(CubeClient, self).__init__(config, transport, middleware, logger)
def crea... | 0.489259 | 0.142172 |
import gemmi
import unittest
from swamp.utils import *
from conkit.core import ContactMap, Contact
class UtilsTestCase(unittest.TestCase):
def test_1(self):
contact_map = ContactMap("test")
contact_map.add(Contact(1, 4, 1.0))
contact_map.add(Contact(2, 4, 1.0))
contact_map.add(Con... | swamp/utils/tests/test_utils.py | import gemmi
import unittest
from swamp.utils import *
from conkit.core import ContactMap, Contact
class UtilsTestCase(unittest.TestCase):
def test_1(self):
contact_map = ContactMap("test")
contact_map.add(Contact(1, 4, 1.0))
contact_map.add(Contact(2, 4, 1.0))
contact_map.add(Con... | 0.331877 | 0.233422 |
from pyspark.sql.types import StructType, StructField, \
IntegerType, TimestampType, StringType, DoubleType
citibike_schema = StructType(
[
StructField('tripduration', IntegerType(), True),
StructField('starttime', TimestampType(), True),
StructField('stoptime', TimestampType(), True),
... | src/config/schemas.py | from pyspark.sql.types import StructType, StructField, \
IntegerType, TimestampType, StringType, DoubleType
citibike_schema = StructType(
[
StructField('tripduration', IntegerType(), True),
StructField('starttime', TimestampType(), True),
StructField('stoptime', TimestampType(), True),
... | 0.709523 | 0.423041 |
from jinja2 import Template
# >>> template = Template('Hello {{ name }}!')
# >>> template.render(name='<NAME>')
template = ''' <div class="col-md-4 col-sm-6 portfolio-item">
<div>
<img src="img/games/jigsaw_puzzles.png" class="img-responsive" alt="">
<... | python/generate_games.py | from jinja2 import Template
# >>> template = Template('Hello {{ name }}!')
# >>> template.render(name='<NAME>')
template = ''' <div class="col-md-4 col-sm-6 portfolio-item">
<div>
<img src="img/games/jigsaw_puzzles.png" class="img-responsive" alt="">
<... | 0.313945 | 0.295579 |
import re
FILENAME = "HPatPS.txt"
def main():
passphrase = "<PASSWORD>."
phrase = ""
escape = "escape"
while (phrase != passphrase):
print(passphrase)
print("Type the passphrase above to continue...")
phrase = input(">>> ")
if (phrase == escape):
return... | philosophers-stone.py | import re
FILENAME = "HPatPS.txt"
def main():
passphrase = "<PASSWORD>."
phrase = ""
escape = "escape"
while (phrase != passphrase):
print(passphrase)
print("Type the passphrase above to continue...")
phrase = input(">>> ")
if (phrase == escape):
return... | 0.201499 | 0.078184 |
import sys, os, shutil, stat, glob, re
from os import path
import requests
import argparse
import hashlib
class CopyScoringFiles:
ftp_scoring_files_dir = '/ebi/ftp/pub/databases/spot/pgs/scores/'
ftp_std_scoringfile_suffix = '.txt.gz'
scores_list_file = 'pgs_scores_list.txt'
log_msg = {
'new'... | release/scripts/CopyScoringFiles.py | import sys, os, shutil, stat, glob, re
from os import path
import requests
import argparse
import hashlib
class CopyScoringFiles:
ftp_scoring_files_dir = '/ebi/ftp/pub/databases/spot/pgs/scores/'
ftp_std_scoringfile_suffix = '.txt.gz'
scores_list_file = 'pgs_scores_list.txt'
log_msg = {
'new'... | 0.173323 | 0.096877 |
import os
import json
import requests
from jama import api_caller
from flask import make_response
"""Return dialog fields for Slack from Jama API
Purpose of this file is to format data in a JSON object that
Slack can handle. Each of the fucntion queries a different REST endpoint
on the Jama instance.
Attributes:
... | src/slack/slack_json_factories/dialog_json/create_fields.py | import os
import json
import requests
from jama import api_caller
from flask import make_response
"""Return dialog fields for Slack from Jama API
Purpose of this file is to format data in a JSON object that
Slack can handle. Each of the fucntion queries a different REST endpoint
on the Jama instance.
Attributes:
... | 0.687525 | 0.231593 |
import numpy
import warnings
from pychemkin.config import R_VALUE
from pychemkin.parsers import SQLParser
def determine_rxn_rate_coeff_type(type_name):
"""Helper function to determine type of
(forward) reaction rate coefficient.
Args:
=====
type_name : str, required
Type of reaction rate... | pychemkin/rxn_rate_coefficients/rxn_rate_coefficients.py |
import numpy
import warnings
from pychemkin.config import R_VALUE
from pychemkin.parsers import SQLParser
def determine_rxn_rate_coeff_type(type_name):
"""Helper function to determine type of
(forward) reaction rate coefficient.
Args:
=====
type_name : str, required
Type of reaction rate... | 0.914718 | 0.512266 |
import functools
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core... | sdk/ml/azure-ai-ml/azure/ai/ml/_restclient/model_dataplane/operations/_models_operations.py | import functools
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core... | 0.662141 | 0.068071 |
import itertools
from typing import Union, Sequence, Callable
from astlib.asdl import (VisitorBase, Constructor, Module, Field, Product, Sum,
Type, builtin_types, parse as ParseAsdl)
from astlib.cc_types import (ConstructorNode, TypeNode, ProductNode, SumEnum,
Kind... | astlib/gen_data.py | import itertools
from typing import Union, Sequence, Callable
from astlib.asdl import (VisitorBase, Constructor, Module, Field, Product, Sum,
Type, builtin_types, parse as ParseAsdl)
from astlib.cc_types import (ConstructorNode, TypeNode, ProductNode, SumEnum,
Kind... | 0.764716 | 0.381277 |
from __future__ import absolute_import, print_function
import os
import sys
import traceback
import click
from pywbem import WBEMConnection, MOFParseError
import pywbem_mock
from .config import DEFAULT_MAXPULLCNT
# __all__ = ['PYWBEMCLIConnection', 'PYWBEMCLIFakedConnection']
# pylint: disable=useless-object-inh... | pywbemtools/pywbemcli/_pywbemcli_operations.py | from __future__ import absolute_import, print_function
import os
import sys
import traceback
import click
from pywbem import WBEMConnection, MOFParseError
import pywbem_mock
from .config import DEFAULT_MAXPULLCNT
# __all__ = ['PYWBEMCLIConnection', 'PYWBEMCLIFakedConnection']
# pylint: disable=useless-object-inh... | 0.550849 | 0.078466 |
from tkinter import Tk, Text, Menu, filedialog, Label, Button, END, W, E, FALSE
from tkinter.scrolledtext import ScrolledText
from prologpy.solver import Solver
def is_file_path_selected(file_path):
return file_path is not None and file_path != ""
def get_file_contents(file_path):
"""Return a string contain... | editor.py | from tkinter import Tk, Text, Menu, filedialog, Label, Button, END, W, E, FALSE
from tkinter.scrolledtext import ScrolledText
from prologpy.solver import Solver
def is_file_path_selected(file_path):
return file_path is not None and file_path != ""
def get_file_contents(file_path):
"""Return a string contain... | 0.731826 | 0.262089 |
import argparse
import os
import psycopg2
from pirogue.utils import select_columns, insert_command, update_command, table_parts
def vw_sign_symbol(srid: int, pg_service: str = None):
"""
Creates sign_symbol view
:param srid: EPSG code for geometries
:param pg_service: the PostgreSQL service name
... | data_model/app/vw_sign_symbol.py |
import argparse
import os
import psycopg2
from pirogue.utils import select_columns, insert_command, update_command, table_parts
def vw_sign_symbol(srid: int, pg_service: str = None):
"""
Creates sign_symbol view
:param srid: EPSG code for geometries
:param pg_service: the PostgreSQL service name
... | 0.373076 | 0.137359 |
## Load packages
import pandas as pd
import numpy as np
import os
from os import scandir, listdir
# data IO
import dask as da
import dask.dataframe as dd
# Multi-threading
import multiprocessing as mp
from multiprocessing import Process, Pool, cpu_count, Array, JoinableQueue
# Garbage collection
import gc
# Erro... | avito-demand-prediction-challenge/python_codes/merge_gbm_dataset.py |
## Load packages
import pandas as pd
import numpy as np
import os
from os import scandir, listdir
# data IO
import dask as da
import dask.dataframe as dd
# Multi-threading
import multiprocessing as mp
from multiprocessing import Process, Pool, cpu_count, Array, JoinableQueue
# Garbage collection
import gc
# Erro... | 0.330795 | 0.234511 |
import base64
import json
from flask import Flask
from oauth2client.client import AccessTokenInfo
from flask_gsa import GoogleServiceAccount
import pytest
from mock import Mock
from tests.conftest import app as make_app
from tests.compat import text_type
def base64url_decode(s):
rem = len(s) % 4
if rem > ... | tests/test_flask_gsa.py |
import base64
import json
from flask import Flask
from oauth2client.client import AccessTokenInfo
from flask_gsa import GoogleServiceAccount
import pytest
from mock import Mock
from tests.conftest import app as make_app
from tests.compat import text_type
def base64url_decode(s):
rem = len(s) % 4
if rem > ... | 0.49585 | 0.260936 |
from __future__ import division, print_function
import pymysql
import argparse
parser = argparse.ArgumentParser(description="Parse the database")
parser.add_argument("--user", "-u", help="Your MySQL user name",
default="root")
parser.add_argument("--password", "-p", help="Your MySQL password")
ar... | scripts/find_movies.py |
from __future__ import division, print_function
import pymysql
import argparse
parser = argparse.ArgumentParser(description="Parse the database")
parser.add_argument("--user", "-u", help="Your MySQL user name",
default="root")
parser.add_argument("--password", "-p", help="Your MySQL password")
ar... | 0.515376 | 0.184749 |
from __future__ import print_function
import sys
import re
VERSION = '1.1.1'
colour_names = {
'bold': '1',
'black': '30',
'brown': '31',
'green': '32',
'yellow': '33',
'blue': '34',
'magenta': '35',
'cyan': '36',
'gray': ... | Source/colour_filter/__init__.py | from __future__ import print_function
import sys
import re
VERSION = '1.1.1'
colour_names = {
'bold': '1',
'black': '30',
'brown': '31',
'green': '32',
'yellow': '33',
'blue': '34',
'magenta': '35',
'cyan': '36',
'gray': ... | 0.257485 | 0.165897 |
import itertools
import os
import sys
import geopandas as gpd
import pandas as pd
from shapely.geometry import Polygon
from vtra.utils import *
from vtra.transport_flow_and_failure_functions import *
def create_hazard_attributes_for_network(intersection_dir,sector,hazard_files,hazard_df,bands,thresholds,commune_shap... | src/vtra/failure_scenario_selection/hazards_network_intersections_results_collect.py | import itertools
import os
import sys
import geopandas as gpd
import pandas as pd
from shapely.geometry import Polygon
from vtra.utils import *
from vtra.transport_flow_and_failure_functions import *
def create_hazard_attributes_for_network(intersection_dir,sector,hazard_files,hazard_df,bands,thresholds,commune_shap... | 0.589362 | 0.387777 |
import os
import sys
import types
import logging
import argparse
cmdparser = argparse.ArgumentParser(description = 'generate initial HTK V3.5 DNN model')
egroup = cmdparser.add_mutually_exclusive_group()
egroup.add_argument('-v', '--verbose', help = 'increase output verbosity', action = 'store_true', default = False)... | samples/RMHTK/python_scripts/GenInitDNN.py |
import os
import sys
import types
import logging
import argparse
cmdparser = argparse.ArgumentParser(description = 'generate initial HTK V3.5 DNN model')
egroup = cmdparser.add_mutually_exclusive_group()
egroup.add_argument('-v', '--verbose', help = 'increase output verbosity', action = 'store_true', default = False)... | 0.173673 | 0.12665 |
import sys
import qrcode
from PIL import Image, ImageColor
URL = 'cellar.casasumu.com/#u={}&p={}&b={}'
ARG_MSG = '''img width, img height, sticker width, sticker height,
left margin, right margin, top margin, bottom margin, x spacing, y spacing,
username, password, lower bottle #, upper bottle # (inclusive), dpi,
num... | qr/generate_qr_sheets.py | import sys
import qrcode
from PIL import Image, ImageColor
URL = 'cellar.casasumu.com/#u={}&p={}&b={}'
ARG_MSG = '''img width, img height, sticker width, sticker height,
left margin, right margin, top margin, bottom margin, x spacing, y spacing,
username, password, lower bottle #, upper bottle # (inclusive), dpi,
num... | 0.268749 | 0.290213 |
from colcon_core.plugin_system import get_first_line_doc
from colcon_core.plugin_system import instantiate_extensions
from colcon_core.plugin_system import order_extensions_by_priority
class EventHandlerExtensionPoint:
"""
The interface for event handler extensions.
An event handler extension processes ... | colcon_core/event_handler/__init__.py |
from colcon_core.plugin_system import get_first_line_doc
from colcon_core.plugin_system import instantiate_extensions
from colcon_core.plugin_system import order_extensions_by_priority
class EventHandlerExtensionPoint:
"""
The interface for event handler extensions.
An event handler extension processes ... | 0.858689 | 0.309359 |
import torch
import numpy as numpy
import torch.nn as nn
import torchsnooper
class lambda_loss:
def __init__(self, device, rank_list, target_list, t, b, p, num_pos, num_neg):
# self.rank_list = rank_list.unsqueeze(1)
# self.target_list = target_list.unsqueeze(1)
self.rank_list = rank_list
self... | lambda_loss.py | import torch
import numpy as numpy
import torch.nn as nn
import torchsnooper
class lambda_loss:
def __init__(self, device, rank_list, target_list, t, b, p, num_pos, num_neg):
# self.rank_list = rank_list.unsqueeze(1)
# self.target_list = target_list.unsqueeze(1)
self.rank_list = rank_list
self... | 0.195748 | 0.448909 |
import neoml.PythonWrapper as PythonWrapper
from .Dnn import Layer
from neoml.Utils import check_input_layers
class PrecisionRecall(Layer):
"""The layer that calculates the number of objects classified
correctly for either class in a binary classification scenario.
Using these statistics, you can easily c... | NeoML/Python/neoml/Dnn/PrecisionRecall.py | import neoml.PythonWrapper as PythonWrapper
from .Dnn import Layer
from neoml.Utils import check_input_layers
class PrecisionRecall(Layer):
"""The layer that calculates the number of objects classified
correctly for either class in a binary classification scenario.
Using these statistics, you can easily c... | 0.896823 | 0.749569 |
from enum import Enum
from random import choice
class BusinessType(Enum):
COMPANIES_HOUSE = "LTD, PLC or Royal Charter"
INDIVIDUAL = "Individual"
OVERSEAS_COMPANY = "Overseas company"
SOLE_TRADER = "Sole trader"
CHARITY = "Charity"
PARTNERSHIP = "Partnership"
OTHER = "Other UK business no... | directory_tests_shared/directory_tests_shared/enums.py | from enum import Enum
from random import choice
class BusinessType(Enum):
COMPANIES_HOUSE = "LTD, PLC or Royal Charter"
INDIVIDUAL = "Individual"
OVERSEAS_COMPANY = "Overseas company"
SOLE_TRADER = "Sole trader"
CHARITY = "Charity"
PARTNERSHIP = "Partnership"
OTHER = "Other UK business no... | 0.512449 | 0.116136 |
import os
import pickle
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler, FileCreatedEvent, FileDeletedEvent, FileModifiedEvent, FileMovedEvent, \
DirCreatedEvent, DirDeletedEvent, DirModifiedEvent, DirMovedEvent
from watchdog.utils.dirsna... | src/dukepy/watcher.py | import os
import pickle
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler, FileCreatedEvent, FileDeletedEvent, FileModifiedEvent, FileMovedEvent, \
DirCreatedEvent, DirDeletedEvent, DirModifiedEvent, DirMovedEvent
from watchdog.utils.dirsna... | 0.392453 | 0.068506 |
import sys
sys.path.append('../gen-py')
import random
from social_network import PostStorageService
from social_network.ttypes import Media
from social_network.ttypes import PostType
from social_network.ttypes import Creator
from social_network.ttypes import Url
from social_network.ttypes import UserMention
from socia... | socialNetwork/test/TestPostStorage.py | import sys
sys.path.append('../gen-py')
import random
from social_network import PostStorageService
from social_network.ttypes import Media
from social_network.ttypes import PostType
from social_network.ttypes import Creator
from social_network.ttypes import Url
from social_network.ttypes import UserMention
from socia... | 0.124639 | 0.060529 |
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
class RNN(nn.Module):
def __init__(self, config):
"""
type_rnn: RNN, GRU, LSTM 可选
"""
super(RNN, self).__init__()
# self.xxx = config.xxx
self.input_size = c... | module/RNN.py | import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
class RNN(nn.Module):
def __init__(self, config):
"""
type_rnn: RNN, GRU, LSTM 可选
"""
super(RNN, self).__init__()
# self.xxx = config.xxx
self.input_size = c... | 0.885798 | 0.355132 |
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium... | driver_actions.py | from selenium.webdriver import Firefox
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium... | 0.344113 | 0.102125 |
import logging
import os
from pathlib import Path
from typing import List, Union
import requests
from Xerus.settings.settings import REQUESTS_TIMEOUT, REQUESTS_HEADER
from optimade.adapters import Structure
class OptimadeQuery:
def __init__(
self,
base_url: str,
elements: List[str] = No... | Xerus/queriers/optimade.py | import logging
import os
from pathlib import Path
from typing import List, Union
import requests
from Xerus.settings.settings import REQUESTS_TIMEOUT, REQUESTS_HEADER
from optimade.adapters import Structure
class OptimadeQuery:
def __init__(
self,
base_url: str,
elements: List[str] = No... | 0.743354 | 0.242038 |
"""Common utility functions for Composer environment patch commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.composer import environments_util as environments_api_util
from googlecloudsdk.api_lib.composer import oper... | lib/googlecloudsdk/command_lib/composer/environment_patch_util.py | """Common utility functions for Composer environment patch commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.composer import environments_util as environments_api_util
from googlecloudsdk.api_lib.composer import oper... | 0.848094 | 0.225033 |
import os
import pytest
from unittest.mock import call, Mock, patch
import time
import json
from common.distributed import MultiNodeScript, MPIHandler, mpi_config_class
from test_component import (
assert_runnable_script_properties,
assert_runnable_script_metrics
)
class FakeMultiNodeScript(MultiNodeScript):
... | tests/common/test_distributed.py | import os
import pytest
from unittest.mock import call, Mock, patch
import time
import json
from common.distributed import MultiNodeScript, MPIHandler, mpi_config_class
from test_component import (
assert_runnable_script_properties,
assert_runnable_script_metrics
)
class FakeMultiNodeScript(MultiNodeScript):
... | 0.515864 | 0.338159 |
import json
import boto3
import datetime
from copy import deepcopy
from package import db_config
from package.query_db import query
from package.lambda_exception import LambdaException
# Author: <NAME>
# function creates an appointment block
# Input: supporter_id, start_date, end_date, max_num_of_appts, isReccuring... | lambdas/create_appointment_block.py | import json
import boto3
import datetime
from copy import deepcopy
from package import db_config
from package.query_db import query
from package.lambda_exception import LambdaException
# Author: <NAME>
# function creates an appointment block
# Input: supporter_id, start_date, end_date, max_num_of_appts, isReccuring... | 0.274838 | 0.106598 |
import os
from py4j.protocol import Py4JJavaError
from pypmml.base import JavaModelWrapper, PMMLContext, PmmlError
from pypmml.elements import Header
from pypmml.metadata import Field, OutputField, DataDictionary
class Model(JavaModelWrapper):
"""A PMML model.
"""
def __init__(self, java_model):
... | pypmml/model.py |
import os
from py4j.protocol import Py4JJavaError
from pypmml.base import JavaModelWrapper, PMMLContext, PmmlError
from pypmml.elements import Header
from pypmml.metadata import Field, OutputField, DataDictionary
class Model(JavaModelWrapper):
"""A PMML model.
"""
def __init__(self, java_model):
... | 0.782663 | 0.38549 |
from typing import Optional, Dict, OrderedDict, Any, Union, Literal, Tuple, NamedTuple
from dataclasses import dataclass, field
import requests
import urllib
from http.cookiejar import CookieJar
from .options import RequestOptions, UserCookie, LoginPolicy, LuweiCookieFormat
from .requestutils import BandwidthUsage, g... | anobbsclient/baseclient.py | from typing import Optional, Dict, OrderedDict, Any, Union, Literal, Tuple, NamedTuple
from dataclasses import dataclass, field
import requests
import urllib
from http.cookiejar import CookieJar
from .options import RequestOptions, UserCookie, LoginPolicy, LuweiCookieFormat
from .requestutils import BandwidthUsage, g... | 0.705582 | 0.131982 |
from __future__ import division, print_function, absolute_import
import numpy as np
from scipy.linalg import svd
__all__ = ['polar']
def polar(a, side="right"):
"""
Compute the polar decomposition.
Returns the factors of the polar decomposition [1]_ `u` and `p` such
that ``a = up`` (if `side` is "... | dipy/fixes/scipy.py | from __future__ import division, print_function, absolute_import
import numpy as np
from scipy.linalg import svd
__all__ = ['polar']
def polar(a, side="right"):
"""
Compute the polar decomposition.
Returns the factors of the polar decomposition [1]_ `u` and `p` such
that ``a = up`` (if `side` is "... | 0.941735 | 0.644575 |
from django.db import models
from django.contrib.auth import get_user_model
from multiselectfield import MultiSelectField
from master.models import Department, Semester
from teachers.models import Teacher
User = get_user_model()
class Stream(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
... | classes/models.py | from django.db import models
from django.contrib.auth import get_user_model
from multiselectfield import MultiSelectField
from master.models import Department, Semester
from teachers.models import Teacher
User = get_user_model()
class Stream(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
... | 0.589598 | 0.163947 |
import torch
import torch.nn as nn
class Cell(nn.Module):
def __init__(self, conv, in_channels, out_channels, double=False):
super().__init__()
self.conv_type = conv
self.double = double
self.conv_i1 = nn.Conv3d(in_channels, in_channels, kernel_size=1,
... | models/backbone/cells.py | import torch
import torch.nn as nn
class Cell(nn.Module):
def __init__(self, conv, in_channels, out_channels, double=False):
super().__init__()
self.conv_type = conv
self.double = double
self.conv_i1 = nn.Conv3d(in_channels, in_channels, kernel_size=1,
... | 0.959734 | 0.433502 |
import os
import sys
import re
import getopt
import json
import time
import datetime
import hashlib
from pymongo import MongoClient
from conf.config import MongoDBConfig
def usage():
print('import.py USAGE:')
print('-h, --help:\tprint help message.')
print('-f, --format:\tformat json file')
print('-d,... | backend/import.py | import os
import sys
import re
import getopt
import json
import time
import datetime
import hashlib
from pymongo import MongoClient
from conf.config import MongoDBConfig
def usage():
print('import.py USAGE:')
print('-h, --help:\tprint help message.')
print('-f, --format:\tformat json file')
print('-d,... | 0.058561 | 0.084758 |
from django.db import migrations, models
import django.db.models.deletion
import django_extensions.db.fields
def update_record_field(apps, schema_editor):
Record = apps.get_model("records", "Record")
Letter = apps.get_model("letters", "Letter")
db_alias = schema_editor.connection.alias
for letter in ... | feder/letters/migrations/0017_auto_20180227_1908.py |
from django.db import migrations, models
import django.db.models.deletion
import django_extensions.db.fields
def update_record_field(apps, schema_editor):
Record = apps.get_model("records", "Record")
Letter = apps.get_model("letters", "Letter")
db_alias = schema_editor.connection.alias
for letter in ... | 0.510985 | 0.153549 |
import os
import sys
from github import Github
class InvalidPR(Exception):
pass
def get_expected_filename(filename, pr_creator):
expected_testnet_filename = "testnet/%s-entity.json" % pr_creator
expected_mainnet_filename = "mainnet/%s-entity.json" % pr_creator
if (filename == expected_mainnet_filenam... | .github/scripts/python/validate_pr_file_name.py | import os
import sys
from github import Github
class InvalidPR(Exception):
pass
def get_expected_filename(filename, pr_creator):
expected_testnet_filename = "testnet/%s-entity.json" % pr_creator
expected_mainnet_filename = "mainnet/%s-entity.json" % pr_creator
if (filename == expected_mainnet_filenam... | 0.283484 | 0.226709 |
import os
import sys
import time
import numpy as np
import tensorflow as tf
class V_group(object):
def __init__(self):
self.group_dim = 4
self.cayleytable = self.get_cayleytable()
def get_cayleytable(self):
print("...Computing Cayley table")
cayley = np.asarray([[0,1,2,3],
... | cubenet/V_group.py | import os
import sys
import time
import numpy as np
import tensorflow as tf
class V_group(object):
def __init__(self):
self.group_dim = 4
self.cayleytable = self.get_cayleytable()
def get_cayleytable(self):
print("...Computing Cayley table")
cayley = np.asarray([[0,1,2,3],
... | 0.387227 | 0.282932 |
import collections
import functools
import math
import random
from typing import List, Optional
from project.conf import get_configuration
from project.message import print_dice_result, print_suffer_damage, print_missed, print_area_damage, print_found_item, \
print_use_item
from project.interface import IBotDecis... | project/bot/bot_decisioning.py | import collections
import functools
import math
import random
from typing import List, Optional
from project.conf import get_configuration
from project.message import print_dice_result, print_suffer_damage, print_missed, print_area_damage, print_found_item, \
print_use_item
from project.interface import IBotDecis... | 0.75037 | 0.166269 |
import functools
import os
from typing import Any, List, Optional, Sequence
from fvcore.common.registry import Registry as _Registry
from tabulate import tabulate
from meerkat.config import ContribOptions
from meerkat.datapanel import DataPanel
class Registry(_Registry):
"""Extension of fvcore's registry that s... | meerkat/contrib/registry.py | import functools
import os
from typing import Any, List, Optional, Sequence
from fvcore.common.registry import Registry as _Registry
from tabulate import tabulate
from meerkat.config import ContribOptions
from meerkat.datapanel import DataPanel
class Registry(_Registry):
"""Extension of fvcore's registry that s... | 0.797162 | 0.180992 |
from __future__ import print_function, unicode_literals, division, absolute_import
import sys
import ipaddress
from struct import pack, unpack
from binascii import hexlify, unhexlify
import enum
PY2 = sys.version_info.major == 2
if PY2:
str = unicode
from StringIO import StringIO as BytesIO
else:
from io i... | zprocess/socks/__init__.py | from __future__ import print_function, unicode_literals, division, absolute_import
import sys
import ipaddress
from struct import pack, unpack
from binascii import hexlify, unhexlify
import enum
PY2 = sys.version_info.major == 2
if PY2:
str = unicode
from StringIO import StringIO as BytesIO
else:
from io i... | 0.513181 | 0.382747 |
import networkx as nx
import numpy as np
from _fasttr import *
template_classes = {
'int': IntHistorySampler,
'str': StringHistorySampler
}
class HistorySampler:
"""
This class implements a uniform sampler for histories of a graph growth.
This class is a wrapper around a C++ implementation.
"... | fasttr/_wrapper.py | import networkx as nx
import numpy as np
from _fasttr import *
template_classes = {
'int': IntHistorySampler,
'str': StringHistorySampler
}
class HistorySampler:
"""
This class implements a uniform sampler for histories of a graph growth.
This class is a wrapper around a C++ implementation.
"... | 0.860296 | 0.472379 |
from typing import Dict
import abc
import collections
import torch
class Metric(abc.ABC):
"""A generic metric calculated over multiple batches."""
@abc.abstractmethod
def update(self, key: str, y_pred: torch.Tensor, y_true: torch.Tensor) -> None:
"""Updates values from a single batch of y_pred an... | metrics.py | from typing import Dict
import abc
import collections
import torch
class Metric(abc.ABC):
"""A generic metric calculated over multiple batches."""
@abc.abstractmethod
def update(self, key: str, y_pred: torch.Tensor, y_true: torch.Tensor) -> None:
"""Updates values from a single batch of y_pred an... | 0.956947 | 0.667256 |
import secrets
# preverja datum
def je_prestopno(leto):
if isinstance(leto, int):
return leto % 4 == 0 and leto % 100 != 0 or leto % 400 == 0
else:
raise Exception("a")
def stevilo_dni(mesec, leto):
if not isinstance(mesec, int) or not isinstance(leto, int):
raise Exception("b")... | model.py | import secrets
# preverja datum
def je_prestopno(leto):
if isinstance(leto, int):
return leto % 4 == 0 and leto % 100 != 0 or leto % 400 == 0
else:
raise Exception("a")
def stevilo_dni(mesec, leto):
if not isinstance(mesec, int) or not isinstance(leto, int):
raise Exception("b")... | 0.341912 | 0.278921 |
from flask import request, jsonify, make_response, json
from datetime import datetime, timezone
import pytz
import urllib.parse
from google.cloud import firestore, storage
from common.exceptions import exception_common
from config.secret import get_storage_name
STORAGE_NAME = get_storage_name()
db = firestore.Client(... | backend/common/history_management.py | from flask import request, jsonify, make_response, json
from datetime import datetime, timezone
import pytz
import urllib.parse
from google.cloud import firestore, storage
from common.exceptions import exception_common
from config.secret import get_storage_name
STORAGE_NAME = get_storage_name()
db = firestore.Client(... | 0.478041 | 0.153994 |
import numpy as np
from src import functions
from src.layers import Dense, Dropout, Conv2D, Reshape
from src.utils import print_progress_bar
from examples.mlp_mnist.mnist_loader import plot_digit
class Sequential(object):
def __init__(self, input_shape, cost_function='cross_entropy', learning_rate=1e-3, batch_si... | src/models.py | import numpy as np
from src import functions
from src.layers import Dense, Dropout, Conv2D, Reshape
from src.utils import print_progress_bar
from examples.mlp_mnist.mnist_loader import plot_digit
class Sequential(object):
def __init__(self, input_shape, cost_function='cross_entropy', learning_rate=1e-3, batch_si... | 0.896928 | 0.72958 |
from datetime import datetime
from requests import Session
from betconnect.baseclient import BaseClient
from betconnect.enums import Environment
from betconnect import config
class TestBaseClient:
def test___init__(self):
client = BaseClient(
username="test",
password="<PASSWORD>",... | tests/unit/test_baseclient.py | from datetime import datetime
from requests import Session
from betconnect.baseclient import BaseClient
from betconnect.enums import Environment
from betconnect import config
class TestBaseClient:
def test___init__(self):
client = BaseClient(
username="test",
password="<PASSWORD>",... | 0.547706 | 0.21429 |
import re
from typing import List, Optional, Tuple
from .context import TranspilerContext
from .utils import SHELL_CALL_REGEX, SHELL_VAR_REGEX, as_call, as_const, as_var, padded_string
def retokenize(script_source: str, context: Optional[TranspilerContext] = None) -> str:
if context is None:
context = Tr... | shed/transpiler/retokenizer.py | import re
from typing import List, Optional, Tuple
from .context import TranspilerContext
from .utils import SHELL_CALL_REGEX, SHELL_VAR_REGEX, as_call, as_const, as_var, padded_string
def retokenize(script_source: str, context: Optional[TranspilerContext] = None) -> str:
if context is None:
context = Tr... | 0.62498 | 0.207737 |
import torch as T
from torch.autograd import Variable
import numpy as np
class Learner(object):
def __init__(self, CNN, input, target, batch_size=1000, epochs=1000):
self.CNN = CNN
self.input = Variable(input)
self.input_dim = input.shape
self.target = Variable(target).long... | CNN/learner.py | import torch as T
from torch.autograd import Variable
import numpy as np
class Learner(object):
def __init__(self, CNN, input, target, batch_size=1000, epochs=1000):
self.CNN = CNN
self.input = Variable(input)
self.input_dim = input.shape
self.target = Variable(target).long... | 0.705481 | 0.238229 |
from time import perf_counter
from whynot.framework import InferenceResult
import whynot_estimators
class CausalForest(whynot_estimators.Estimator):
"""Estimate average and individual treatment effects using causal forest.
The causal forest implementation uses the `grf` package. For more details see:
... | whynot_estimators/causal_forest.py | from time import perf_counter
from whynot.framework import InferenceResult
import whynot_estimators
class CausalForest(whynot_estimators.Estimator):
"""Estimate average and individual treatment effects using causal forest.
The causal forest implementation uses the `grf` package. For more details see:
... | 0.93263 | 0.619788 |
import os
import sys
import prody as pr
#sys.path.append(r'/mnt/e/GitHub_Design/Metalprot')
from metalprot.database import database_extract as ldb
import itertools
### set up parameters
workdir = "/mnt/e/DesignData/ligands/ZN_rcsb/20210608/"
metal_sel = 'ion or name NI MN ZN CO CU MG FE'
align_sel_backbone = 'name ... | scrips/database_generate/run_cluster_combine2.py | import os
import sys
import prody as pr
#sys.path.append(r'/mnt/e/GitHub_Design/Metalprot')
from metalprot.database import database_extract as ldb
import itertools
### set up parameters
workdir = "/mnt/e/DesignData/ligands/ZN_rcsb/20210608/"
metal_sel = 'ion or name NI MN ZN CO CU MG FE'
align_sel_backbone = 'name ... | 0.113309 | 0.334535 |
from fastapi import FastAPI, Form
from uuid import uuid4
from models import create_session, Block, Transaction, User, Chain, asdict
from blockchain import hash, proof_of_work
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///./blockchains.db'
db = SQLAlchemy(app)
@app.route('/mine', methods=[... | api.py | from fastapi import FastAPI, Form
from uuid import uuid4
from models import create_session, Block, Transaction, User, Chain, asdict
from blockchain import hash, proof_of_work
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///./blockchains.db'
db = SQLAlchemy(app)
@app.route('/mine', methods=[... | 0.492432 | 0.104067 |
import pygame, json
from itertools import count
from enum import Enum
RESOLUTION = 64
SCREEN_WIDTH = 12 * RESOLUTION
SCREEN_HEIGHT = 9 * RESOLUTION
FRAMERATE = 30 # fps
CONFIG_FILE = "assets/config.json"
IMAGE_DIRECTORY = "assets/images/"
SPRITESHEET_DIRECTORY = "assets/spritesheets/"
BACKGROUND_IMAGE = IMAGE_DIRECTOR... | spoodle_client.py | import pygame, json
from itertools import count
from enum import Enum
RESOLUTION = 64
SCREEN_WIDTH = 12 * RESOLUTION
SCREEN_HEIGHT = 9 * RESOLUTION
FRAMERATE = 30 # fps
CONFIG_FILE = "assets/config.json"
IMAGE_DIRECTORY = "assets/images/"
SPRITESHEET_DIRECTORY = "assets/spritesheets/"
BACKGROUND_IMAGE = IMAGE_DIRECTOR... | 0.676086 | 0.185154 |
from typing import Iterable, List, Set
from abc import ABC
import datetime
import os
import tempfile
import numpy as np
import pyspark
import sqlalchemy
import pandas
from pyspark.sql import SparkSession
from lazy_property import LazyProperty
from jetavator.sqlalchemy_delta import HiveWithDDLDialect
from .Compute... | jetavator/services/SparkService.py | from typing import Iterable, List, Set
from abc import ABC
import datetime
import os
import tempfile
import numpy as np
import pyspark
import sqlalchemy
import pandas
from pyspark.sql import SparkSession
from lazy_property import LazyProperty
from jetavator.sqlalchemy_delta import HiveWithDDLDialect
from .Compute... | 0.548069 | 0.261398 |
# third-party modules
import pandas as pd
# my modules
import data_checks
# MATRICE STATISTICHE PG = { pg_1: [STR, DEX, CON, INT, WIS, CHA], ..., pg_n: [STR, DEX, CON, INT, WIS, CHA] }
def make_dict_(index):
"""make dictionary taking as input lists of stats (1 list --> 1 character)"""
do_repeat = True
d... | character_dataframe.py | # third-party modules
import pandas as pd
# my modules
import data_checks
# MATRICE STATISTICHE PG = { pg_1: [STR, DEX, CON, INT, WIS, CHA], ..., pg_n: [STR, DEX, CON, INT, WIS, CHA] }
def make_dict_(index):
"""make dictionary taking as input lists of stats (1 list --> 1 character)"""
do_repeat = True
d... | 0.479747 | 0.346044 |
from datetime import datetime
from unittest.mock import patch
import pytest
from tatoebatools.version import Version
class TestVersion:
@patch("tatoebatools.version.json.load")
@patch("builtins.open")
def test_init_with_file(self, m_open, m_load):
m_load.return_value = {"foo": "2020-05-22 11:51:0... | tests/test_version.py | from datetime import datetime
from unittest.mock import patch
import pytest
from tatoebatools.version import Version
class TestVersion:
@patch("tatoebatools.version.json.load")
@patch("builtins.open")
def test_init_with_file(self, m_open, m_load):
m_load.return_value = {"foo": "2020-05-22 11:51:0... | 0.814127 | 0.503174 |
import re
from datetime import timedelta
from django import template
from django.utils import html, safestring
from django.template.defaultfilters import stringfilter
from math import ceil
register = template.Library()
@register.simple_tag
def sitenav():
return """<ul id="sitenav">
<li><a href="/" rel="sigrie" cla... | sigrie/sigrie/common/templatetags/extratags.py | import re
from datetime import timedelta
from django import template
from django.utils import html, safestring
from django.template.defaultfilters import stringfilter
from math import ceil
register = template.Library()
@register.simple_tag
def sitenav():
return """<ul id="sitenav">
<li><a href="/" rel="sigrie" cla... | 0.284675 | 0.176725 |
import math
import random
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, FFMpegWriter
from matplotlib.patches import Polygon
import numpy as np
from utils import check_obstacle, gen_neighbours, dijkstra
from dimensions import *
def init():
scat.set_offsets([])
return scat,
def... | Dijkstra-pathplanning-Arunava-Basu.py | import math
import random
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, FFMpegWriter
from matplotlib.patches import Polygon
import numpy as np
from utils import check_obstacle, gen_neighbours, dijkstra
from dimensions import *
def init():
scat.set_offsets([])
return scat,
def... | 0.206574 | 0.333123 |
import warnings
import numpy as np
from sklearn.ensemble import RandomForestRegressor, StackingRegressor, GradientBoostingRegressor, AdaBoostRegressor, \
VotingRegressor
from sklearn.linear_model import Ridge, Lasso
from sklearn.metrics import r2_score
from sklearn.model_selection import GridSearchCV
from sklearn.... | model_tuner/modeltuner.py | import warnings
import numpy as np
from sklearn.ensemble import RandomForestRegressor, StackingRegressor, GradientBoostingRegressor, AdaBoostRegressor, \
VotingRegressor
from sklearn.linear_model import Ridge, Lasso
from sklearn.metrics import r2_score
from sklearn.model_selection import GridSearchCV
from sklearn.... | 0.812793 | 0.631168 |
import torch, copy
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
def _copy(state):
if isinstance(state, torch.Tensor):
return state.cpu().clone()
elif isinstance(state, dict):
new_state = {}
for key in state:
new_state[key] =... | train/meta_optimizers.py | import torch, copy
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
def _copy(state):
if isinstance(state, torch.Tensor):
return state.cpu().clone()
elif isinstance(state, dict):
new_state = {}
for key in state:
new_state[key] =... | 0.793586 | 0.281002 |
import falcon
import arrow
import time
try:
import simplejson as json
except ImportError:
import json
from collections import OrderedDict
from ..help import helping
from .. import didering
from ..db import dbing as db
def basicValidation(req, resp, resource, params):
raw = helping.parseReqBody(req)
b... | src/didery/controllers/history.py | import falcon
import arrow
import time
try:
import simplejson as json
except ImportError:
import json
from collections import OrderedDict
from ..help import helping
from .. import didering
from ..db import dbing as db
def basicValidation(req, resp, resource, params):
raw = helping.parseReqBody(req)
b... | 0.439988 | 0.096962 |
import unittest
from unittest.mock import ANY, call, patch
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import KeyBindings
from prompt_toolkit.styles.style import Style
from InquirerPy.exceptions import InvalidArgument, RequiredKeyNotFound
from InquirerPy.prompts.checkbox ... | tests/prompts/test_checkbox.py | import unittest
from unittest.mock import ANY, call, patch
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.key_bindings import KeyBindings
from prompt_toolkit.styles.style import Style
from InquirerPy.exceptions import InvalidArgument, RequiredKeyNotFound
from InquirerPy.prompts.checkbox ... | 0.516595 | 0.468 |
import os
import sys
import math
import re
import argparse
import codecs
import string
try:
import cPickle as pickle
except:
import pickle
from collections import defaultdict
LANGUAGES = {"as": "Assamese", "gu": "Gujarati", "hi": "Hindi",
"ka": "Kannada", "ml": "Malayalam",
"mr": "Mar... | whichlang/whichlang.py | import os
import sys
import math
import re
import argparse
import codecs
import string
try:
import cPickle as pickle
except:
import pickle
from collections import defaultdict
LANGUAGES = {"as": "Assamese", "gu": "Gujarati", "hi": "Hindi",
"ka": "Kannada", "ml": "Malayalam",
"mr": "Mar... | 0.452294 | 0.245249 |
import re
import urllib.request
from bs4 import BeautifulSoup
from docx import Document
from docx.shared import Pt
document = Document()
style = document.styles['Normal']
font = style.font
font.name = 'Garamond'
font.size = Pt(12)
#new_heading_style = document.styles['Heading 1']
#font_heading = new_heading_style.fo... | jobscraperModule.py | import re
import urllib.request
from bs4 import BeautifulSoup
from docx import Document
from docx.shared import Pt
document = Document()
style = document.styles['Normal']
font = style.font
font.name = 'Garamond'
font.size = Pt(12)
#new_heading_style = document.styles['Heading 1']
#font_heading = new_heading_style.fo... | 0.066911 | 0.086787 |
import argparse
from pulp import *
def create_starting_numbers(path):
"""
Reads a file containing a sudoku grid and converts its content to a list of tuples.
@param path: The path of the file to read
@return A list of tuples containing the starting numbers
"""
starting_numbers = []
... | solver.py | import argparse
from pulp import *
def create_starting_numbers(path):
"""
Reads a file containing a sudoku grid and converts its content to a list of tuples.
@param path: The path of the file to read
@return A list of tuples containing the starting numbers
"""
starting_numbers = []
... | 0.560974 | 0.577197 |
from botocore.exceptions import ClientError
from datetime import timedelta
from dateutil.tz import tzutc
import boto3
import click
import datetime
import getpass
import sys
ONE_HOUR_IN_SECONDS = timedelta(hours=1).seconds
TWELVE_HOURS_IN_SECONDS = timedelta(hours=12).seconds
class STS:
""" A small class that wra... | awscli_bastion/sts.py | from botocore.exceptions import ClientError
from datetime import timedelta
from dateutil.tz import tzutc
import boto3
import click
import datetime
import getpass
import sys
ONE_HOUR_IN_SECONDS = timedelta(hours=1).seconds
TWELVE_HOURS_IN_SECONDS = timedelta(hours=12).seconds
class STS:
""" A small class that wra... | 0.553505 | 0.135289 |
import unittest
from IPython.terminal.interactiveshell import TerminalInteractiveShell
import nose.tools as nt
import mock
from ipydb import magic, plugin
class ModelTest(unittest.TestCase):
def setUp(self):
self.ipydb = mock.MagicMock(spec=plugin.SqlPlugin)
self.ipython = mock.MagicMock(spec=T... | tests/test_magic.py | import unittest
from IPython.terminal.interactiveshell import TerminalInteractiveShell
import nose.tools as nt
import mock
from ipydb import magic, plugin
class ModelTest(unittest.TestCase):
def setUp(self):
self.ipydb = mock.MagicMock(spec=plugin.SqlPlugin)
self.ipython = mock.MagicMock(spec=T... | 0.649356 | 0.319281 |
import torch
from torch.autograd import Variable
from pg_methods import interfaces
def calculate_returns(rewards, discount, masks=None):
"""
Calculates the returns from a sequence of rewards.
:param rewards: a torch.Tensor of size (time, batch_size)
:param discount: a float
:param masks: will use t... | pg_methods/gradients.py | import torch
from torch.autograd import Variable
from pg_methods import interfaces
def calculate_returns(rewards, discount, masks=None):
"""
Calculates the returns from a sequence of rewards.
:param rewards: a torch.Tensor of size (time, batch_size)
:param discount: a float
:param masks: will use t... | 0.920504 | 0.867598 |
"""Get key information about the camera."""
import os
import numpy as np
import unagi
__all__ = []
# Directory that save the files related to camera
CAMERA_DIR = os.path.join(os.path.dirname(unagi.__file__), 'data', 'camera')
# List of primary mirror data available
PRIMARY_MIRROR_LIST = ['']
class Camera(object)... | unagi/camera.py | """Get key information about the camera."""
import os
import numpy as np
import unagi
__all__ = []
# Directory that save the files related to camera
CAMERA_DIR = os.path.join(os.path.dirname(unagi.__file__), 'data', 'camera')
# List of primary mirror data available
PRIMARY_MIRROR_LIST = ['']
class Camera(object)... | 0.722429 | 0.254926 |
from typing import Dict, List, Union
import pytest
from multiformats import multicodec
from multiformats.multicodec import Multicodec
exists_cases = [
"identity",
0x00
]
@pytest.mark.parametrize("name_or_code", exists_cases)
def test_exists(name_or_code: Union[str, int]) -> None:
""" Tests `multicodec.... | test/test_01_multicodec.py |
from typing import Dict, List, Union
import pytest
from multiformats import multicodec
from multiformats.multicodec import Multicodec
exists_cases = [
"identity",
0x00
]
@pytest.mark.parametrize("name_or_code", exists_cases)
def test_exists(name_or_code: Union[str, int]) -> None:
""" Tests `multicodec.... | 0.783864 | 0.498596 |
import json
from pathlib import Path
from requests import RequestException
from unittest.mock import Mock
import pytest
from cdptools.sr_models.webvtt_sr_model import WebVTTSRModel
@pytest.fixture
def fake_caption(data_dir) -> Path:
return data_dir / "fake_caption.vtt"
@pytest.fixture
def fake_timestamped_s... | cdptools/tests/sr_models/test_webvtt_sr_model.py |
import json
from pathlib import Path
from requests import RequestException
from unittest.mock import Mock
import pytest
from cdptools.sr_models.webvtt_sr_model import WebVTTSRModel
@pytest.fixture
def fake_caption(data_dir) -> Path:
return data_dir / "fake_caption.vtt"
@pytest.fixture
def fake_timestamped_s... | 0.718693 | 0.228942 |
from urllib import request, parse
from bs4 import BeautifulSoup
import re
def make_search_url(keyword, start, end):
print('make_basic_url')
base_url = 'https://m.search.naver.com/search.naver?display=15&nso=p%3A'
period = 'from' + start + 'to' + end
query = '&query=' + parse.quote(keyword)
end = '&... | crawl_title_only.py | from urllib import request, parse
from bs4 import BeautifulSoup
import re
def make_search_url(keyword, start, end):
print('make_basic_url')
base_url = 'https://m.search.naver.com/search.naver?display=15&nso=p%3A'
period = 'from' + start + 'to' + end
query = '&query=' + parse.quote(keyword)
end = '&... | 0.282196 | 0.141459 |
import os
from os import listdir, path
from PIL import Image
from random import shuffle
from scipy.io import loadmat, savemat
import numpy as np
class dirload():
'''
Reads a sorted list of files from the specified directory if those files are of type tif, tiff, jpg, jpeg, png, or PNG. Can specify the type if ... | imagemks/rw/folder.py | import os
from os import listdir, path
from PIL import Image
from random import shuffle
from scipy.io import loadmat, savemat
import numpy as np
class dirload():
'''
Reads a sorted list of files from the specified directory if those files are of type tif, tiff, jpg, jpeg, png, or PNG. Can specify the type if ... | 0.627951 | 0.439326 |
from HyperAPI.util import Helper
from HyperAPI.hyper_api.base import Base
from HyperAPI.utils.exceptions import ApiException
from HyperAPI.hyper_api.xrayvariable import XRayVariableFactory
from HyperAPI.hyper_api.target import TargetFactory, Target, Description
class XrayFactory:
"""
"""
def __init__(self... | hyper_api/xray.py | from HyperAPI.util import Helper
from HyperAPI.hyper_api.base import Base
from HyperAPI.utils.exceptions import ApiException
from HyperAPI.hyper_api.xrayvariable import XRayVariableFactory
from HyperAPI.hyper_api.target import TargetFactory, Target, Description
class XrayFactory:
"""
"""
def __init__(self... | 0.858541 | 0.253641 |
import discord
from discord.ext import commands
class chelp(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def help(self, ctx):
embed = discord.Embed(colour = 0xFFA500, title = 'Help!', description = 'shows information about the command... | cogs/customhelp.py | import discord
from discord.ext import commands
class chelp(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def help(self, ctx):
embed = discord.Embed(colour = 0xFFA500, title = 'Help!', description = 'shows information about the command... | 0.280321 | 0.131954 |
import random
import re
from configparser import SafeConfigParser
from logging import getLogger
from operator import attrgetter
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple
import attr
from . import database, models
logger = getLogger(__name__)
DEFAULT_SUBREDDIT_SIMULATOR_C... | subreddit_simulator/config.py | import random
import re
from configparser import SafeConfigParser
from logging import getLogger
from operator import attrgetter
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple
import attr
from . import database, models
logger = getLogger(__name__)
DEFAULT_SUBREDDIT_SIMULATOR_C... | 0.775009 | 0.158239 |
from __future__ import print_function
from __future__ import absolute_import
import os
import sys
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
import yaml
from contextlib import contextmanager
from PIL import Image
from io import BytesIO
fro... | keynote_parser/file_utils.py | from __future__ import print_function
from __future__ import absolute_import
import os
import sys
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
import yaml
from contextlib import contextmanager
from PIL import Image
from io import BytesIO
fro... | 0.413714 | 0.075448 |
import asyncio
import unittest
import reactivex
import reactivex.operators as ops
from reactivex.internal.exceptions import SequenceContainsNoElementsError
from reactivex.subject import Subject
from reactivex.testing import ReactiveTest
on_next = ReactiveTest.on_next
on_completed = ReactiveTest.on_completed
on_error ... | tests/test_observable/test_tofuture.py | import asyncio
import unittest
import reactivex
import reactivex.operators as ops
from reactivex.internal.exceptions import SequenceContainsNoElementsError
from reactivex.subject import Subject
from reactivex.testing import ReactiveTest
on_next = ReactiveTest.on_next
on_completed = ReactiveTest.on_completed
on_error ... | 0.565899 | 0.395922 |
import datetime
import glob
import json
import os.path
import shutil
import sys
import yaml
# Some test YAML documents create big recursions in the YAML parser
sys.setrecursionlimit(10000)
iarna_root = sys.argv[1]
output_dir = os.path.join(os.getcwd(), 'tests', 'iarna-toml-spec-tests')
os.mkdir(output_dir)
def i... | test-importers/iarna-toml-spec-tests.py | import datetime
import glob
import json
import os.path
import shutil
import sys
import yaml
# Some test YAML documents create big recursions in the YAML parser
sys.setrecursionlimit(10000)
iarna_root = sys.argv[1]
output_dir = os.path.join(os.getcwd(), 'tests', 'iarna-toml-spec-tests')
os.mkdir(output_dir)
def i... | 0.28597 | 0.264412 |
'''
This is the Chapter 4 for the book
codes for book and the excercises
'''
#######################################################################
'P_71 Find_Max_Crossing_Subarray'
def Find_Max_Crossing_Subarray(A,low,mid,high):
left_sum=float("-inf")
now_sum=0
for i in range(mid, low-1, ... | Chapter_4.py | '''
This is the Chapter 4 for the book
codes for book and the excercises
'''
#######################################################################
'P_71 Find_Max_Crossing_Subarray'
def Find_Max_Crossing_Subarray(A,low,mid,high):
left_sum=float("-inf")
now_sum=0
for i in range(mid, low-1, ... | 0.40698 | 0.531635 |
##### Libraries :
from math import exp
import dataprep as dp
### Fonction Logistique
def logistic(x):
return 1.0 / (1.0 + exp(-x))
####
def accuracy_metric(test, predicted):
correct = 0
for k in range(len(test)):
if test[k] == predicted[k]:
correct += 1
return (corr... | logistic_regression.py |
##### Libraries :
from math import exp
import dataprep as dp
### Fonction Logistique
def logistic(x):
return 1.0 / (1.0 + exp(-x))
####
def accuracy_metric(test, predicted):
correct = 0
for k in range(len(test)):
if test[k] == predicted[k]:
correct += 1
return (corr... | 0.429429 | 0.514522 |
from flask import Flask, abort
from flask import request, session, redirect, flash
from flask import render_template, send_from_directory
from files import get_files_data, DEFAULT_PATH, DRIVERS_LIST, \
get_current_path
import os
import re
from random import randint
# 创建项目以及初始化一些关键信息
app = Flask(__name__, template... | app.py | from flask import Flask, abort
from flask import request, session, redirect, flash
from flask import render_template, send_from_directory
from files import get_files_data, DEFAULT_PATH, DRIVERS_LIST, \
get_current_path
import os
import re
from random import randint
# 创建项目以及初始化一些关键信息
app = Flask(__name__, template... | 0.2587 | 0.086478 |
import logging
from ignition.boot.config import BootProperties
from ignition.boot.connexionutils import build_resolver_to_instance
from ignition.service.framework import ServiceRegistration
from ignition.service.messaging import PostalCapability, TopicsProperties, TopicCreator, MessagingProperties
from ignition.service... | ignition/boot/configurators/resourcedriverapi.py | import logging
from ignition.boot.config import BootProperties
from ignition.boot.connexionutils import build_resolver_to_instance
from ignition.service.framework import ServiceRegistration
from ignition.service.messaging import PostalCapability, TopicsProperties, TopicCreator, MessagingProperties
from ignition.service... | 0.533397 | 0.040731 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import numpy as np
try:
import cPickle as pickle
except ImportError:
import pickle
from utils.blob import im_list_to_blob
from model.config import cfg
def _get_image_blob(im):
"""Converts an... | lib/model/test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import numpy as np
try:
import cPickle as pickle
except ImportError:
import pickle
from utils.blob import im_list_to_blob
from model.config import cfg
def _get_image_blob(im):
"""Converts an... | 0.777553 | 0.349755 |
import logging
from decimal import Decimal, InvalidOperation
from functools import reduce
from django.db import IntegrityError, migrations, transaction
logger = logging.getLogger(__name__)
CHAR_FIELDS_TO_DATA_KEY_MAP = {
"phone_number": "applicant.contact.mobile_phone",
"address": "applicant.postal.street_ad... | applications/migrations/0003_from_data_to_main_fields.py | import logging
from decimal import Decimal, InvalidOperation
from functools import reduce
from django.db import IntegrityError, migrations, transaction
logger = logging.getLogger(__name__)
CHAR_FIELDS_TO_DATA_KEY_MAP = {
"phone_number": "applicant.contact.mobile_phone",
"address": "applicant.postal.street_ad... | 0.586996 | 0.255007 |
from typing import Dict, List
import matplotlib.pyplot as plt
from src.environment.status import Status
class Graph:
@staticmethod
def generate_fig_ax(show_params: bool):
fig = plt.figure()
if show_params:
gs = fig.add_gridspec(3, 4)
ax1 = fig.add_subplot(gs[:, :2])... | src/simulation/graph.py | from typing import Dict, List
import matplotlib.pyplot as plt
from src.environment.status import Status
class Graph:
@staticmethod
def generate_fig_ax(show_params: bool):
fig = plt.figure()
if show_params:
gs = fig.add_gridspec(3, 4)
ax1 = fig.add_subplot(gs[:, :2])... | 0.786049 | 0.676914 |
from flask_restful import reqparse, abort
from flask_restful_swagger_2 import Api, swagger, Resource
from lib import mongodbConnection
import requests
import configuration
import csv
import io
from functools import reduce
from lib.aggregator import Aggregator
from flask import Response
import logging
logger = logging.g... | src/resources/aggregationResource.py | from flask_restful import reqparse, abort
from flask_restful_swagger_2 import Api, swagger, Resource
from lib import mongodbConnection
import requests
import configuration
import csv
import io
from functools import reduce
from lib.aggregator import Aggregator
from flask import Response
import logging
logger = logging.g... | 0.642769 | 0.121347 |
from abc import ABC, abstractmethod
import time
from typing import List, Tuple, Iterator, Type
_sleep_for: float = 0.2
class TestCase(ABC):
"""Abstract test case interface."""
@abstractmethod
def run(self) -> None:
pass
class TestCaseOne(TestCase):
"""Concrete test case one."""
def __... | patterns/structural/facade.py | from abc import ABC, abstractmethod
import time
from typing import List, Tuple, Iterator, Type
_sleep_for: float = 0.2
class TestCase(ABC):
"""Abstract test case interface."""
@abstractmethod
def run(self) -> None:
pass
class TestCaseOne(TestCase):
"""Concrete test case one."""
def __... | 0.826292 | 0.376423 |
# Programa simple para aprender a usar Qt
from __future__ import with_statement
import sys
import matplotlib
matplotlib.use('Qt4Agg')
from PyQt4 import QtGui, QtCore
from ellipse_plot import Ui_MplMainWindow
from polarization_routines import plot_ellipse, getAnglesFromEllipse, getAnglesFromJones
from matplotlib.figu... | Python_version/ellipse_app.py |
# Programa simple para aprender a usar Qt
from __future__ import with_statement
import sys
import matplotlib
matplotlib.use('Qt4Agg')
from PyQt4 import QtGui, QtCore
from ellipse_plot import Ui_MplMainWindow
from polarization_routines import plot_ellipse, getAnglesFromEllipse, getAnglesFromJones
from matplotlib.figu... | 0.509276 | 0.209591 |
import logging
from operator import itemgetter
import requests
from sqlalchemy.orm.exc import NoResultFound
from ultros_site.database.schema.news_post import NewsPost
from ultros_site.database.schema.setting import Setting
from ultros_site.tasks.__main__ import app
from ultros_site.tasks.base import DatabaseTask
__... | ultros_site/tasks/nodebb.py | import logging
from operator import itemgetter
import requests
from sqlalchemy.orm.exc import NoResultFound
from ultros_site.database.schema.news_post import NewsPost
from ultros_site.database.schema.setting import Setting
from ultros_site.tasks.__main__ import app
from ultros_site.tasks.base import DatabaseTask
__... | 0.391755 | 0.0771 |
import json
import logging
import requests
from functools import reduce
from urllib.parse import urljoin
from flask import Blueprint, render_template, flash, redirect, url_for, current_app
from app import db
from app.planet.models import Planet
planet_bp = Blueprint('planet', __name__)
@planet_bp.route('/')
def i... | app/planet/controllers.py | import json
import logging
import requests
from functools import reduce
from urllib.parse import urljoin
from flask import Blueprint, render_template, flash, redirect, url_for, current_app
from app import db
from app.planet.models import Planet
planet_bp = Blueprint('planet', __name__)
@planet_bp.route('/')
def i... | 0.294114 | 0.059976 |
from __future__ import print_function
import numpy as np
import cv2, time, math
import rospy, rospkg
from cv_bridge import CvBridge, CvBridgeError
from std_msgs.msg import Empty, UInt8, String
from sensor_msgs.msg import CompressedImage, Imu, Image
from selfiestickdrone.msg import device_state, selfie_state
from face_... | script/phone.py | from __future__ import print_function
import numpy as np
import cv2, time, math
import rospy, rospkg
from cv_bridge import CvBridge, CvBridgeError
from std_msgs.msg import Empty, UInt8, String
from sensor_msgs.msg import CompressedImage, Imu, Image
from selfiestickdrone.msg import device_state, selfie_state
from face_... | 0.34621 | 0.196768 |
from onapsdk.utils.jinja import jinja_env
from ..msb_service import MSB
class ConnectivityInfo(MSB):
"""Connectivity-Info class."""
api_version = "/api/multicloud-k8s/v1/v1"
url = f"{MSB.base_url}{api_version}/connectivity-info"
def __init__(self, cloud_region_id: str,
cloud_owner: ... | src/onapsdk/msb/k8s/connectivity_info.py | from onapsdk.utils.jinja import jinja_env
from ..msb_service import MSB
class ConnectivityInfo(MSB):
"""Connectivity-Info class."""
api_version = "/api/multicloud-k8s/v1/v1"
url = f"{MSB.base_url}{api_version}/connectivity-info"
def __init__(self, cloud_region_id: str,
cloud_owner: ... | 0.814975 | 0.099295 |
# -*- coding:utf-8 -*-
# Author: hankcs
import math
import torch
import torch.nn.functional as F
from torch import nn
from elit.common.transform import VocabDict
from elit.components.amr.amr_parser.customized_bart import CustomizedDecoderLayer
from elit.components.amr.amr_parser.data import list_to_tensor, lists_of_s... | elit/components/amr/amr_parser/parser_model.py |
# -*- coding:utf-8 -*-
# Author: hankcs
import math
import torch
import torch.nn.functional as F
from torch import nn
from elit.common.transform import VocabDict
from elit.components.amr.amr_parser.customized_bart import CustomizedDecoderLayer
from elit.components.amr.amr_parser.data import list_to_tensor, lists_of_s... | 0.806281 | 0.329823 |
import abc
import io
import xml.etree.ElementTree as ET
from os import path
import mujoco_py
import numpy as np
import robosuite
from d4rl.kitchen.adept_envs.simulation import module
from d4rl.kitchen.adept_envs.simulation.renderer import DMRenderer, MjPyRenderer
from metaworld.envs.mujoco.mujoco_env import MujocoEnv
... | rlkit/rlkit/envs/dm_backend_wrappers.py | import abc
import io
import xml.etree.ElementTree as ET
from os import path
import mujoco_py
import numpy as np
import robosuite
from d4rl.kitchen.adept_envs.simulation import module
from d4rl.kitchen.adept_envs.simulation.renderer import DMRenderer, MjPyRenderer
from metaworld.envs.mujoco.mujoco_env import MujocoEnv
... | 0.432782 | 0.297585 |