text stringlengths 2 999k |
|---|
from typing import List, Optional
from os.path import join
from rastervision.pipeline.pipeline import Pipeline
from rastervision.pipeline.file_system import str_to_file, file_to_str
from rastervision.pipeline.pipeline_config import PipelineConfig
from rastervision.pipeline.config import register_config, Config
from ra... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 24 14:27:25 2021
@author: zongsing.huang
"""
import numpy as np
# dim size
D = 6
# method 1
RK1 = np.random.uniform(low=0, high=D, size=[D])
# method2
RK2 = [ np.random.uniform(low=i, high=i+1) for i in range(D)]
np.random.shuffle(RK2) |
class DownloadStringCompletedEventArgs(AsyncCompletedEventArgs):
""" Provides data for the System.Net.WebClient.DownloadStringCompleted event. """
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return DownloadStringCompletedEventArgs()
instance=ZZZ()
"""hardcoded/returns an instance of the clas... |
#!/usr/bin/env python
# encoding: utf-8
dict = {}
dict['cat'] = "This is a cat."
dict[2] = "This is a dog."
minidict = {'name': 'zhongwei', 'code': 56867, 'dept': 'gbs'}
print dict['cat']
print dict[2]
print minidict
print minidict.keys()
print minidict.values()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import urllib.request, urllib.parse, urllib.error
handle = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
counter = dict()
for line in handle:
line = line.decode().strip()
print(line)
words = line.split()
for word in words:
counter[word]... |
# coding: utf-8
# Author: Will
# Contributor: 阿财(Rgveda@github)(11652964@qq.com)
# Created date: 2018-06-08
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2018 yutiansut/QUANTAXIS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (th... |
#!/usr/bin/env python
# encoding: utf-8
# n.b. we can't have unicode_literals here due to http://bugs.python.org/setuptools/issue152
from __future__ import absolute_import, division, print_function
try:
from setuptools import setup
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
... |
import numpy as np
import cv2 as cv
import cmath
#cap = cv.VideoCapture(0)
cap = cv.VideoCapture('udpsrc port=5004 ! application/x-rtp,encoding-name=H264,payload=96 ! rtph264depay ! avdec_h264 ! videoconvert ! appsink', cv.CAP_GSTREAMER)
PI = 3.14159
while(1):
# read the video capture frame
_, frame... |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 13 10:50:55 2021
@author: marti
"""
if __name__ == '__main__':
import os, sys
depth = 1
root_folder = os.path.realpath(os.path.join(__file__,'../' * (1+depth)))
os.chdir(root_folder)
sys.path.append(root_folder)
from jumpflood.helpers import (init... |
"""Changes tablename blog to blogs
Revision ID: 763b085736ad
Revises: 5a8e4632f6d1
Create Date: 2020-05-09 22:10:15.992648
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '763b085736ad'
down_revision = '5a8e4632f6d1'
branch_labels = None
depends_on = None
def... |
class Solution(object):
def searchLeftMost(self, nums, target):
# init with len, instead of len - 1, to handle corner case or one-element array
l, r = 0, len(nums)
while l != r:
m = (l + r) // 2
if nums[m] >= target:
r = m
else:
... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import utils
from operators.argo_gitops_operator import ArgoGitopsOperator
from operators.flux_gitops_operator import FluxGitopsOperator
from operators.gitops_operator import GitopsOperatorInterface
FLUX_TYPE = "FLUX"
ARGOCD_TYPE = "ARGOCD"
cl... |
from typing import Optional, Any
from functools import reduce
from pyscf import __config__
from pyscf.cc import ccsd
from pyscf.mp.mp2 import _mo_without_core
from pyscfad import lib
from pyscfad.lib import numpy as jnp
from pyscfad.gto import mole
from pyscfad.scf import hf
def amplitudes_to_vector(t1, t2, out=None):... |
#!/usr/bin/python
import MySQLdb
import sys
import random
import string
import time
import re
# Or "/usr/share/dict/words" if you prefer it
WORDS_FILE = "/usr/share/dict/cracklib-small"
with open(WORDS_FILE, "r") as __fp:
__all_words = __fp.readlines()
__all_words = [__x.strip() for __x in __all_words]
def phra... |
# Generated by Django 3.0.6 on 2020-05-11 11:20
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Category",
fields=[
(
"id",
... |
class Config:
"""
General configuration parent class
"""
MOVIE_API_BASE_URL ='https://api.themoviedb.org/3/movie/{}?api_key={}'
class ProdConfig(Config):
"""
Production configuration child class
Args:
Config: The pareny configuration class with General configuration settings
... |
import logging
import os
import sentry_sdk
from nltk.tokenize import sent_tokenize
import common.dialogflow_framework.utils.state as state_utils
import common.gaming as common_gaming
from dialogflows.common import game_info
from dialogflows.common.game_info import search_igdb_game_description_by_user_and_bot_phrases... |
# Copyright (C) 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 law or agreed to in wri... |
import math
import numpy as np
from numba import float64, int64
from numba import njit
from numba.experimental import jitclass
from tardis.montecarlo.montecarlo_numba import njit_dict_no_parallel
from tardis.montecarlo import (
montecarlo_configuration as montecarlo_configuration,
)
from tardis.montecarlo.montec... |
from unittest.mock import Mock
from weaverbird.backends.pandas_executor.steps.domain import execute_domain
from weaverbird.pipeline.steps.domain import DomainStep
def test_retrieve_domain():
domain_retriever_mock = Mock(return_value='sample_dataframe')
step = DomainStep(name='domain', domain='kalimdor')
... |
# -*- coding: utf-8 -*-
# import cvxpy as cvx
from typing import Optional, Tuple, Union
import numpy as np
from lmi_solver.lmi0_oracle import lmi0_oracle
from lmi_solver.lmi_oracle import lmi_oracle
Arr = Union[np.ndarray]
Cut = Tuple[Arr, float]
class mle_oracle:
def __init__(self, Sig: Arr, Y: Arr):
"... |
#!/usr/bin/python2.4
#
# Copyright 2008 Google Inc.
#
# 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 o... |
import matplotlib.cm as cm
import matplotlib.pyplot as plt
d_pop = {}
with open("population.csv") as f:
for line in f:
code, _, pop = line.split(",")
d_pop[int(code)] = int(pop)
data = []
with open("position.csv") as f:
for line in f:
a = line.strip().split(",")
if len(a) < 4:... |
import pytest
from dagster import execute_solid
from .inputs import sort_by_calories
@pytest.mark.xfail
def test_sort_by_calories():
res = execute_solid(
sort_by_calories,
input_values={
'cereals': [
{'name': 'just_lard', 'calories': '1100'},
{'name': ... |
# -*- coding: utf-8 -*-
# This file was generated
import nidigital._visatype as _visatype
import nidigital.errors as errors
import array
import collections
import hightime
import numbers
from functools import singledispatch
@singledispatch
def _convert_repeated_capabilities(arg, prefix): # noqa: F811
'''Base v... |
#!/usr/bin/env python3 -u
# -*- coding: utf-8 -*-
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
__author__ = ["Markus Löning"]
__all__ = ["TransformedTargetForecaster"]
from sklearn.base import clone
from sktime.base import _HeterogenousMetaEstimator
from sktime.forecasting.base._base impor... |
import numpy as np
import random
from scipy.linalg import block_diag
import torch
import torch.nn as nn
import torch.nn.functional as F
from .. import BaseModel, register_model
from .gin import split_dataset_general
from .graphsage import GraphSAGELayer
class EntropyLoss(nn.Module):
# Return Scalar
def forw... |
import os
import re
from time import sleep
import pytest
from test import test_utils
from test.test_utils.ec2 import get_ec2_instance_type
from test.dlc_tests.conftest import LOGGER
TENSORFLOW1_VERSION = "1."
TENSORFLOW2_VERSION = "2."
# TODO: Set enable_p3dn=True when releasing
TF_EC2_GPU_INSTANCE_TYPE = get_ec2_... |
import binascii
import os
from io import BytesIO
from typing import TYPE_CHECKING, Any, Callable, Collection, Dict, Optional, Type
import attr
import yaml
from typing_extensions import Protocol, runtime_checkable
from .utils import is_json_media_type, is_plain_text_media_type
if TYPE_CHECKING:
from .models impor... |
#!/usr/bin/env python3
# Copyright (C) 2016 Intel Corporation
# Released under the MIT license (see COPYING.MIT)
import signal
import unittest
from common import setup_sys_path, TestBase
setup_sys_path()
from oeqa.core.exception import OEQADependency
from oeqa.core.utils.test import getCaseMethod, getSuiteCasesName... |
"""
Solution to https://adventofcode.com/2020/day/9
"""
def read_input():
with open("./input.txt", mode="r") as file_pointer:
return tuple(int(line.strip()) for line in file_pointer.readlines())
def walk(encrypted_data, preamble=25):
for pos, data_point in enumerate(encrypted_data[preamble:]):
... |
import sys
print("Exiting...")
sys.exit()
print("This will not show!") |
class Node():
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList():
def __init__(self):
self.head = None
def insert_at_beginning(self, data):
node = Node(data = data, next = self.head)
self.head = node
... |
from __future__ import division, print_function, absolute_import
import warnings
import numpy as np
from numpy.testing import TestCase, assert_array_almost_equal, \
assert_array_equal, assert_raises, assert_equal, assert_, \
run_module_suite
from scipy.signal import tf2zpk, zpk2tf, BadCoefficients, f... |
# Copyright (c) 2017 nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/vulnerablecode/
# The VulnerableCode software is licensed under the Apache License version 2.0.
# Data generated with VulnerableCode require an acknowledgment.
#
# You may not use this software except in compli... |
import datetime
def DateTimeNow():
return datetime.date.today()
def DateTime1WeekAgo():
return DateTimeNow() - datetime.timedelta(7+1)
def DateTime2WeekAgo():
return DateTimeNow() - datetime.timedelta(14+1)
def DateTime4WeekAgo():
return DateTimeNow() - datetime.timedelta(28+1)
def DateTime26W... |
#!/usr/bin/env python3
import unittest
from typing import List, Tuple, Union, Any
import torch
from torch import Tensor
from torch.nn import Module
from captum.attr._core.layer.grad_cam import LayerGradCam
from ..helpers.basic_models import BasicModel_MultiLayer, BasicModel_ConvNet_One_Conv
from ..helpers.utils impo... |
import glob
from r0vert_panel.menu import Menu, MenuItem
class BatteryMenuItem(MenuItem):
def value_string(self):
return "%.2fV" % self.value
class Status(Menu):
def __init__(self):
super(Status, self).__init__("status", True)
self.battery1 = BatteryMenuItem("Bat1", 0.0)
sel... |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class VariantOnDependencyConditionRoot(Package):
"""Test that dependencies that are conditional on the state of
oth... |
from collections import deque, defaultdict
from functools import wraps
from types import GeneratorType
from typing import Callable
import numpy as np
import time
from ditk import logging
class StepTimer:
def __init__(self, print_per_step: int = 1, smooth_window: int = 10) -> None:
self.print_per_step = p... |
#!/usr/bin/env python3
# Copyright (c) 2015-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test p2p mempool message.
Test that nodes are disconnected if they send mempool messages when bloom
fi... |
from direct.showbase.ShowBase import ShowBase
from direct.actor.Actor import Camera, NodePath
from panda3d.core import GeomNode
from square import make_square, make_color_vertices
class ColorMaps(object):
def __init__(self):
self.base = ShowBase()
self.base.disableMouse()
self.base.camera.... |
# This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) Philippe Biondi <phil@secdev.org>
# This program is published under a GPLv2 license
"""
Wrap Scapy's shell in pyannotate.
"""
import os
import sys
sys.path.insert(0, os.path.abspath('../../'))
from pyannotate... |
#!/home/dk/Desktop/ip/instagram/virtual/bin/python
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# 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 requir... |
print('=-'*50)
print('-----------\033[33mLEITOR DE NÚMEROS INTEIROS:\033[m------------')
print('O PROGRAMA VAI SOMAR TODOS OS NÚMEROS DIGITADOS E SÓ VAI PARAR QUANDO O USUÁRIO DIGITAR O VALOR 999.')
print('=-'*50)
n = 0
soma = 0
cont = -1
while n != 999:
soma = soma + n
cont = cont + 1
n = int(input('Digite... |
# -*- coding: utf-8 -*-
"""
@FileName : dataset.py
@Description : 数据集类,仿照Tensorflow功能编写
@Author : 齐鲁桐
@Email : qilutong@yahoo.com
@Time : 2019-05-28 15:11
@Modify : None
"""
from __future__ import absolute_import, division, print_function
import numpy as np
import fairy.tail as ft
from .rin... |
#!/usr/bin/env python3
# Copyright (c) 2014-2019 Joergen Ibsen
#
# 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, ... |
import yagmail
import os
import datetime
date = datetime.date.today().strftime("%B %d, %Y")
path = 'Attendance'
os.chdir(path)
files = sorted(os.listdir(os.getcwd()), key=os.path.getmtime)
newest = files[-1]
filename = newest
sub = "Attendance Report for " + str(date)
# mail information
yag = yagmail.SMTP("youremail@em... |
# qubit number=4
# total number=29
import cirq
import qiskit
from qiskit.providers.aer import QasmSimulator
from qiskit.test.mock import FakeVigo
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import ... |
#!/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__()
self.depth = 0.33
self.width = 0.375
self.input_scale = (416, 416)
... |
import csv
import errno
import hashlib
import logging
import os
import sys
import tarfile
import threading
import zipfile
from queue import Queue
import torch
import urllib
from torch.utils.data import Dataset
from torch.utils.model_zoo import tqdm
def unicode_csv_reader(unicode_csv_data, **kwargs):
r"""Since th... |
"""
Contains plotters for various types of datasets which require special plotting requirements.
"""
from matplotlib.figure import Figure
import sys, pathlib
from sugarplot import normalize_pandas, prettifyPlot, ureg, plt, weibull, fit_weibull, \
fit_lia, fit_impedance, cmap
from sciparse import to_standard_qu... |
"""
Examples will be published soon ...
"""
|
from django.contrib import admin
from profiles_api import models
# Register your models here.
admin.site.register(models.UserProfile)
admin.site.register(models.ProfileFeedItem)
|
import tensorflow as tf
import tf_slim as slim
def head(endpoints, embedding_dim, is_training):
endpoints['head_output'] = slim.fully_connected(
endpoints['model_output'], 1024, normalizer_fn=slim.batch_norm,
normalizer_params={
'decay': 0.9,
'epsilon': 1e-5,
'sc... |
from flask import Flask, render_template
from flask.ext.responses import json_response, xml_response, auto_response
import RPi.GPIO as GPIO
app = Flask(__name__)
@app.route(“/toggle”, methods=[‘POST’])
def togle():
GPIO.setmode(GPIO.BOARD) ## Use board pin numbering
GPIO.setup(7, GPIO.OUT) ## Setup GPIO Pin 7 to ... |
"""
Provide django models to back the discussions app
"""
from __future__ import annotations
import logging
from enum import Enum
from collections import namedtuple
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import uge... |
#
# Copyright (c) Pret-a-3D/Paolo Ciccone. All rights reserved.
# Modified by Fuzzy70/Lee Furssedonn with kind permission from Paolo Ciccone
#
from Reality_services import *
from Reality import *
# To customize this script all you need to do is to
# change the following variable
Re_sIBL_Map = ":Runtime:Text... |
import http.client
conn = http.client.HTTPConnection("ec2-3-222-208-106.compute-1.amazonaws.com:8086")
payload = "{\"exchange\":\"kraken\",\"key\":\"1aa5695d-4b8d-4aeb-8312-8a97d2119764\",\"secret\":\"1aa5695d-4b8d-4aeb-8312-8a97d2119764\",\"passphrase\":\"SECRET PHRASE\",\"activated\":true,\"allocation\":\"TIER4\"}"... |
import os, signal, subprocess, sys, threading
def isint(s):
'''
Check if a string represents an int.
Note: Numbers in scientific notation (e.g., 1e3) are floats in Python,
and `isint('1e3')` will return False.
Source: https://stackoverflow.com/a/1265696
'''
if len(s) < 1:
retu... |
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField
from wtforms.validators import DataRequired, Length
# Create a student sign-in form class
class StudentSignInForm(FlaskForm):
# Form fields with validators
student_name = StringField('Student Name', validators=[
D... |
# -*- coding: utf-8 -*-
'''
Interface to Red Hat tuned-adm module
:maintainer: Syed Ali <alicsyed@gmail.com>
:maturity: new
:depends: cmd.run
:platform: Linux
'''
# Import Python libs
from __future__ import absolute_import
# Import Salt libs
import salt.exceptions
def profile(name):
'''
... |
#!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Copyright (c) 2017-2018 The Mynt Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the SegWit changeover logic."""
from test_framework... |
from __future__ import absolute_import
import mock
import os
import pytest
import signal
import urllib
from datetime import datetime
from django.conf import settings
from selenium import webdriver
def pytest_configure(config):
# HACK: Only needed for testing!
os.environ.setdefault('_SENTRY_SKIP_CONFIGURATIO... |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distr... |
# -*- coding: utf-8 -*-
# flake8: noqa
import logging
import utool as ut
(print, rrr, profile) = ut.inject2(__name__)
logger = logging.getLogger('wbia')
def load_multiclass_scores(self):
# convert simple scores to multiclass scores
import vtool as vt
self.multiclass_scores = {}
for key in self.sampl... |
"""
Guided image optimization
=========================
This example showcases how a guided, i.e. regionally constraint, NST can be performed
in ``pystiche``.
Usually, the ``style_loss`` discards spatial information since the style elements
should be able to be synthesized regardless of their position in the
``style_... |
## \file Calculations.py
# \author Nikitha Krithnan and W. Spencer Smith
# \brief Provides functions for calculating the outputs
import math
import Interpolation
## \brief Calculates stress distribution factor (Function) based on Pbtol
# \param inParams structure holding the input values
# \return stress distribution... |
# -*- coding: utf-8 -*-
#
# This class was auto-generated.
#
from onlinepayments.sdk.data_object import DataObject
from onlinepayments.sdk.domain.card_without_cvv import CardWithoutCvv
from onlinepayments.sdk.domain.external_token_linked import ExternalTokenLinked
class CreatedTokenResponse(DataObject):
__card = ... |
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
... |
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='page... |
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... |
import os
import time
from os.path import join, dirname
import json
import requests
import discord
from discord.ext import tasks
from discord.ext import commands as dcmd
from dotenv import load_dotenv
import firebolt
from itertools import cycle
from flask import Flask
from threading import Thread
app = Flask('')
@... |
# coding: utf-8
"""
Wavefront REST API
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST ... |
#!/usr/bin/env python2
# Copyright (c) 2014-2016, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
import argparse
import ctypes
import platform
class c_cudaDeviceProp(ctypes.Structure):
"""
Passed to cudart.cudaGetDeviceProperties()
"""
_fields_ = [
('name', c... |
import os
from os import path
from executor import execute
ALL_SERVICES = 'all'
# env definition
class ENV:
DEV = 'dev'
PROD = 'prod'
@staticmethod
def allEnvs():
return [ENV.DEV, ENV.PROD]
@staticmethod
def valid(env):
return env in ENV.allEnvs()
# action definition
class... |
#!/usr/bin/env python
"""
Example of a self-updating pure Python module with no external dependencies.
"""
# MANAGED BY AUTO-UPDATE PROCESS: imports
from __future__ import print_function
from argparse import ArgumentParser
import re
from os import path
try:
from urllib.request import urlopen
except ImportError:
... |
import json
import os
import shutil
import sys
import tempfile
import unittest
from unittest import TestCase
from unittest.mock import patch
import numpy as np
from datasets import Dataset
import faiss
from transformers.configuration_bart import BartConfig
from transformers.configuration_dpr import DPRConfig
from tra... |
import requests, re
from bs4 import BeautifulSoup
from collections import OrderedDict
headers = {
'Referer': 'http://stdweb2.korean.go.kr/search/List_dic.jsp',
'Content-Type': 'application/x-www-form-urlencoded'
}
r = requests.post('http://stdweb2.korean.go.kr/search/List_dic.jsp',
headers=headers, data='''idx=&... |
usuario = input ("Digite seu usuário : ")
qtd_caracteres = len(usuario)
print(usuario,qtd_caracteres,type(qtd_caracteres))
n1 = input("Digite alguma coisa: ")
n2 = input("Digite outra coisa: ")
print(f"O total de caracteres digitados foi {len(n1)+len(n2)} ")
|
import asynctest
from asynctest.mock import patch
class TestHelloWorld(asynctest.TestCase):
def setUp(self):
patcher1 = patch('charlesbot_hello_world.helloworld.HelloWorld.load_config') # NOQA
self.addCleanup(patcher1.stop)
self.mock_load_config = patcher1.start()
from charlesbo... |
# Copyright 2021 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/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... |
import tensorflow.examples.tutorials.mnist.input_data as input_data
import tensorflow as tf
import config as cfg
import os
import lenet
from lenet import Lenet
def main():
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
sess = tf.Session()
batch_size = cfg.BATCH_SIZE
parameter_path = cf... |
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
number = x ^ y
bitCount = 0
while number != 0:
bitCount += number & 1
number = number >> 1
return bitCount
|
"""The tests for numeric state automation."""
import unittest
from homeassistant.bootstrap import _setup_component
import homeassistant.components.automation as automation
from tests.common import get_test_home_assistant
class TestAutomationNumericState(unittest.TestCase):
"""Test the event automation."""
... |
"""
Fatture in Cloud API v2 - API Reference
Connect your software with Fatture in Cloud, the invoicing platform chosen by more than 400.000 businesses in Italy. The Fatture in Cloud API is based on REST, and makes possible to interact with the user related data prior authorization via OAuth2 protocol. # noq... |
"""Support for controlling GPIO pins of a Beaglebone Black."""
from Adafruit_BBIO import GPIO # pylint: disable=import-error
from homeassistant.const import EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP
DOMAIN = "bbb_gpio"
def setup(hass, config):
"""Set up the BeagleBone Black GPIO component."""
de... |
from pyccel.decorators import types
#==============================================================================
@types('double[:]','int','double')
def find_span( knots, degree, x ):
"""
Determine the knot span index at location x, given the
B-Splines' knot sequence and polynomial degree. See
Algori... |
import unittest
import sys
import subprocess
import time
class FormattedTestRunner:
def __init__(self, stream=sys.stderr):
self.stream = stream
def writeUpdate(self, message):
self.stream.write(message)
def run(self, test):
"Run the given test case or test suite."
result ... |
data = """0
1
0
0
1
-3
0
0
2
-2
-6
-3
2
-5
-6
-3
-3
0
-8
-12
1
-9
-12
-9
0
-7
-17
-6
-18
-7
-6
-21
-28
-14
-23
-14
-17
-5
-35
-17
-26
-14
1
-27
-19
-40
-32
-44
2
-14
-15
-12
-35
0
-49
-12
-7
-46
-47
-32
-33
-47
-7
-62
-20
-35
-4
-35
-8
-3
-61
-38
-63
-27
-33
-57
-48
-66
-68
-11
-61
-50
-34
-31
-36
-79
-49
-71
1
-34
-65... |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from datetime import date, datetime, time
import pytest
from dateutil.relativedelta import relativedelta
... |
import unittest
from card.utils import CardUtils
class TestCardUtils(unittest.TestCase):
def test_make_key(self):
cases = {
'': '',
'Mountain': 'mountain',
'The Rack': 'therack',
'Ætherling': 'aetherling',
'“Ach! Hans, Run!”': 'achhansrun',
... |
from flask import Blueprint, send_file
from flask_rest_jsonapi import Api
import io
from commandment.inventory.models import db, InstalledCertificate
from commandment.inventory.resources import InstalledApplicationsList, InstalledApplicationDetail, \
InstalledCertificatesList, InstalledCertificateDetail, Installed... |
# Copyright 2021 Google LLC. All Rights Reserved.
#
# 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 o... |
# -*- coding: utf-8 -*-
import os
import glob
import math
import numpy as np
from .write_xml import *
import auto_pose.meshrenderer.meshrenderer as mr
import auto_pose.meshrenderer.meshrenderer_phong as mr_phong
import cv2
from .pysixd import view_sampler
from .pysixd import transform
class SceneRenderer(object):
... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *
class Bolt(CMakePackage):
"""BOLT targets a high-performing OpenMP implementation,
... |
import peewee
from model.base_model import BaseModel
class Query(BaseModel):
query_id = peewee.PrimaryKeyField()
name = peewee.CharField(unique=True)
query = peewee.CharField()
|
from __future__ import print_function
import time
from absl import app
from absl import flags
from multiprocessing import Process
import numpy as np
try:
from std_msgs.msg import Int64
except ModuleNotFoundError:
# ROS not installed
Int64 = int
from erdos.data_stream import DataStream
import erdos.graph
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.