edited_code stringlengths 17 978k | original_code stringlengths 17 978k |
|---|---|
from __future__ import division
from pyomo.environ import *
import numpy as np
import pandas as pd
from folium import Map, CircleMarker, FeatureGroup, LayerControl
import os.path
class linear_program:
def construct_inputs(self):
# Construct the files needed for input from the demand output file
... | from __future__ import division
from pyomo.environ import *
import numpy as np
import pandas as pd
from folium import Map, CircleMarker, FeatureGroup, LayerControl
import os.path
class linear_program:
def construct_inputs(self):
# Construct the files needed for input from the demand output file
... |
# -*- coding: utf-8 -*-
from typing import List
import dash_core_components as dcc
import dash_daq as daq
import dash_html_components as html
from dash import dash
from dash.dependencies import Input, Output, State
from zvt.api.trader_info_api import AccountStatsReader, OrderReader, get_order_securities
from zvt.api.... | # -*- coding: utf-8 -*-
from typing import List
import dash_core_components as dcc
import dash_daq as daq
import dash_html_components as html
from dash import dash
from dash.dependencies import Input, Output, State
from zvt.api.trader_info_api import AccountStatsReader, OrderReader, get_order_securities
from zvt.api.... |
# SPDX-License-Identifier: MIT
import os, shutil, sys, stat, subprocess, urlcache, zipfile, logging, firmware
from util import *
class OSInstaller(PackageInstaller):
PART_ALIGNMENT = 1024 * 1024
def __init__(self, dutil, data, template):
super().__init__()
self.dutil = dutil
self.data ... | # SPDX-License-Identifier: MIT
import os, shutil, sys, stat, subprocess, urlcache, zipfile, logging, firmware
from util import *
class OSInstaller(PackageInstaller):
PART_ALIGNMENT = 1024 * 1024
def __init__(self, dutil, data, template):
super().__init__()
self.dutil = dutil
self.data ... |
# deepROC.py
#
# Copyright 2021 Ottawa Hospital Research Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | # deepROC.py
#
# Copyright 2021 Ottawa Hospital Research Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... |
"""
Copyright (c) 2020-2021 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... | """
Copyright (c) 2020-2021 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... |
# Copyright (c) 2013 - 2020 Adam Caudill and Contributors.
# This file is part of YAWAST which is released under the MIT license.
# See the LICENSE file or go to https://yawast.org/license/ for full license details.
from typing import List, cast
from cryptography import x509
from cryptography.hazmat.primitives imp... | # Copyright (c) 2013 - 2020 Adam Caudill and Contributors.
# This file is part of YAWAST which is released under the MIT license.
# See the LICENSE file or go to https://yawast.org/license/ for full license details.
from typing import List, cast
from cryptography import x509
from cryptography.hazmat.primitives imp... |
from checkov.common.models.enums import CheckCategories, CheckResult
from checkov.kubernetes.base_spec_check import BaseK8Check
class ApiServerEncryptionProviders(BaseK8Check):
def __init__(self):
id = "CKV_K8S_104"
name = "Ensure that encryption providers are appropriately configured"
ca... |
from checkov.common.models.enums import CheckCategories, CheckResult
from checkov.kubernetes.base_spec_check import BaseK8Check
class ApiServerEncryptionProviders(BaseK8Check):
def __init__(self):
id = "CKV_K8S_104"
name = "Ensure that encryption providers are appropriately configured"
ca... |
import base64
import logging
from typing import List
from pydantic.error_wrappers import ErrorWrapper, ValidationError
from pydantic.main import BaseModel
from sqlalchemy.orm import Session
from dispatch.exceptions import NotFoundError
from dispatch.conversation import service as conversation_service
from dispatch.c... | import base64
import logging
from typing import List
from pydantic.error_wrappers import ErrorWrapper, ValidationError
from pydantic.main import BaseModel
from sqlalchemy.orm import Session
from dispatch.exceptions import NotFoundError
from dispatch.conversation import service as conversation_service
from dispatch.c... |
import multiprocessing
import os
import re
import subprocess
from concurrent.futures import ProcessPoolExecutor
from enum import Enum
from functools import partial
from pathlib import Path
import fire
from tools.pykitti_eval.utils.find import find_cuda, find_cuda_device_arch
class Gpp:
def __init__(self,
... | import multiprocessing
import os
import re
import subprocess
from concurrent.futures import ProcessPoolExecutor
from enum import Enum
from functools import partial
from pathlib import Path
import fire
from tools.pykitti_eval.utils.find import find_cuda, find_cuda_device_arch
class Gpp:
def __init__(self,
... |
#!/usr/bin/env python3
from numpy.random import default_rng
import argparse
import csv
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Create reviewing assignments')
parser.add_argument('--n', dest='n', type=int, default=3, required=False, help='number of reviews per submission')
a... | #!/usr/bin/env python3
from numpy.random import default_rng
import argparse
import csv
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Create reviewing assignments')
parser.add_argument('--n', dest='n', type=int, default=3, required=False, help='number of reviews per submission')
a... |
from multiprocessing import Pool
import cv2
import glob
import os.path as osp
import os
class DOTAImageSplitTool(object):
def __init__(self,
in_root,
out_root,
tile_overlap,
tile_shape,
num_process=8,
):
... | from multiprocessing import Pool
import cv2
import glob
import os.path as osp
import os
class DOTAImageSplitTool(object):
def __init__(self,
in_root,
out_root,
tile_overlap,
tile_shape,
num_process=8,
):
... |
import os
import shutil
import subprocess
import zipfile
from pathlib import Path
from typing import Tuple, List, Optional
from version import update_version_txt
# Files or folders common to all bots.
common_sharpy = [
("jsonpickle", None),
("sharpy", None),
(os.path.join("python-sc2", "sc2"), "sc2"),
... | import os
import shutil
import subprocess
import zipfile
from pathlib import Path
from typing import Tuple, List, Optional
from version import update_version_txt
# Files or folders common to all bots.
common_sharpy = [
("jsonpickle", None),
("sharpy", None),
(os.path.join("python-sc2", "sc2"), "sc2"),
... |
import errno
import glob
import json
import os
import random
import numpy
import tracery
from tracery.modifiers import base_english
from PIL import Image
from extended_english import extended_english
def calculate_image_possibilities():
"""Computes the total possible combinations for sword pieces
Returns:
... | import errno
import glob
import json
import os
import random
import numpy
import tracery
from tracery.modifiers import base_english
from PIL import Image
from extended_english import extended_english
def calculate_image_possibilities():
"""Computes the total possible combinations for sword pieces
Returns:
... |
import os
import random
import json
import logging
from datetime import datetime
from eval import eval_wrapper
from train import train_wrapper
from strips_hgn.utils.helpers import mode_to_str
from strips_hgn.utils.logging_setup import setup_full_logging
from default_args import get_training_args, DomainAndProblemConf... | import os
import random
import json
import logging
from datetime import datetime
from eval import eval_wrapper
from train import train_wrapper
from strips_hgn.utils.helpers import mode_to_str
from strips_hgn.utils.logging_setup import setup_full_logging
from default_args import get_training_args, DomainAndProblemConf... |
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu>
"""MneExperiment class to manage data from a experiment
For testing purposed, set up an experiment class without checking for data:
MneExperiment.auto_delete_cache = 'disable'
MneExperiment.sessions = ('session',)
e = MneExperiment('.', find_subjects=False)
""... | # Author: Christian Brodbeck <christianbrodbeck@nyu.edu>
"""MneExperiment class to manage data from a experiment
For testing purposed, set up an experiment class without checking for data:
MneExperiment.auto_delete_cache = 'disable'
MneExperiment.sessions = ('session',)
e = MneExperiment('.', find_subjects=False)
""... |
import logging
from datetime import date
from dispatch.config import INCIDENT_RESOURCE_EXECUTIVE_REPORT_DOCUMENT
from dispatch.conversation.messaging import send_feedack_to_user
from dispatch.decorators import background_task
from dispatch.document import service as document_service
from dispatch.document.models impo... | import logging
from datetime import date
from dispatch.config import INCIDENT_RESOURCE_EXECUTIVE_REPORT_DOCUMENT
from dispatch.conversation.messaging import send_feedack_to_user
from dispatch.decorators import background_task
from dispatch.document import service as document_service
from dispatch.document.models impo... |
from collections import namedtuple
import enum
import os.path
import re
from c_common.clsutil import classonly
import c_common.misc as _misc
import c_common.strutil as _strutil
import c_common.tables as _tables
from .parser._regexes import SIMPLE_TYPE, _STORAGE
FIXED_TYPE = _misc.Labeled('FIXED_TYPE')
STORAGE = fro... | from collections import namedtuple
import enum
import os.path
import re
from c_common.clsutil import classonly
import c_common.misc as _misc
import c_common.strutil as _strutil
import c_common.tables as _tables
from .parser._regexes import SIMPLE_TYPE, _STORAGE
FIXED_TYPE = _misc.Labeled('FIXED_TYPE')
STORAGE = fro... |
# Copyright 2019 Tuomas Aura. See LICENSE.txt for the license.
import json
def make_table_name(network_name, direction, special=None):
if special:
return '_'.join((network_name, direction, special, 'v6'))
else:
return '_'.join((network_name, direction, 'v6'))
def make_network_description(net... | # Copyright 2019 Tuomas Aura. See LICENSE.txt for the license.
import json
def make_table_name(network_name, direction, special=None):
if special:
return '_'.join((network_name, direction, special, 'v6'))
else:
return '_'.join((network_name, direction, 'v6'))
def make_network_description(net... |
from rest_framework import status
from care.facility.models import FacilityUser
from care.users.models import User
from care.utils.tests.test_base import TestBase
from config.tests.helper import mock_equal
class TestFacilityUserApi(TestBase):
def get_base_url(self):
return "/api/v1/users/add_user"
d... | from rest_framework import status
from care.facility.models import FacilityUser
from care.users.models import User
from care.utils.tests.test_base import TestBase
from config.tests.helper import mock_equal
class TestFacilityUserApi(TestBase):
def get_base_url(self):
return "/api/v1/users/add_user"
d... |
import argparse
import os
import socket
import subprocess
import sys
import time
import uuid
import psutil
from flask import Config
import redis
import redis.sentinel
from workers.workers import AssetWorker
from swm import monitors
site_path = "/sites/h51"
logfile_path = os.path.join(site_path, 'logs', 'workers_deb... | import argparse
import os
import socket
import subprocess
import sys
import time
import uuid
import psutil
from flask import Config
import redis
import redis.sentinel
from workers.workers import AssetWorker
from swm import monitors
site_path = "/sites/h51"
logfile_path = os.path.join(site_path, 'logs', 'workers_deb... |
from project.room import Room
class Hotel:
def __init__(self, name: str):
self.name = name
self.rooms = []
self.guests = 0
@classmethod
def from_stars(cls, stars_count: int):
new_name = f"{stars_count} stars Hotel"
return cls(new_name)
def add_room(self, room:... | from project.room import Room
class Hotel:
def __init__(self, name: str):
self.name = name
self.rooms = []
self.guests = 0
@classmethod
def from_stars(cls, stars_count: int):
new_name = f"{stars_count} stars Hotel"
return cls(new_name)
def add_room(self, room:... |
from PyBambooHR.PyBambooHR import PyBambooHR
import csv
import os
import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import random
import statistics
import sys
import jinja2
import itertools
import configparser
def load_df():
EMPLOYEES_CSV = conf... | from PyBambooHR.PyBambooHR import PyBambooHR
import csv
import os
import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import random
import statistics
import sys
import jinja2
import itertools
import configparser
def load_df():
EMPLOYEES_CSV = conf... |
import asyncio
import pytest
import pickle
from pathlib import Path
from aionetworking.compatibility import py37
@pytest.mark.connections('sftp_oneway_all')
class TestConnectionShared:
@pytest.mark.asyncio
async def test_00_connection_made_lost(self, connection, sftp_conn, sftp_adaptor, connections_manager,
... | import asyncio
import pytest
import pickle
from pathlib import Path
from aionetworking.compatibility import py37
@pytest.mark.connections('sftp_oneway_all')
class TestConnectionShared:
@pytest.mark.asyncio
async def test_00_connection_made_lost(self, connection, sftp_conn, sftp_adaptor, connections_manager,
... |
def get_yes_no(text: str="") -> bool:
answer = get_limited_options(["y", "n"], text)
return answer == "y"
def get_limited_options(limited_options, text=""):
limited_options = list(map(str, list(limited_options)))
answer = input(f"{text} ({"/".join(limited_options)})")
while answer.lower() not in l... | def get_yes_no(text: str="") -> bool:
answer = get_limited_options(["y", "n"], text)
return answer == "y"
def get_limited_options(limited_options, text=""):
limited_options = list(map(str, list(limited_options)))
answer = input(f"{text} ({'/'.join(limited_options)})")
while answer.lower() not in l... |
""" Prediction Controller """
__docformat__ = "numpy"
import argparse
from typing import List
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal impor... | """ Prediction Controller """
__docformat__ = "numpy"
import argparse
from typing import List
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal impor... |
#!/usr/bin/env python3
from typing import Tuple, Any, Dict, Optional, List, FrozenSet, Union, Type, Callable, Set
import json
import sys
import zlib
import re
import os
import argparse
import codecs
import hashlib
import enum
import shutil
from os.path import splitext
from datetime import date, datetime, timedelta, ... | #!/usr/bin/env python3
from typing import Tuple, Any, Dict, Optional, List, FrozenSet, Union, Type, Callable, Set
import json
import sys
import zlib
import re
import os
import argparse
import codecs
import hashlib
import enum
import shutil
from os.path import splitext
from datetime import date, datetime, timedelta, ... |
"""Common classes and elements for Omnilogic Integration."""
from datetime import timedelta
import logging
from omnilogic import OmniLogic, OmniLogicException
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_IDENTIFIERS,
ATTR_MANUFACTURER,
ATTR_MODEL,
ATTR_N... | """Common classes and elements for Omnilogic Integration."""
from datetime import timedelta
import logging
from omnilogic import OmniLogic, OmniLogicException
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_IDENTIFIERS,
ATTR_MANUFACTURER,
ATTR_MODEL,
ATTR_N... |
import pytest
@pytest.fixture
def admin(django_user_model):
return django_user_model.objects.create_superuser(username='TestUser', email='admin@yamdb.fake', password='1234567')
@pytest.fixture
def token(admin):
from rest_framework_simplejwt.tokens import RefreshToken
refresh = RefreshToken.for_user(admi... | import pytest
@pytest.fixture
def admin(django_user_model):
return django_user_model.objects.create_superuser(username='TestUser', email='admin@yamdb.fake', password='1234567')
@pytest.fixture
def token(admin):
from rest_framework_simplejwt.tokens import RefreshToken
refresh = RefreshToken.for_user(admi... |
import logging
import threading
import time
import traceback
from dataclasses import dataclass
from functools import reduce
from pathlib import Path
from typing import Dict, List, Optional, Set, Tuple, Union
from concurrent.futures.thread import ThreadPoolExecutor
from blspy import G1Element, PrivateKey
from chiapos i... | import logging
import threading
import time
import traceback
from dataclasses import dataclass
from functools import reduce
from pathlib import Path
from typing import Dict, List, Optional, Set, Tuple, Union
from concurrent.futures.thread import ThreadPoolExecutor
from blspy import G1Element, PrivateKey
from chiapos i... |
import os
import pickle as pkl
from hashlib import md5
from urllib.parse import urlparse
import requests
import wikipedia as wikipedia_api
from requests import utils as requests_utils
from wikidata.client import Client
from wikidata.entity import Entity, EntityId, EntityState
from tomt.data.imdb import ImdbID
WIKIDA... | import os
import pickle as pkl
from hashlib import md5
from urllib.parse import urlparse
import requests
import wikipedia as wikipedia_api
from requests import utils as requests_utils
from wikidata.client import Client
from wikidata.entity import Entity, EntityId, EntityState
from tomt.data.imdb import ImdbID
WIKIDA... |
from functools import wraps
import numpy as np
import inspect
import re
from dask import array as da
from .utilcls import Progress
from .._cupy import xp_ndarray, asnumpy
__all__ = ["record",
"record_lazy",
"same_dtype",
"dims_to_spatial_axes",
"make_history",
]
... | from functools import wraps
import numpy as np
import inspect
import re
from dask import array as da
from .utilcls import Progress
from .._cupy import xp_ndarray, asnumpy
__all__ = ["record",
"record_lazy",
"same_dtype",
"dims_to_spatial_axes",
"make_history",
]
... |
#MIT License
#Copyright (c) 2021 slgeekshow
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, ... | #MIT License
#Copyright (c) 2021 slgeekshow
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, ... |
import datetime
import flask
import inspect
import jwt
import jwt.exceptions
import redis
import user_agents as ua
import user_agents.parsers as ua_parser
import typing
import app.common.utils as utils
import app.database as db_module
import app.database.user as user_module
db = db_module.db
redis_db: redis.StrictRed... | import datetime
import flask
import inspect
import jwt
import jwt.exceptions
import redis
import user_agents as ua
import user_agents.parsers as ua_parser
import typing
import app.common.utils as utils
import app.database as db_module
import app.database.user as user_module
db = db_module.db
redis_db: redis.StrictRed... |
import grpc
from cli.constants import METAMAP
from proto.python.uwbionlp_pb2 import MetaMapInput
from proto.python.uwbionlp_pb2_grpc import MetaMapStub
class MetaMapChannelManager():
def __init__(self, container):
self.name = METAMAP
self.host = container.host
self.port = container.port
... | import grpc
from cli.constants import METAMAP
from proto.python.uwbionlp_pb2 import MetaMapInput
from proto.python.uwbionlp_pb2_grpc import MetaMapStub
class MetaMapChannelManager():
def __init__(self, container):
self.name = METAMAP
self.host = container.host
self.port = container.port
... |
"""Super class(es) that is inherited by all API objects."""
from .helper_functions import syntax_correcter
import logging
import json
logging.debug(f"In the {__name__} module.")
class APIClassTemplate(object):
"""The base framework for all/(most of) the objects in the FMC."""
REQUIRED_FOR_POST = ["name"]
... | """Super class(es) that is inherited by all API objects."""
from .helper_functions import syntax_correcter
import logging
import json
logging.debug(f"In the {__name__} module.")
class APIClassTemplate(object):
"""The base framework for all/(most of) the objects in the FMC."""
REQUIRED_FOR_POST = ["name"]
... |
""" Prometheus querying and result transformation
The module provides functionality to query a Prometheus server and
helpers to create correct query parameters.
"""
from datetime import datetime, timedelta
import time
from typing import Union
import aiohttp
from thumbling.luis import group_datetimeV2_entities
from... | """ Prometheus querying and result transformation
The module provides functionality to query a Prometheus server and
helpers to create correct query parameters.
"""
from datetime import datetime, timedelta
import time
from typing import Union
import aiohttp
from thumbling.luis import group_datetimeV2_entities
from... |
"""HVCS
"""
import logging
import mimetypes
import os
from typing import Any, Optional, Union, cast
from urllib.parse import urlsplit
from gitlab import exceptions, gitlab
from requests import HTTPError, Session
from requests.auth import AuthBase
from urllib3 import Retry
from .errors import ImproperConfigurationErro... | """HVCS
"""
import logging
import mimetypes
import os
from typing import Any, Optional, Union, cast
from urllib.parse import urlsplit
from gitlab import exceptions, gitlab
from requests import HTTPError, Session
from requests.auth import AuthBase
from urllib3 import Retry
from .errors import ImproperConfigurationErro... |
#!/usr/bin/python3.6
import ast
import sys
import tokenize
import pickle
from datetime import datetime
import re
import argparse
from functools import reduce
import json
from .genCode import genCode, PrintState
from .mod_index_generator import get_index
from .get_comments import get_comments
from . import For2PyError
... | #!/usr/bin/python3.6
import ast
import sys
import tokenize
import pickle
from datetime import datetime
import re
import argparse
from functools import reduce
import json
from .genCode import genCode, PrintState
from .mod_index_generator import get_index
from .get_comments import get_comments
from . import For2PyError
... |
#!/usr/bin/env python
from pathlib import Path
from datetime import datetime
from typing import Dict, Any, Sequence, Optional
from typing.io import TextIO
import xarray
import numpy as np
import logging
from .io import opener, rinexinfo
from .common import rinex_string_to_float
#
STARTCOL2 = 3 # column where numerical... | #!/usr/bin/env python
from pathlib import Path
from datetime import datetime
from typing import Dict, Any, Sequence, Optional
from typing.io import TextIO
import xarray
import numpy as np
import logging
from .io import opener, rinexinfo
from .common import rinex_string_to_float
#
STARTCOL2 = 3 # column where numerical... |
import typing
import ast
_HANDLE = {
}
def handle(expr):
return _HANDLE[ type(expr) ] (expr)
def _strip(s):
while ' ' in s:
s = s.replace(' ', ' ')
return s.strip()
def _transformer(expr):
args = ', '.join( [ handle(arg) for arg in expr.args ] )
return _strip(f'<{args}>')
def _inclu... | import typing
import ast
_HANDLE = {
}
def handle(expr):
return _HANDLE[ type(expr) ] (expr)
def _strip(s):
while ' ' in s:
s = s.replace(' ', ' ')
return s.strip()
def _transformer(expr):
args = ', '.join( [ handle(arg) for arg in expr.args ] )
return _strip(f'<{args}>')
def _inclu... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
"""
User actions against Keycloak.
"""
import asyncio
import logging
from .token import get_rest_client
logger = logging.getLogger('krs.users')
def _fix_attributes(user):
"""
"Fix" user attributes that are only a single value.
Translates them from a list to the single value. Operation
is done in-pl... | """
User actions against Keycloak.
"""
import asyncio
import logging
from .token import get_rest_client
logger = logging.getLogger('krs.users')
def _fix_attributes(user):
"""
"Fix" user attributes that are only a single value.
Translates them from a list to the single value. Operation
is done in-pl... |
import pymysql
import logging
import traceback
from singleton import Singleton
from database_config import MysqlDataBaseConfig
from config import Config
class MysqlDataBase(metaclass=Singleton):
def __init__(self, ticker_priority_exchange):
self.logger = logging.getLogger(
Config.LOGGING_NA... | import pymysql
import logging
import traceback
from singleton import Singleton
from database_config import MysqlDataBaseConfig
from config import Config
class MysqlDataBase(metaclass=Singleton):
def __init__(self, ticker_priority_exchange):
self.logger = logging.getLogger(
Config.LOGGING_NA... |
"""This modules contains helper methods to export nitextureproperty type nodes"""
# ***** BEGIN LICENSE BLOCK *****
#
# Copyright © 2020, NIF File Format Library and Tools contributors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided ... | """This modules contains helper methods to export nitextureproperty type nodes"""
# ***** BEGIN LICENSE BLOCK *****
#
# Copyright © 2020, NIF File Format Library and Tools contributors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided ... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import logging
import os
import sys
import time
from collections import defaultdict
import numpy as np
import pandas as pd
import torch
import torch.distributed as dist
from tensorboardX import SummaryWriter
from tor... | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import logging
import os
import sys
import time
from collections import defaultdict
import numpy as np
import pandas as pd
import torch
import torch.distributed as dist
from tensorboardX import SummaryWriter
from tor... |
import boto3
import os
import traceback
from string import ascii_lowercase
from random import choice
import json
import logging
import shutil
import time
from pathlib import Path
LOG = logging.getLogger(__name__)
def proxy_needed(cluster_name: str, boto3_session: boto3.Session) -> (boto3.client, str):
# If there... | import boto3
import os
import traceback
from string import ascii_lowercase
from random import choice
import json
import logging
import shutil
import time
from pathlib import Path
LOG = logging.getLogger(__name__)
def proxy_needed(cluster_name: str, boto3_session: boto3.Session) -> (boto3.client, str):
# If there... |
import http.client
import github3.exceptions
from github3 import GitHubError
from cumulusci.core.exceptions import GithubApiNotFoundError
from cumulusci.core.utils import process_bool_arg
from cumulusci.tasks.github.base import BaseGithubTask
from cumulusci.utils.git import is_release_branch
class MergeBranch(BaseG... | import http.client
import github3.exceptions
from github3 import GitHubError
from cumulusci.core.exceptions import GithubApiNotFoundError
from cumulusci.core.utils import process_bool_arg
from cumulusci.tasks.github.base import BaseGithubTask
from cumulusci.utils.git import is_release_branch
class MergeBranch(BaseG... |
from blpapi_import_helper import blpapi
from argparse import Action
_SESSION_IDENTITY_AUTH_OPTIONS = "sessionIdentityAuthOptions"
class AuthOptionsAction(Action):
"""The action that parses authorization options from user input"""
def __call__(self, parser, args, values, option_string=None):
... | from blpapi_import_helper import blpapi
from argparse import Action
_SESSION_IDENTITY_AUTH_OPTIONS = "sessionIdentityAuthOptions"
class AuthOptionsAction(Action):
"""The action that parses authorization options from user input"""
def __call__(self, parser, args, values, option_string=None):
... |
pessoas = {'nome': 'Álamo', 'sexo': 'M', 'idade': '26'}
print(pessoas['nome']) # quando eu passo o nome da chave dentro de colchetes ele me dá o item dessa chave
print(f'O {pessoas['nome']} tem {pessoas['idade']} anos.') # print formatado
print(pessoas.keys()) # me retorna todas as chaves
print(pessoas.values()... | pessoas = {'nome': 'Álamo', 'sexo': 'M', 'idade': '26'}
print(pessoas['nome']) # quando eu passo o nome da chave dentro de colchetes ele me dá o item dessa chave
print(f'O {pessoas["nome"]} tem {pessoas["idade"]} anos.') # print formatado
print(pessoas.keys()) # me retorna todas as chaves
print(pessoas.values()... |
import asyncio
import os
import sys
import traceback
import aiohttp
from aiohttp import web
import cachetools
from gidgethub import aiohttp as gh_aiohttp
from gidgethub import routing
from gidgethub import sansio
from webservice import utils
router = routing.Router()
cache = cachetools.LRUCache(maxsize=500)
route... | import asyncio
import os
import sys
import traceback
import aiohttp
from aiohttp import web
import cachetools
from gidgethub import aiohttp as gh_aiohttp
from gidgethub import routing
from gidgethub import sansio
from webservice import utils
router = routing.Router()
cache = cachetools.LRUCache(maxsize=500)
route... |
import logging
from os import unlink
from pathlib import Path
from secrets import token_bytes
from shutil import copy, move
import time
import pytest
from blspy import AugSchemeMPL
from chiapos import DiskPlotter
from tranzact.consensus.coinbase import create_puzzlehash_for_pk
from tranzact.plotting.util import strea... | import logging
from os import unlink
from pathlib import Path
from secrets import token_bytes
from shutil import copy, move
import time
import pytest
from blspy import AugSchemeMPL
from chiapos import DiskPlotter
from tranzact.consensus.coinbase import create_puzzlehash_for_pk
from tranzact.plotting.util import strea... |
# -*- coding: utf-8 -*-
"""Implements the base xonsh parser."""
import os
import re
import time
import textwrap
from threading import Thread
from ast import parse as pyparse
from collections.abc import Iterable, Sequence, Mapping
try:
from ply import yacc
except ImportError:
from xonsh.ply.ply import yacc
fro... | # -*- coding: utf-8 -*-
"""Implements the base xonsh parser."""
import os
import re
import time
import textwrap
from threading import Thread
from ast import parse as pyparse
from collections.abc import Iterable, Sequence, Mapping
try:
from ply import yacc
except ImportError:
from xonsh.ply.ply import yacc
fro... |
from dataclasses import make_dataclass
import numpy as np
from scipy.optimize import OptimizeResult
from .util import TAB, ReprMixin, spearman2d, pearson2d
class Parameter(ReprMixin):
def __init__(self, guess, bounds, grid_range=None):
"""
Class that defines the fitting characteristics of a Para... | from dataclasses import make_dataclass
import numpy as np
from scipy.optimize import OptimizeResult
from .util import TAB, ReprMixin, spearman2d, pearson2d
class Parameter(ReprMixin):
def __init__(self, guess, bounds, grid_range=None):
"""
Class that defines the fitting characteristics of a Para... |
import abc
import typing as t
from collections import namedtuple
import discord.errors
from botcore.site_api import ResponseCodeError
from discord import Guild
from discord.ext.commands import Context
from more_itertools import chunked
import bot
from bot.log import get_logger
log = get_logger(__name__)
CHUNK_SIZE ... | import abc
import typing as t
from collections import namedtuple
import discord.errors
from botcore.site_api import ResponseCodeError
from discord import Guild
from discord.ext.commands import Context
from more_itertools import chunked
import bot
from bot.log import get_logger
log = get_logger(__name__)
CHUNK_SIZE ... |
from io import StringIO
import json
import shutil
default_dir_schema = 'schema.json'
class Schema:
"""
{[clear] -> load} -> [create] -> (safe) edit -> dump
note: [] is optional, {} is init
states: loaded -> created
"""
def __init__(self, dir_schema: str=None) -> None:
self.schema = {... | from io import StringIO
import json
import shutil
default_dir_schema = 'schema.json'
class Schema:
"""
{[clear] -> load} -> [create] -> (safe) edit -> dump
note: [] is optional, {} is init
states: loaded -> created
"""
def __init__(self, dir_schema: str=None) -> None:
self.schema = {... |
import subprocess, os, struct
from . import flatten_list, _monitor_brand_lookup
class _EDID:
'''
simple structure and method to extract monitor serial and name from an EDID string.
The EDID parsing was created with inspiration from the [pyedid library](https://github.com/jojonas/pyedid)
'''
... | import subprocess, os, struct
from . import flatten_list, _monitor_brand_lookup
class _EDID:
'''
simple structure and method to extract monitor serial and name from an EDID string.
The EDID parsing was created with inspiration from the [pyedid library](https://github.com/jojonas/pyedid)
'''
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2021 Snowflake Computing Inc. All right reserved.
#
from __future__ import division
import os
import shutil
import time
from collections import namedtuple
from io import BytesIO
from logging import getLogger
from typing import TYPE_CHECKING
from bo... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2021 Snowflake Computing Inc. All right reserved.
#
from __future__ import division
import os
import shutil
import time
from collections import namedtuple
from io import BytesIO
from logging import getLogger
from typing import TYPE_CHECKING
from bo... |
import os, sys
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, QEvent, QBuffer, QIODevice, QLocale, Qt, QVariant, QModelIndex
from PyQt5 import QtGui, QtWidgets, QtCore
import time
import numpy as np
from pymodaq.daq_utils import daq_utils as utils
from pymodaq.daq_utils.gui_utils import select_file
from pyqtgr... | import os, sys
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, QEvent, QBuffer, QIODevice, QLocale, Qt, QVariant, QModelIndex
from PyQt5 import QtGui, QtWidgets, QtCore
import time
import numpy as np
from pymodaq.daq_utils import daq_utils as utils
from pymodaq.daq_utils.gui_utils import select_file
from pyqtgr... |
from collections import (
namedtuple,
)
import datetime
import hashlib
import hmac
import json
import os
import urllib
from jupyterhub.spawner import (
Spawner,
)
from tornado import (
gen,
)
from tornado.concurrent import (
Future,
)
from tornado.httpclient import (
AsyncHTTPClient,
HTTPError,... | from collections import (
namedtuple,
)
import datetime
import hashlib
import hmac
import json
import os
import urllib
from jupyterhub.spawner import (
Spawner,
)
from tornado import (
gen,
)
from tornado.concurrent import (
Future,
)
from tornado.httpclient import (
AsyncHTTPClient,
HTTPError,... |
import argparse
import json
from bs4 import BeautifulSoup
def format_answer(data):
with open(args.data, "r") as file:
data = file.readlines()
soups = [BeautifulSoup(d, 'html.parser') for d in data]
is_first = True
doc_id = -1
sent_id = 0
for soup in soups:
sent_id += 1
... | import argparse
import json
from bs4 import BeautifulSoup
def format_answer(data):
with open(args.data, "r") as file:
data = file.readlines()
soups = [BeautifulSoup(d, 'html.parser') for d in data]
is_first = True
doc_id = -1
sent_id = 0
for soup in soups:
sent_id += 1
... |
#!/usr/bin/env python3
import os
import pathlib
import pprint
import sys
import traceback
import m2r
import msgpack
from jinja2 import Template
from tqdm import tqdm
DISABLE_TQDM = "CI" in os.environ
REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent
LOCAL_CACHE_PATH = pathlib.Path(
os.environ.get("LOCAL... | #!/usr/bin/env python3
import os
import pathlib
import pprint
import sys
import traceback
import m2r
import msgpack
from jinja2 import Template
from tqdm import tqdm
DISABLE_TQDM = "CI" in os.environ
REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent
LOCAL_CACHE_PATH = pathlib.Path(
os.environ.get("LOCAL... |
import logging
from asyncio import sleep as asleep # For waiting asynchronously.
from os import listdir # To check files on disk.
from asyncpg import IntegrityConstraintViolationError # To check for database conflicts.
from discord import Embed, Activity, ActivityType # For bot status
from discord.ext import comma... | import logging
from asyncio import sleep as asleep # For waiting asynchronously.
from os import listdir # To check files on disk.
from asyncpg import IntegrityConstraintViolationError # To check for database conflicts.
from discord import Embed, Activity, ActivityType # For bot status
from discord.ext import comma... |
import sys
import pytest
import pytorch_testing_utils as ptu
import torch
import torch.nn.functional as F
from torch import nn
from torch.utils import data
from pystiche import loss, ops, optim
from tests import mocks
skip_if_py38 = pytest.mark.skipif(
sys.version_info >= (3, 8),
reason=(
"Test err... | import sys
import pytest
import pytorch_testing_utils as ptu
import torch
import torch.nn.functional as F
from torch import nn
from torch.utils import data
from pystiche import loss, ops, optim
from tests import mocks
skip_if_py38 = pytest.mark.skipif(
sys.version_info >= (3, 8),
reason=(
"Test err... |
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the NiBabel package for the
# copyright and license terms.
#
### ### ### #... | # emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the NiBabel package for the
# copyright and license terms.
#
### ### ### #... |
# --------- Notes ---------
# This version uses PostgreSQL as the backend database
# The reason why is that SQLite3 locks up very fast and is not recommended for cogs like these, where high read/write speeds are key
# Make sure to have an PostgreSQL server running, and a database called "disquest"
import asyncio
... | # --------- Notes ---------
# This version uses PostgreSQL as the backend database
# The reason why is that SQLite3 locks up very fast and is not recommended for cogs like these, where high read/write speeds are key
# Make sure to have an PostgreSQL server running, and a database called "disquest"
import asyncio
... |
import requests
from .enums import TransactionStatus
from .exceptions import InvalidPaymentException, SslcommerzAPIException
from .services import PayloadSchema, is_verify_sign_valid
DEFAULT_CONFIG = {
"base_url": "https://sandbox.sslcommerz.com",
"session_url": "/gwprocess/v4/api.php",
"validation_url":... | import requests
from .enums import TransactionStatus
from .exceptions import InvalidPaymentException, SslcommerzAPIException
from .services import PayloadSchema, is_verify_sign_valid
DEFAULT_CONFIG = {
"base_url": "https://sandbox.sslcommerz.com",
"session_url": "/gwprocess/v4/api.php",
"validation_url":... |
"""Config flow for ZHA."""
from __future__ import annotations
import os
from typing import Any
import serial.tools.list_ports
import voluptuous as vol
from zigpy.config import CONF_DEVICE, CONF_DEVICE_PATH
from homeassistant import config_entries
from .core.const import (
CONF_BAUDRATE,
CONF_FLOWCONTROL,
... | """Config flow for ZHA."""
from __future__ import annotations
import os
from typing import Any
import serial.tools.list_ports
import voluptuous as vol
from zigpy.config import CONF_DEVICE, CONF_DEVICE_PATH
from homeassistant import config_entries
from .core.const import (
CONF_BAUDRATE,
CONF_FLOWCONTROL,
... |
#!/usr/local/bin/python3
import sys
import app
from parser import create_parser, ACTIONS
REQUIRED_FIELDS = ['path']
if __name__ == '__main__':
app.setup_directories()
parser = create_parser()
args = parser.parse_args()
if (args.new):
if not all([getattr(args, field) for field in REQUIRED_FIEL... | #!/usr/local/bin/python3
import sys
import app
from parser import create_parser, ACTIONS
REQUIRED_FIELDS = ['path']
if __name__ == '__main__':
app.setup_directories()
parser = create_parser()
args = parser.parse_args()
if (args.new):
if not all([getattr(args, field) for field in REQUIRED_FIEL... |
import math
from copy import deepcopy
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from miyanmaayeh.runner import Runner
PLOT_DIR = "verification/"
Path(PLOT_DIR).mkdir(parents=True, exist_ok=True)
NUM_RUNS = 5
ITERS = 500
def generate_plots(runners):
sns.s... | import math
from copy import deepcopy
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from miyanmaayeh.runner import Runner
PLOT_DIR = "verification/"
Path(PLOT_DIR).mkdir(parents=True, exist_ok=True)
NUM_RUNS = 5
ITERS = 500
def generate_plots(runners):
sns.s... |
"""Datastructures for Adaptive immune receptor (IR) data.
Currently only used as intermediate storage.
See also discussion at https://github.com/theislab/anndata/issues/115
"""
from ..util import _is_na2, _is_true2, _doc_params
from typing import Collection, Dict, Iterable, List, Mapping, Optional, Iterator, Tuple
fr... | """Datastructures for Adaptive immune receptor (IR) data.
Currently only used as intermediate storage.
See also discussion at https://github.com/theislab/anndata/issues/115
"""
from ..util import _is_na2, _is_true2, _doc_params
from typing import Collection, Dict, Iterable, List, Mapping, Optional, Iterator, Tuple
fr... |
import os
from spirl.models.closed_loop_spirl_mdl import ClSPiRLMdl
from spirl.models.skill_prior_mdl import SkillSpaceLogger
from spirl.utils.general_utils import AttrDict
from spirl.configs.default_data_configs.maze import data_spec
from spirl.components.evaluator import TopOfNSequenceEvaluator
from spirl.data.maze.... | import os
from spirl.models.closed_loop_spirl_mdl import ClSPiRLMdl
from spirl.models.skill_prior_mdl import SkillSpaceLogger
from spirl.utils.general_utils import AttrDict
from spirl.configs.default_data_configs.maze import data_spec
from spirl.components.evaluator import TopOfNSequenceEvaluator
from spirl.data.maze.... |
#!/usr/bin/env python3
import json
import math
import numpy as np
import re
import sys
from terminaltables import AsciiTable
from termcolor import colored
from scipy.stats import ttest_ind
p_value_significance_threshold = 0.001
min_iterations = 10
min_runtime_ns = 59 * 1000 * 1000 * 1000
min_iterations_disabling_min_... | #!/usr/bin/env python3
import json
import math
import numpy as np
import re
import sys
from terminaltables import AsciiTable
from termcolor import colored
from scipy.stats import ttest_ind
p_value_significance_threshold = 0.001
min_iterations = 10
min_runtime_ns = 59 * 1000 * 1000 * 1000
min_iterations_disabling_min_... |
# pylint: disable=too-many-lines
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------... | # pylint: disable=too-many-lines
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------... |
"""CoronaVirus LookUp
Syntax: .covid <country>"""
from covid import Covid
from uniborg.util import admin_cmd
@borg.on(admin_cmd(pattern="covid ?(.*)", allow_sudo=True))
async def corona(event):
await event.edit("`Processing...`")
if event.pattern_match.group(1):
country = event.pattern_match.group(1... | """CoronaVirus LookUp
Syntax: .covid <country>"""
from covid import Covid
from uniborg.util import admin_cmd
@borg.on(admin_cmd(pattern="covid ?(.*)", allow_sudo=True))
async def corona(event):
await event.edit("`Processing...`")
if event.pattern_match.group(1):
country = event.pattern_match.group(1... |
from multiprocessing import Pool
from cfg import UNKNOWN_ERROR, TIMED_OUT
try:
from python.make_dir import make_dir
from python.get_this_url import get_this_url
from python.pic_format import pic_format
except (ImportError, FileNotFoundError, ModuleNotFoundError) as e:
from make_dir import make_dir
... | from multiprocessing import Pool
from cfg import UNKNOWN_ERROR, TIMED_OUT
try:
from python.make_dir import make_dir
from python.get_this_url import get_this_url
from python.pic_format import pic_format
except (ImportError, FileNotFoundError, ModuleNotFoundError) as e:
from make_dir import make_dir
... |
from asyncdbus import Message, MessageBus
from asyncdbus._private.address import parse_address
import anyio
import pytest
import os
@pytest.mark.anyio
async def test_tcp_connection_with_forwarding():
async with anyio.create_task_group() as tg:
closables = []
host = '127.0.0.1'
port = '555... | from asyncdbus import Message, MessageBus
from asyncdbus._private.address import parse_address
import anyio
import pytest
import os
@pytest.mark.anyio
async def test_tcp_connection_with_forwarding():
async with anyio.create_task_group() as tg:
closables = []
host = '127.0.0.1'
port = '555... |
"""
The main tytg module.
"""
import telegram.ext
import argparse, logging
import os, os.path, subprocess
import json, ast, random
from glob import glob
from telegram import ReplyKeyboardMarkup as RKM
from telegram import KeyboardButton as KB
class User:
"""
This class represent an user that's using the bot.
"""
... | """
The main tytg module.
"""
import telegram.ext
import argparse, logging
import os, os.path, subprocess
import json, ast, random
from glob import glob
from telegram import ReplyKeyboardMarkup as RKM
from telegram import KeyboardButton as KB
class User:
"""
This class represent an user that's using the bot.
"""
... |
'''Shows the stats of a NT team.'''
from discord.ext import commands
from packages.utils import Embed, ImproperType
from packages.nitrotype import Team, Racer
import json, os, requests
from datetime import datetime
from mongoclient import DBClient
class Command(commands.Cog):
def __init__(self, client):
s... | '''Shows the stats of a NT team.'''
from discord.ext import commands
from packages.utils import Embed, ImproperType
from packages.nitrotype import Team, Racer
import json, os, requests
from datetime import datetime
from mongoclient import DBClient
class Command(commands.Cog):
def __init__(self, client):
s... |
import fnmatch
import mimetypes
import os
from datetime import datetime, timedelta, timezone
from threading import Thread
from time import sleep, time
import requests
from dateutil import parser
from requests import auth
import config
from db_handler import db_queue
from frameioclient.utils import calculate_hash
from... | import fnmatch
import mimetypes
import os
from datetime import datetime, timedelta, timezone
from threading import Thread
from time import sleep, time
import requests
from dateutil import parser
from requests import auth
import config
from db_handler import db_queue
from frameioclient.utils import calculate_hash
from... |
'''
This tool provides a method to lookup constants to easily decode, for instance,
ErrorCodes.
'''
import argparse
from pathlib import Path
from collections import Counter
from tinydb import TinyDB, where
from rich.console import Console
from rich.padding import Padding
def const_lookup(search, const_type=None):
... | '''
This tool provides a method to lookup constants to easily decode, for instance,
ErrorCodes.
'''
import argparse
from pathlib import Path
from collections import Counter
from tinydb import TinyDB, where
from rich.console import Console
from rich.padding import Padding
def const_lookup(search, const_type=None):
... |
"""
by Caio Madeira
see hexadecimal colors in: https://htmlcolorcodes.com/
bug splash screen and main solved: https://stackoverflow.com/questions/38676617/tkinter-show-splash-screen-and-hide-main-screen-until-init-has-finished
"""
import random
import time
from tkinter import *
from tkinter import ttk
import tkint... | """
by Caio Madeira
see hexadecimal colors in: https://htmlcolorcodes.com/
bug splash screen and main solved: https://stackoverflow.com/questions/38676617/tkinter-show-splash-screen-and-hide-main-screen-until-init-has-finished
"""
import random
import time
from tkinter import *
from tkinter import ttk
import tkint... |
from __future__ import unicode_literals
import re
import sys
import types
from django.conf import settings
from django.core.urlresolvers import Resolver404, resolve
from django.http import HttpResponse, HttpResponseNotFound
from django.template import Context, Engine, TemplateDoesNotExist
from django.template.default... | from __future__ import unicode_literals
import re
import sys
import types
from django.conf import settings
from django.core.urlresolvers import Resolver404, resolve
from django.http import HttpResponse, HttpResponseNotFound
from django.template import Context, Engine, TemplateDoesNotExist
from django.template.default... |
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import os
import pytest
import threading
from datetime import datetime
import time
from openvino.inference_engine import ie_api as ie
from conftest import model_path, image_path, create_encoder
import ngraph as ng
fro... | # Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import os
import pytest
import threading
from datetime import datetime
import time
from openvino.inference_engine import ie_api as ie
from conftest import model_path, image_path, create_encoder
import ngraph as ng
fro... |
import os
from typing import Optional
from grapl_common.utils.primitive_convertors import to_bool
IS_LOCAL = to_bool(os.getenv("IS_LOCAL", default=False))
def endpoint_url(suffix: Optional[str]) -> str:
"""Builds the URL for the Grapl API endpoint corresponding to
the given suffix. This function expects tha... | import os
from typing import Optional
from grapl_common.utils.primitive_convertors import to_bool
IS_LOCAL = to_bool(os.getenv("IS_LOCAL", default=False))
def endpoint_url(suffix: Optional[str]) -> str:
"""Builds the URL for the Grapl API endpoint corresponding to
the given suffix. This function expects tha... |
"""
dayong.utils
~~~~~~~~~~~~
This module provides useful functions that facilitate some of Dayong's routine
operations.
"""
import asyncio
import functools
from typing import Any, Awaitable, Callable
SUPPORTED_DB = ("postgres://",)
def format_db_url(database_url: str) -> str:
"""Format the default database URL... | """
dayong.utils
~~~~~~~~~~~~
This module provides useful functions that facilitate some of Dayong's routine
operations.
"""
import asyncio
import functools
from typing import Any, Awaitable, Callable
SUPPORTED_DB = ("postgres://",)
def format_db_url(database_url: str) -> str:
"""Format the default database URL... |
import logging
import sys
from tonguetwister.lib.helper import grouper
class LastPartFilter(logging.Filter):
def filter(self, record):
record.name_last = record.name.rsplit('.', 1)[-1]
return True
def setup_logger(log_level=None):
if log_level is None:
log_level = logging.DEBUG
... | import logging
import sys
from tonguetwister.lib.helper import grouper
class LastPartFilter(logging.Filter):
def filter(self, record):
record.name_last = record.name.rsplit('.', 1)[-1]
return True
def setup_logger(log_level=None):
if log_level is None:
log_level = logging.DEBUG
... |
#!/usr/bin/env python
from argparse import ArgumentParser
from models import UNet
import torch
from ignite.contrib.handlers import ProgressBar
from ignite.engine import Events
from ignite.utils import manual_seed
from pathlib import Path
from models import SegNet
import json
import numpy as np
from coteaching import k... | #!/usr/bin/env python
from argparse import ArgumentParser
from models import UNet
import torch
from ignite.contrib.handlers import ProgressBar
from ignite.engine import Events
from ignite.utils import manual_seed
from pathlib import Path
from models import SegNet
import json
import numpy as np
from coteaching import k... |
import os
import sys
os.system(f"""gpg --quiet --batch --yes --decrypt --passphrase="{os.environ["DRIVE_SECRET"]}" --output token.json token.json.gpg""")
| import os
import sys
os.system(f"""gpg --quiet --batch --yes --decrypt --passphrase="{os.environ['DRIVE_SECRET']}" --output token.json token.json.gpg""")
|
import datetime, random
from django.conf import settings
from background_task import background
from background_task.models import Task
from templated_email import send_templated_mail
from newsletter.models import Subscriber
from idea.models import Idea
from the_impossible.utils import *
# Send email to users every... | import datetime, random
from django.conf import settings
from background_task import background
from background_task.models import Task
from templated_email import send_templated_mail
from newsletter.models import Subscriber
from idea.models import Idea
from the_impossible.utils import *
# Send email to users every... |
import logging
import statistics
import requests
from .client import AddressLookupClient
from ..errors import AddressLookupException
from ..result import AddressLookupResult, AddressLookupResultType
class AddressLookupHereClient(AddressLookupClient):
"""Client for the HERE Address Lookup API"""
_url = "htt... | import logging
import statistics
import requests
from .client import AddressLookupClient
from ..errors import AddressLookupException
from ..result import AddressLookupResult, AddressLookupResultType
class AddressLookupHereClient(AddressLookupClient):
"""Client for the HERE Address Lookup API"""
_url = "htt... |
"""Support for control of ElkM1 sensors."""
from elkm1_lib.const import (
SettingFormat,
ZoneLogicalStatus,
ZonePhysicalStatus,
ZoneType,
)
from elkm1_lib.util import pretty_const, username
from . import ElkAttachedEntity, create_elk_entities
from .const import DOMAIN
UNDEFINED_TEMPATURE = -40
async... | """Support for control of ElkM1 sensors."""
from elkm1_lib.const import (
SettingFormat,
ZoneLogicalStatus,
ZonePhysicalStatus,
ZoneType,
)
from elkm1_lib.util import pretty_const, username
from . import ElkAttachedEntity, create_elk_entities
from .const import DOMAIN
UNDEFINED_TEMPATURE = -40
async... |
#!/usr/bin/python3
# coding=utf-8
# pylint: skip-file
# Copyright 2019 getcarrier.io
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-... | #!/usr/bin/python3
# coding=utf-8
# pylint: skip-file
# Copyright 2019 getcarrier.io
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-... |
"""Graph representation aggregation layer."""
from abc import abstractmethod
from typing import List, NamedTuple, Optional
import tensorflow as tf
from dpu_utils.tf2utils import MLP, get_activation_function_by_name, unsorted_segment_softmax
class NodesToGraphRepresentationInput(NamedTuple):
"""A named tuple to h... | """Graph representation aggregation layer."""
from abc import abstractmethod
from typing import List, NamedTuple, Optional
import tensorflow as tf
from dpu_utils.tf2utils import MLP, get_activation_function_by_name, unsorted_segment_softmax
class NodesToGraphRepresentationInput(NamedTuple):
"""A named tuple to h... |
# coding=utf-8
# Copyright 2020-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... | # coding=utf-8
# Copyright 2020-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... |
#!/usr/bin/python3
import logging
logging.basicConfig(level=logging.WARNING)
import xmlrpc.client
import requests, datetime, os, sys
from json import dumps, loads
from PyQt5 import QtCore, QtWidgets
from PyQt5 import uic
from PyQt5.QtCore import QDir
from PyQt5.QtGui import QFontDatabase
def relpath(filename):
try... | #!/usr/bin/python3
import logging
logging.basicConfig(level=logging.WARNING)
import xmlrpc.client
import requests, datetime, os, sys
from json import dumps, loads
from PyQt5 import QtCore, QtWidgets
from PyQt5 import uic
from PyQt5.QtCore import QDir
from PyQt5.QtGui import QFontDatabase
def relpath(filename):
try... |
from json import JSONDecodeError
from urllib.parse import urljoin
from uuid import UUID
from django.conf import settings
from requests import RequestException
from requests import get as _get
from ..constants import REQUEST_TIMEOUT_SECONDS
from .exceptions import GetPaymentError, ParsePaymentError
from .types import ... | from json import JSONDecodeError
from urllib.parse import urljoin
from uuid import UUID
from django.conf import settings
from requests import RequestException
from requests import get as _get
from ..constants import REQUEST_TIMEOUT_SECONDS
from .exceptions import GetPaymentError, ParsePaymentError
from .types import ... |
import sys
import reconcile.utils.gql as gql
import reconcile.queries as queries
import reconcile.openshift_base as ob
from reconcile.utils.semver_helper import make_semver
from reconcile.utils.openshift_resource import (OpenshiftResource as OR,
ResourceKeyExistsError)
... | import sys
import reconcile.utils.gql as gql
import reconcile.queries as queries
import reconcile.openshift_base as ob
from reconcile.utils.semver_helper import make_semver
from reconcile.utils.openshift_resource import (OpenshiftResource as OR,
ResourceKeyExistsError)
... |
import uuid
import time
import requests
import urllib3
import boto3
import cfnresponse
from log_mechanism import LogMechanism
from pvwa_integration import PvwaIntegration
from dynamo_lock import LockerClient
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
DEBUG_LEVEL_DEBUG = 'debug' # Outputs all ... | import uuid
import time
import requests
import urllib3
import boto3
import cfnresponse
from log_mechanism import LogMechanism
from pvwa_integration import PvwaIntegration
from dynamo_lock import LockerClient
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
DEBUG_LEVEL_DEBUG = 'debug' # Outputs all ... |
import math
from collections.abc import Iterable
from operator import itemgetter
import random
import os
from glob import glob
from .geom import hflip_pattern, vflip_pattern, rot_pattern
from .error import GollyPatternsError
def get_patterns():
patternfiles = glob(
os.path.join(os.path.dirname(os.path.abs... | import math
from collections.abc import Iterable
from operator import itemgetter
import random
import os
from glob import glob
from .geom import hflip_pattern, vflip_pattern, rot_pattern
from .error import GollyPatternsError
def get_patterns():
patternfiles = glob(
os.path.join(os.path.dirname(os.path.abs... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.