content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from posixpath import join
import threading
from civis.response import PaginatedResponse, convert_response_data_type
def tostr_urljoin(*x):
return join(*map(str, x))
class CivisJobFailure(Exception):
def __init__(self, err_msg, response=None):
self.error_message = err_msg
self.response = re... | python |
class InstantTest:
pass
| python |
import os
import numpy as np
from PIL import Image
import cv2
import pickle
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
image_dir = os.path.join(BASE_DIR, "images")
face_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt2.xml')
recognizer = cv2.face.LBPHFaceRecognizer_create()
curre... | python |
from rest_framework import status
from .base_test import BaseTestCase
class TestProfile(BaseTestCase):
"""Test the User profile GET responses"""
all_profiles_url = 'http://127.0.0.1:8000/api/profiles/'
my_profile_url = 'http://127.0.0.1:8000/api/profiles/jane'
def test_get_all_profiles_without_accou... | python |
import lambdser
import multiprocessing as mp
def make_proxy(para, *funcs):
# make proxy for the mp
ser_list = []
for f in funcs:
ser_list.append(lambdser.dumps(f))
return para, ser_list
def processor(*ser):
# unzip the proxy and to the work
para, funcs = ser
funcs = [lambdser.loa... | python |
from numbers import Number
import torch
from torch.distributions import constraints, Gamma, MultivariateNormal
from torch.distributions.multivariate_normal import _batch_mv, _batch_mahalanobis
from torch.distributions.distribution import Distribution
from torch.distributions.utils import broadcast_all, _standard_normal... | python |
import json
from pathlib import Path
from typing import Tuple
from segmantic.seg import dataset
def dataset_mockup(root_path: Path, size: int = 3) -> Tuple[Path, Path]:
image_dir, labels_dir = root_path / "image", root_path / "label"
image_dir.mkdir()
labels_dir.mkdir()
for idx in range(size):
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Created on Mon Apr 10 17:41:24 2017
# DEPENDENCIES:
import numpy as np
import random
# FUNCTION THAT CREATES GAUSSIAN MULTIVARIATE 2D DATASETS, D = features, N = observations
def create_multivariate_Gauss_2D_dataset(mean, sigma, N_observations):
np.random.seed(444... | python |
# Generated by Django 3.1.7 on 2021-03-17 12:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backoffice', '0027_auto_20210317_1314'),
]
operations = [
migrations.AlterField(
model_name='partitionformulla',
nam... | python |
# -*- coding: utf8 -*-
from __future__ import unicode_literals
from django.db import models
from datetime import datetime
from users.models import UserProfile
# Create your models here.
class Tab(models.Model):
name = models.CharField(max_length=50, verbose_name='标签名称')
add_time = models.DateTimeField(defa... | python |
import unittest
import requests
from pyalt.api.objects import AltObject
class TestAPIObjects(unittest.TestCase):
def setUp(self):
url_fmt = "https://online-shkola.com.ua/api/v2/users/1269/thematic/subject/{}"
self.responses = {
requests.get(url_fmt.format(n))
for n in (3... | python |
import logging
import re
from collections import OrderedDict
from io import StringIO
import numpy as np
from .._exceptions import ReadError
from .._files import open_file
from .._helpers import register
from .._mesh import CellBlock, Mesh
float_pattern = r"[+-]?(?:\d+\.?\d*|\d*\.?\d+)"
float_re = re.compile(float_pa... | python |
# -*- coding:utf-8 -*-
# author:Anson
from __future__ import unicode_literals
import os
import sys
import re
from datetime import date, datetime, timedelta
from docx import Document
import xlwt
from settings import MD_PATH, SITE_1, SITE_2, CELL
reload(sys)
sys.setdefaultencoding('utf-8')
def get_file_path(path, ... | python |
##############################################################################
# Copyright 2016 IBM Corp.
#
# 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/LI... | python |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from collections import OrderedDict as odict
from copy import deepcopy
from functools import partial
import sys
import bindings as bi
from custom import get_customizations_for, reformat_block
PY3 = sys.version_info[0] == 3
str_typ... | python |
"""
1. Clarification
2. Possible solutions
- Dynamic programming
- Divide and Conquer
3. Coding
4. Tests
"""
# T=O(n), S=O(1)
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
if not nums: return 0
maxn, subSum = -math.inf, 0
for num in nums:
subSum += num
... | python |
import logging
from easyjoblite import state, constants
from easyjoblite.utils import kill_process
logger = logging.getLogger(__name__)
class WorkerManager(object):
@staticmethod
def stop_all_workers(worker_type):
"""
stops all the workers of the given type
:param worker_type:
... | python |
#!/usr/bin/env python2
# Copyright (C) 2001 Jeff Epler <jepler@unpythonic.dhs.org>
# Copyright (C) 2006 Csaba Henk <csaba.henk@creo.hu>
# Copyright (C) 2011 Marek Kubica <marek@xivilization.net>
#
# This program can be distributed under the terms of the GNU LGPLv3.
import os, sys
from errno import *
from stat import *... | python |
import igraph
import numpy as np
import pandas as pd
from tqdm import tqdm
from feature_engineering.tools import lit_eval_nan_proof
# this script adds the feature shortest_path to the files training_features and testing_features
# this script takes approximately 1000 minutes to execute
# progress bar for pandas
tqdm... | python |
# encoding: utf-8
"""
lxml custom element classes for shape tree-related XML elements.
"""
from __future__ import absolute_import
from .autoshape import CT_Shape
from .connector import CT_Connector
from ...enum.shapes import MSO_CONNECTOR_TYPE
from .graphfrm import CT_GraphicalObjectFrame
from ..ns import qn
from .p... | python |
import sys
import sh
def app(name, *args, _out=sys.stdout, _err=sys.stderr, _tee=True, **kwargs):
try:
return sh.Command(name).bake(
*args, _out=_out, _err=_err, _tee=_tee, **kwargs
)
except sh.CommandNotFound:
return sh.Command(sys.executable).bake(
"-c",
... | python |
"""
This options file demonstrates how to run a stripping line
from a specific stripping version on a local MC DST file
It is based on the minimal DaVinci DecayTreeTuple example
"""
from StrippingConf.Configuration import StrippingConf, StrippingStream
from StrippingSettings.Utils import strippingConfiguration
from St... | python |
from .base import BaseField
class IntegerField(BaseField):
pass
| python |
def ingredients(count):
"""Prints ingredients for making `count` arepas."""
print('{:.2} cups arepa flour'.format(0.1*count))
print('{:.2} cups cheese'.format(0.1*count))
print('{:.2} cups water'.format(0.025*count))
| python |
from __future__ import absolute_import, unicode_literals
import os
import celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_project.settings')
app = celery.Celery('test_project') # noqa: pylint=invalid-name
# Using a string here means the... | python |
'''
Created on Apr 15, 2016
@author: Drew
'''
class CogTV:
def __init__(self):
pass
def setScreen(self, scene):
pass
| python |
import sys
import csv
import numpy as np
import statistics
import scipy.stats
def anova(index, norobot_data, video_data, robot_data):
norobot_mean = norobot_data.mean(axis = 0)[index]
video_mean = video_data.mean(axis = 0)[index]
robot_mean = robot_data.mean(axis = 0)[index]
group_means = [... | python |
from .sequence_tagger_model import SequenceTagger, MultiTagger
from .language_model import LanguageModel
from .text_classification_model import TextClassifier
from .pairwise_classification_model import TextPairClassifier
from .relation_extractor_model import RelationExtractor
from .entity_linker_model import EntityLink... | python |
def longestPalindromicSubstring(string):
longest = ""
for i in range(len(string)):
for j in range(i, len(string)):
substring = string[i : j + 1]
if len(substring) > len(longest) and isPalindrome(substring):
longest = substring
return longest
def isPalindrome(string):
leftIdx = 0
rightIdx = len(stri... | python |
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from user.models import User
from user.serializers import UserSerializer
import redis
import uuid
import pycountry
# initiates the redis instance.
redis_... | python |
import cv2
import numpy as np
import BboxToolkit as bt
import pycocotools.mask as maskUtils
from mmdet.core import PolygonMasks, BitmapMasks
pi = 3.141592
def bbox2mask(bboxes, w, h, mask_type='polygon'):
polys = bt.bbox2type(bboxes, 'poly')
assert mask_type in ['polygon', 'bitmap']
if mask_type == 'bit... | python |
from flask_sqlalchemy import SQLAlchemy
from typing import Optional, Set
from models import Team, ProblemSet, PermissionPack
class DefaultPermissionProvider:
def __init__(self, db: SQLAlchemy) -> None:
self.db = db
def get_contest_permissions(self, uid: int, contest_id: Optional[str]) -> S... | python |
import pytest
from drink_partners.extensions.authentication.static import (
StaticAuthenticationBackend
)
class TestStaticAuthentication:
@pytest.fixture
def backend(self):
return StaticAuthenticationBackend.create()
async def test_respects_the_token_from_querystring_param(
self,
... | python |
from tracrpc.api import *
from tracrpc.web_ui import *
from tracrpc.ticket import *
from tracrpc.wiki import *
from tracrpc.search import *
| python |
import sys
import azure
import socket
from azure.servicebus import (
_service_bus_error_handler
)
from azure.servicebus.servicebusservice import (
ServiceBusService,
ServiceBusSASAuthentication
)
#from azure.http import (
# HTTPRequest,
# HTTPError
# )
#from azure.http.httpclient impo... | python |
#función para leer el archivo txt que contiene el mensaje encriptado
# el archivo se llama mensaje_cifrado_grupo1.txt
def txt_a_mensaje(): # funcion 7
return # se devuelve el mensaje en string | python |
from django.urls import path
from .views import Notifier
urlpatterns = [
path('get/<int:pk>', Notifier.as_view()),
path('get', Notifier.as_view()),
]
| python |
# built-in
from argparse import ArgumentParser
from pathlib import Path
from shutil import rmtree
# app
from ..actions import format_size, get_path_size
from ..config import builders
from .base import BaseCommand
class SelfUncacheCommand(BaseCommand):
"""Remove dephell cache.
"""
@staticmethod
def bu... | python |
from distutils.core import setup
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name = 'EssentialCV',
packages = ['EssentialCV'],
version = '0.26',
licen... | python |
import numpy as np
def wPrefersM1OverM(prefer, w, m, m1):
for i in range(N):
if (prefer[w][i] == m1):
return True
if (prefer[w][i] == m):
return False
def stableMarriage(prefer):
wPartner = [-1 for i in range(N)]
mFree = [False for i in range(N)]
... | python |
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
##############################################################################
#
# PURPOSE:
# Helper library used by the MRE internal lambda functions to interact with
# the control plane
#
################... | python |
##########################################################################
# MediPy - Copyright (C) Universite de Strasbourg
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for de... | python |
def count(a, b, c):
if not a and not b and not c:
return '1'
sum = 2 * a + 3 * b + 4 * c
cnt = a + b + c
l = 0
r = cnt + 1
while l < r:
m = (l + r) // 2
if (sum + 5 * m) / (cnt + m) < 3.5:
l = m + 1
else:
r = m
# так и не понял, почему... | python |
import logging
import sqlite3
import os
import datetime
from resources.cloud.clouds import Cloud, Clouds
from resources.cluster.database import Database
from lib.util import read_path, Command, RemoteCommand, check_port_status
LOG = logging.getLogger(__name__)
class Cluster(object):
"""Cluster class represents... | python |
"""
Tema: Assertions y Test suites
Curso: Selenium con python.
Plataforma: Platzi.
Profesor: Hector Vega.
Alumno: @edinsonrequena.
"""
# Unittest Modules
import unittest
# Selenium Modules
from selenium import webdriver
class SearchTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.d... | python |
try:
import greenlet
except ImportError:
greenlet_available = False
else:
greenlet_available = True
is_patched = False
from weakref import WeakSet
orig_greenlet = greenlet.greenlet
greenlets = WeakSet()
class PatchedGreenlet(orig_greenlet):
def __init__(self, *a, **k):
... | python |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import os
import requests
import pymysql
class WorkPipeline(object):
def process_item(self, item, spider):
return ... | python |
"""
Application ID: 512001308941.
Публичный ключ приложения: COAKPIKGDIHBABABA.
Секретный ключ приложения: 95C3FB547F430B544E82D448.
Вечный session_key:tkn14YgWQ279xMzvjdfJtJuRajPvJtttKSCdawotwIt7ECm6L0PzFZLqwEpBQVe3xGYr7
Session_secret_key:b2208fc58999b290093183f6fdfa6804
""" | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import pytest
from case import skip
@skip.if_pypy()
@skip.unless_module('boto3')
@skip.unless_module('pycurl')
@pytest.mark.usefixtures('hub')
class AWSCase(object):
pass
| python |
"""
Loaders for classic datasets.
"""
from .datasets import Ionosphere, MagicGammaTelescope
__all__ = ["Ionosphere", "MagicGammaTelescope"]
| python |
count = 0
for i in range(10):
nums = int(input())
if nums == 5:
count += 1
print(count)
| python |
import unittest
import logging
import os
import numpy as np
import pandas as pd
import scipy.stats as stats
import broadinstitute_psp.utils.setup_logger as setup_logger
import cmapPy.pandasGEXpress.parse as parse
import cmapPy.pandasGEXpress.GCToo as GCToo
import sip
# Setup logger
logger = logging.getLogger(setup_lo... | python |
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import plotly.graph_objects as go
from main import get_path_distance
# drop down list for use in airport codes
from controls import CI... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from unittest import TestCase
from eve.exceptions import ConfigException
from sqlalchemy import Boolean, Column, ForeignKey, Integer, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from eve_sqlalche... | python |
# -*- coding: utf-8 -*-
from .handler_class import handler_class
import urllib3
import requests
import json
import time
class http_handler_class(handler_class):
def __init__(self, *args, **kwargs):
# verify required input parameters
required_args = ['url']
for param_name in required_args:
... | python |
from setuptools import find_packages, setup
from netbox_nagios.version import VERSION
setup(
name="netbox-nagios",
version=VERSION,
author="Gabriel KAHLOUCHE",
author_email="gabriel.kahlouche@groupama.com",
description="Netbox Plugin to show centreon device state in Netbox.",
url="https://gith... | python |
from django.db import models
from django.utils.translation import gettext_lazy
from cradmin_legacy.superuserui.views import mixins
from cradmin_legacy.viewhelpers import listbuilder
from cradmin_legacy.viewhelpers import listbuilderview
from cradmin_legacy.viewhelpers import listfilter
from cradmin_legacy.viewhelpers ... | python |
#!/home/schamblee/projects/django-oidc-provider/project_env/bin/python3
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| python |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright (c) Megvii, Inc. and its affiliates.
import os
from yolox.exp import Exp as MyExp
class Exp(MyExp):
def __init__(self):
super(Exp, self).__init__()
#### s
self.depth = 0.33
self.width = 0.50
# #### m
# self... | python |
#!/usr/bin/env python3
""" Update Rancher app answers using API """
import os
import requests
class RancherAPI: # pylint: disable=too-few-public-methods
""" Make calls to Rancher API """
_CALLER = {
'GET': requests.get,
'PUT': requests.put,
'POST': requests.post,
}
def __ini... | python |
from __future__ import absolute_import
__author__ = 'katharine'
from enum import IntEnum
from .base import PebblePacket
from .base.types import *
__all__ = ["MusicControlPlayPause", "MusicControlPause", "MusicControlPlay", "MusicControlNextTrack",
"MusicControlPreviousTrack", "MusicControlVolumeUp", "Musi... | python |
# Authors: Sylvain MARIE <sylvain.marie@se.com>
# + All contributors to <https://github.com/smarie/python-pytest-cases>
#
# License: 3-clause BSD, <https://github.com/smarie/python-pytest-cases/blob/master/LICENSE>
from .common_pytest_lazy_values import lazy_value, is_lazy
from .common_others import unfold_exp... | python |
#!/usr/bin/python
'''
(C) Copyright 2020 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 ... | python |
# -*- coding: utf-8 -*-
ZFILL = 3
| python |
"""Config flow for DSMR integration."""
import logging
from typing import Any, Dict, Optional
from homeassistant import config_entries
from homeassistant.const import CONF_HOST, CONF_PORT
from .const import DOMAIN # pylint:disable=unused-import
_LOGGER = logging.getLogger(__name__)
class DSMRFlowHandler(config_en... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Card',
fields=[
('id', models.AutoField(verbose... | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2020 Kumagai group.
import os
from pathlib import Path
from monty.serialization import loadfn
from pydefect.analyzer.calc_results import CalcResults
from pydefect.analyzer.grids import Grids
from pydefect.analyzer.refine_defect_structure import refine_defect_structure
from pyde... | python |
"""
These constants provide well-known strings that are used for identifiers,
etc... for widgets that are commonly sub-classed by Manager implementations.
"""
kUIIdBase = "uk.co.foundry.asset.api.ui."
kParameterDelegateId = kUIIdBase + "parameterdelegate"
kParameterDelegateName = "Asset Parameter UI"
kInfoWidgetId... | python |
import matplotlib.pyplot as plt
def plot_creater(history,bin, modelname):
"""[For the training progress, a chart about the accuracy / loss is created for the deep learning approaches and stored accordingly]
Args:
history (keras.callbacks.History object): [Contains values accuracy, validation-accuracy, ... | python |
import GrossSalary, SalaryDeductions, NetSalary
print("Salary Computation App")
while True:
action = str(input("\nWould you like to to do? \n[A] Calculate Salary\n[B] Exit Application")).lower()
if(action == 'a'):
try:
name = str(input("\nEnter Name: "))
rendered_hours = float(... | python |
from src.libs.CrabadaWeb2Client.CrabadaWeb2Client import CrabadaWeb2Client
from pprint import pprint
from src.libs.CrabadaWeb2Client.types import CrabForLending
# VARS
client = CrabadaWeb2Client()
# TEST FUNCTIONS
def test() -> None:
pprint(client.getCheapestCrabForLending())
# EXECUTE
test()
| python |
# coding: utf-8
import requests
from bs4 import BeautifulSoup
import re
import json
import os
from xml.etree import ElementTree
import time
import io
import pandas as pd
from gotoeat_map.module import getLatLng, checkRemovedMerchant
def main():
merchantFilePath = os.path.dirname(
os.path.abspath(__file__)... | python |
#!/usr/bin/env python
# coding: utf-8
# ## Full Run
# In[1]:
import os
# In[2]:
Xtrain_dir = 'solar/data/kaggle_solar/train/'
Xtest_dir = 'solar/data/kaggle_solar/test'
ytrain_file = 'solar/data/kaggle_solar/train.csv'
station_file = 'solar/data/kaggle_solar/station_info.csv'
import solar.wrangle.wrangle
import so... | python |
from typing import Tuple, AnyStr
from lib.ui import BasePage
from lib.log import Loggers
from utils.Files import read_page_elements
log = Loggers(__name__)
class Baidu(BasePage):
def open_index(self):
self.get_url("https://www.baidu.com")
def login(self, locator: Tuple[AnyStr]):
self.click... | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 10:22:30 2020
@author: NN133
"""
import sys
import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
sys.path.append("C:/Users/NN133/Documents/libsvm-3.22/python")
from svmutil import *
#%matplotlib inline
from util_ker import *
#Import data... | python |
# meta class 에서는 __init__ 보다는 __new__ 를 사용합니다.
# 사용법은 아래와 같습니다.
# __new__ (<클래스자신>, <클래스명>, (클래스의 부모 클래스), {클래스의 어트리뷰트 딕셔너리} )
# __new__ 가 실행된 다음에 __init__ 가 실행되게 됩니다.
class Meta(type):
def __new__(cls, name, bases, attrs):
print("__new__ 메서드!")
print(cls, name, bases, attrs)
return type.__... | python |
default_app_config = 'action_notifications.apps.ActionNotificationsConfig'
| python |
from __future__ import division, unicode_literals
import codecs
from bs4 import BeautifulSoup
import urllib
from logzero import logger as LOGGER
import re
import codecs
from w3lib.html import replace_entities
import os
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from PIL import... | python |
from setuptools import setup, find_packages
with open("README.md") as f:
long_description = f.read()
setup(
name="BindsNET",
version="0.2.9",
description="Spiking neural networks for ML in Python",
license="AGPL-3.0",
long_description=long_description,
long_description_content_type="text/m... | python |
class Queue(object):
def __init__(self, queue):
self._queue = queue
self.name = None
def delete(self):
raise NotImplementedError()
class BrokerBackend(object):
def __init__(self):
self._queues = None
@property
def queues(self):
if self._queues is None:
... | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.keras.layers as tfkl
from veqtor_keras.util import localized_attention
class LocalizedAttentionLayer1D(tfkl.Layer):
def __init__(self,
patch_size=3,
n... | python |
"""
https://adventofcode.com/2018/day/2
"""
from collections import Counter
from itertools import product
from pathlib import Path
def solve_a(codes):
pairs = triplets = 0
for code in codes:
occurrences = Counter(code).values()
pairs += any(count == 2 for count in occurrences)
triplet... | python |
import hashlib
def hash_uid(uid, truncate=6):
"""Hash a UID and truncate it
Args:
uid (str): The UID to hash
truncate (int, optional): The number of the leading characters to keep. Defaults to 6.
Returns:
str: The hashed and trucated UID
"""
hash_sha = hashlib.sha256()
... | python |
from lib.interface import *
from lib.arquivo import *
from time import sleep
arq = './Ex115/cadastro.txt'
if not arquivoExiste(arq):
criarArquivo(arq)
while True:
cor(2)
opcao = menu(['Cadastrar', 'Listar', 'Sair'])
if opcao == 1:
#Opção para cadastrar uma nova pessoa no arquivo
cabec... | python |
from datetime import datetime
import json
import platform
import socket
import sys
from collections.abc import Iterable
import os
import inspect
import types
import pickle
import base64
import re
import subprocess
import io
import threading
import signal
try:
import pkg_resources
except ImportError:
pkg_resourc... | python |
import logging
from tqdm import tqdm
import tmdb
from page import blocked_qids
from sparql import sparql
def main():
"""
Find Wikidata items that are missing a TMDb TV series ID (P4983) but have a
IMDb ID (P345) or TheTVDB.com series ID (P4835). Attempt to look up the
TV show via the TMDb API. If th... | python |
import sys
sum = 0
for i in range(1, len(sys.argv), 1):
sum += int(sys.argv[i])
print(sum) | python |
from .normalize import *
from .logarithmic import *
from .exponential import *
from .gamma import *
from .tumblin import *
from .reinhard import *
from .durand import *
from .drago import *
from .fattal import *
from .lischinski import *
| python |
__author__ = 'xf'
| python |
# -*- coding: utf-8 -*-
import pytest
from django.conf import settings
from django.http import HttpResponse
from mock import Mock, PropertyMock, patch
from django_toolkit import middlewares
@pytest.fixture
def http_request(rf):
return rf.get('/')
@pytest.fixture
def http_response():
return HttpResponse()
... | python |
__version__ = 0.6 | python |
import boto3
import json
import string
from time import asctime
from urllib.request import Request, urlopen
import yaml
def get_API_key() -> None:
"""Grab QnAMaker API key from encrypted s3 object.
"""
s3_client = boto3.client('s3')
response = s3_client.get_object(
Bucket='octochat-processor',... | python |
import warnings
from collections import Counter
from itertools import chain
from typing import Tuple, Type
import strawberry
def merge_types(name: str, types: Tuple[Type]) -> Type:
"""Merge multiple Strawberry types into one
For example, given two queries `A` and `B`, one can merge them into a
super typ... | python |
#!/usr/bin/env python3
from matplotlib import pyplot as plt
import numpy as np
with plt.xkcd():
# Based on "Stove Ownership" from XKCD by Randall Munroe
# https://xkcd.com/418/
fig = plt.figure(figsize=(6,4))
ax = fig.add_axes((0.1, 0.2, 0.8, 0.7))
ax.set_xticks([])
ax.set_yticks([])
# a... | python |
import collections
import itertools
import json
import os
import operator
import attr
import torch
import torchtext
import numpy as np
from seq2struct.models import abstract_preproc
try:
from seq2struct.models import lstm
except ImportError:
pass
from seq2struct.models import spider_enc_modules
from seq2struc... | python |
import logging
import numpy as np
from rasterio.dtypes import dtype_ranges
import warnings
logger = logging.getLogger(__name__)
def execute(
mp,
resampling="nearest",
band_indexes=None,
td_matching_method="gdal",
td_matching_max_zoom=None,
td_matching_precision=8,
td_fallback_to_higher_zo... | python |
from Classes.Wrappers.PlayerDisplayData import PlayerDisplayData
class BattleLogPlayerEntry:
def encode(calling_instance, fields):
pass
def decode(calling_instance, fields):
fields["BattleLogEntry"] = {}
fields["BattleLogEntry"]["Unkown1"] = calling_instance.readVInt()
fields["... | python |
# coding: UTF-8
import numpy as np
import chainer
from chainer import Variable,Chain
import chainer.links as L
import chainer.functions as F
import chainer.optimizers as O
# model
class MyChain(Chain):
def __init__(self):
super().__init__(
l1 = L.Linear(1,2),
l2 = L.Linear(2,1),
... | python |
# -*- coding: utf-8 -*-
"""
Script Name:
Author: Do Trinh/Jimmy - 3D artist.
Description:
"""
# -------------------------------------------------------------------------------------------------------------
""" Import """
import argparse
from PLM.cores.Errors import VersionNotFoundException
from PLM ... | python |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# Huawei.VRP config normalizer
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# -------------------------------------------------... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.