text stringlengths 1 927k |
|---|
# https://www.hackerrank.com/challenges/30-loops/problem
#!/bin/python3
import math
import os
import random
import re
import sys
def printMultiples(number):
for i in range(1,11):
print(str(number)+" x "+str(i)+" = "+str(number*i))
if __name__ == '__main__':
n = int(input())
printMultiples(n) |
import claripy
import angr
class A:
n = 0
def do_vault_identity(v_factory):
v = v_factory()
v.uuid_dedup.add(A)
assert len(v.keys()) == 0
a = A()
b = A()
b.n = 1
c = A()
c.n = 2
aid = v.store(a)
assert len(v.keys()) == 1
bid = v.store(b)
assert len(v.keys()) == 2
cid = v.store(c)
assert len(v.keys())... |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pickle
class Line():
def __init__(self,n):
self.n=n
self.detected =False
#Polynomial coefficients of the lines
self.A=[]
self.B=[]
self.C=[]
#Running average of coefficients
self.A_avg=0.
self.B... |
#!/usr/bin/env python
# coding=utf-8
# (C) Copyright 2017 Hewlett Packard Enterprise Development LP
#
# 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... |
import json
import jydoop
import healthreportutils
setupjob = healthreportutils.setupjob
combine = jydoop.sumreducer
def map(key, value, context):
try:
payload = json.loads(value)
except:
context.write("Bogus\tBogus\tBogus\tBogus", 1)
return
output = []
try:
info = pa... |
from typing import Dict, Optional, Union
from uuid import uuid4
import webview
from kanmail.log import logger
from kanmail.server.app import server
from kanmail.settings.constants import DEBUG, FRAMELESS, IS_APP, SERVER_HOST, SESSION_TOKEN
ID_TO_WINDOW = {} # internal ID -> window object
UNIQUE_NAME_TO_ID = {} # n... |
"""
Common utilities to implement policy gradient algorithms
"""
from collections import namedtuple, deque
import numpy as np
from scipy import signal
from torchlib.dataset.utils import create_data_loader
from torchlib.deep_rl.utils.replay.replay import ReplayBuffer
from torchlib.deep_rl.utils.replay.sampler import S... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
OpenAPI spec version: v1.15.6
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import kube... |
''' Jogo Batalha Naval ''' |
from __future__ import unicode_literals
try:
from collections import OrderedDict
except ImportError:
from django.utils.datastructures import SortedDict as OrderedDict
from tablib import Dataset
class Error(object):
def __init__(self, error, traceback=None, row=None):
self.error = error
s... |
from django.db import IntegrityError
from django.test import TestCase
from ..models import Badge, Award
from .mixins import UserFixturesMixin
class BadgeTestCase(TestCase):
"""
Badge model test case.
"""
def test_autocreate_slug(self):
badge = Badge.objects.create(name='Super Chouette')
... |
import pytest
import textwrap
from ansible_builder.steps import AdditionalBuildSteps, PipSteps, BindepSteps
def test_steps_for_collection_dependencies():
assert list(PipSteps('requirements.txt')) == [
'ADD requirements.txt /build/',
'RUN pip3 install --upgrade -r /build/requirements.txt'
]
... |
#!/usr/bin/env python
"""
Download the latest heroicons zip file and select only the optimized icons.
"""
import argparse
import os
import sys
from io import BytesIO
from zipfile import ZIP_DEFLATED, ZipFile
import requests
def main(args=None):
parser = argparse.ArgumentParser()
parser.add_argument("version"... |
import binascii
import errno
import functools
import hashlib
import importlib
import logging
import multiprocessing
import os
import signal
import subprocess
import sys
import tempfile
import threading
import time
from typing import Optional, Sequence, Tuple, Any, Union, Dict
import uuid
import grpc
import warnings
tr... |
"""Tests for HomematicIP Cloud switch."""
from openpeerpower.components.homematicip_cloud import DOMAIN as HMIPC_DOMAIN
from openpeerpower.components.homematicip_cloud.generic_entity import (
ATTR_GROUP_MEMBER_UNREACHABLE,
)
from openpeerpower.components.switch import (
ATTR_CURRENT_POWER_W,
ATTR_TODAY_ENER... |
# Generated by Django 3.0.4 on 2020-03-26 11:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('base', '0011_auto_20200326_1107'),
]
operations = [
migrations.DeleteModel(
name='Questionnaire',
),
] |
# Run options
# gunicorn -w 4 -b 127.0.0.1:5000 main:app
# waitress main:app
# python3 main.py runserver
# uwsgi --http 0.0.0.0:8000 --home env --wsgi-file main.py --callable app --master --enable-threads --thunder-lock
# virtualenv -p /usr/local/bin/python3 env
# source env/bin/activate
# pip3 install --upg... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.21
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... |
from typing import Dict, Optional
from great_expectations.core import ExpectationConfiguration
from great_expectations.core.expectation_configuration import parse_result_format
from great_expectations.execution_engine import ExecutionEngine
from great_expectations.expectations.expectation import (
ColumnMapExpecta... |
from django.test import TestCase
from dojo.tools.acunetix.parser import AcunetixParser
from dojo.models import Test
class TestAcunetixParser(TestCase):
def test_parse_without_file(self):
parser = AcunetixParser()
findings = parser.get_findings(None, Test())
self.assertEqual(0, len(findings... |
from .custom_user import User |
# -*- coding: utf-8 -*-
from django import template
from django.template import Node, TemplateSyntaxError, Variable
from django.conf import settings
from django.utils.translation import ugettext as _
from ..generate import image_url as url
register = template.Library()
class AllImagesCheckPermissionForObjectsNode(N... |
"""Handle the EAP socket"""
from __future__ import absolute_import
import struct
from abc import ABC, abstractmethod
from fcntl import ioctl
import errno
import socket
from mac_address import MacAddress
from utils import get_logger, get_interface_mac
class PromiscuousSocket(ABC):
"""Abstract Raw Socket in Promi... |
""" In order to reuse and have a consistent set of arguments we use the
functions in this file to build argument parsers for all scripts.
TODO: change to class methods to common methods if there is no need to call
those functions outside an instance of OptionParser.
"""
from argparse import ArgumentPa... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from unittest.mock import patch, mock_open
from nose.tools import assert_equals
from django.test import TestCase
from vaas.configuration.loader import YamlConfigLoader
USER_HOME_PATH = '/user/path/.vaas'
VAAS_APP_RESOURCES_PATH = '/vaas... |
"""
WSGI config for djgumroad project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`... |
'''
Formula for area of circle
Area = pi * r^2
where pi is constant and r is the radius of the circle
'''
def findarea(r):
PI = 3.142
return PI * (r*r);
print("Area is %.6f" % findarea(5)); |
from .deseq2 import *
from .example import * |
class StructureSketch(object):
"""Create 'Sketch' of the structure"""
def __init__(self,structureModel,structureGeometry):
"""init
Required argument:
Optional arguments:
None.
Return value:
Exceptions:
None.
"""
self.structureGeomet... |
import codecs
from subprocess import call
import os
from collections import defaultdict
from marmot.features.feature_extractor import FeatureExtractor
from marmot.util.ngram_window_extractor import left_context, right_context
from marmot.experiment.import_utils import mk_tmp_dir
from marmot.exceptions.no_data_error im... |
# -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE... |
import os
import app
from termcolor import colored
from write import write
import re
from pathlib import Path
from template_handler import templates_lister
def template_registrator():
"""Get templateRegistrator module path and call template module and exporter functions
"""
module_path = f"{app.MODULE_FOLD... |
print("I am having a try.") |
"""
$Id$
This is a ISAPI extension for a wsgi with 2 handlers classes.
- ISAPISimpleHandler which creates a new IsapiWsgiHandler object for
each request.
- ISAPIThreadPoolHandler where the wsgi requests are run on worker threads
from the thread pool.
Dependecies:
- python 2.2+
- win32 ext... |
"""
Views for the media module.
"""
import functools
import json
from flask import session
from flask_socketio import disconnect, emit, join_room, leave_room
from flask_user import current_user
from flask_user.decorators import login_required
from backend import socketio
from backend.apps.chat.models import Message
... |
# coding: utf-8
# In[1]:
import os
import numpy as np
import tensorflow as tf
from tqdm import tqdm
from model import Model
from setting import batch_size, get_cached, idx2char, n_mels, reduction_factor, text2idx
# In[2]:
paths, lengths, texts = [], [], []
text_files = [f for f in os.listdir("spectrogram") if f... |
#!/usr/bin/env python
# -*- coding: Latin-1 -*-
"""
@file GenerateTaxiRoutesMain.py
@author Sascha Krieg
@author Daniel Krajzewicz
@author Michael Behrisch
@date 2008-04-17
@version $Id$
Main of GenerateTaxiRoutes.
SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/
Copyright (C) 2008-2017 DLR (http:... |
import logging
from dataclasses import asdict
from decimal import Decimal
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union
from urllib.parse import urljoin
import opentracing
import opentracing.tags
from django.core.exceptions import ValidationError
from prices import Money, TaxedMoney, Tax... |
import pandas as pd
from pathlib import Path
def df_to_csv(df, path):
df.to_csv(path, sep='\t', index=False, encoding='utf-8')
def csv_to_df(path):
df = pd.read_csv(path, sep='\t', dtype=str, encoding='utf-8')
return df
def max_arguments(task):
fp = open(task, 'r')
lines_args = fp.readlines()
... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import numpy as np
import torch
def get_mask_func(mask_type, which_dataset, rnl_params=None):
# Whether the number of lin... |
t = int(input())
# Python program to compute sum of pairwise bit differences
def sumBitDifferences(arr,n):
ans = 0 # Initialize result
# traverse over all bits
for i in range(0, 32):
# count number of elements with i'th bit set
count = 0
for j in range(0,n):
if... |
#
# __COPYRIGHT__
#
# 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,
# distribute, sublicen... |
import sys
major, minor, micro, releaselevel, serial = sys.version_info
if not (major == 2 and minor >= 5):
print("Python >=2.5 is required to use this module.")
sys.exit(1)
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import os.path
import logging
setup_dir = os.p... |
#!/usr/bin/env python3
# Copyright (c) 2014-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Helpful routines for regression testing."""
from base64 import b64encode
from binascii import hexlify,... |
import torch
import torch.nn as nn
from torch.nn import init
import functools
from torch.optim import lr_scheduler
from math import floor, log2
from functools import partial
from linear_attention_transformer import ImageLinearAttention
###
from random import random
import numpy as np
import torch.nn.functional as F... |
import pytest
from psautohint import _psautohint
INFO = b"FontName Foo"
NAME = b"Foo"
GLYPH = b"""% square
0 500 rb
60 500 ry
sc
560 500 mt
560 0 dt
60 0 dt
60 500 dt
cp
ed
"""
def test_autohint_good_args():
_psautohint.autohint(INFO, GLYPH)
def test_autohintmm_good_args():
_psautohint.autohintmm((GLYPH,... |
"""
Created by Jacky LUO
Using python3.5
Reference: https://pjreddie.com/projects/mnist-in-csv
"""
def convert_mnist_csv(img_file, label_file, output_file, n):
imgf = open(img_file, 'rb')
labelf = open(label_file, 'rb')
outputf = open(output_file, 'w')
imgf.read(16)
labelf.read(8)
images = []... |
#
# 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 us... |
# WARNING: DO NOT USE THIS.
# This setup.py exists only to satisfy Read the Docs until they can support
# pyproject.toml (PEP 517):
# https://github.com/rtfd/readthedocs.org/issues/4912#issuecomment-444198329
# https://github.com/pypa/pip/pull/5743
from setuptools import setup
setup(
name='picard',
version='0.1... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2012-2015, Nigel Small
#
# 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from cassandra.cluster import Cluster
# Conectamos al Cluster
cluster = Cluster()
session = cluster.connect('tienda_online')
#******************************************************
# CONTADORES
#******************************************************
# Cargamos l... |
# Lint as: python3
# Copyright 2020 The TensorFlow Authors. 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 ... |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import logging as log
import numpy as np
from openvino.tools.mo.front.extractor import get_new_placeholder_name
from openvino.tools.mo.graph.graph import Node, Graph
from openvino.tools.mo.utils.error import Error
from openvino.tools.m... |
# Copyright 2015 ETH Zurich
#
# 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... |
"""
Transformer encoder / decoder layer chain
"""
import numpy as np
import tensorflow as tf
import lib.layers
from . import layers, ops
from .data import linelen
class Transformer:
def __init__(
self, name, inp_voc, out_voc,
logits_bias=False, share_emb=False, dst_rand_offset=False,
... |
"""
MySQL database backend for Django.
Requires MySQLdb: http://sourceforge.net/projects/mysql-python
"""
import re
try:
import MySQLdb as Database
except ImportError, e:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
# We want ... |
import torch
import torch as th
import syft
from syft.frameworks.torch.tensors.interpreters.additive_shared import AdditiveSharingTensor
from syft.frameworks.torch.tensors.interpreters.precision import FixedPrecisionTensor
from syft.generic.pointers.pointer_tensor import PointerTensor
import pytest
def test_init(wor... |
# Copyright (c) 2021 PaddlePaddle Authors. 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 appli... |
__author__ = "Johannes Köster"
__copyright__ = "Copyright 2021, Johannes Köster"
__email__ = "johannes.koester@uni-due.de"
__license__ = "MIT"
import collections
import os
import shutil
from pathlib import Path
import re
import stat
import time
import datetime
import json
import copy
import functools
import subprocess... |
from typing import Tuple
from typing import List
from typing import Any
from matplotlib.patches import Circle
from matplotlib.transforms import ScaledTranslation
from compas.geometry import Point
from compas.artists import PrimitiveArtist
from .artist import PlotterArtist
Color = Tuple[float, float, float]
class P... |
# -*- coding: utf-8 -*-
"""
S3 Extensions for gluon.dal.Field, reusable fields
@requires: U{B{I{gluon}} <http://web2py.com>}
@author: Dominic König <dominic[at]aidiq.com>
@copyright: 2009-2012 (c) Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any ... |
"""Grid example."""
from flow.controllers import GridRouter, IDMController, RLController
from flow.controllers.routing_controllers import MinicityRouter
from flow.core.params import SumoParams, EnvParams, InitialConfig, NetParams
from flow.core.params import VehicleParams, PersonParams
from flow.core.params import Traf... |
# -*- coding: UTF-8 -*-
#setup.py
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2006-2018 NV Access Limited, Peter Vágner, Joseph Lee
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
import os
import copy
import gettext
gettext.install("nvda", unicode=True)
f... |
##############################################################################
# Copyright (c) 2017 Huawei Technologies Co.,Ltd.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is avai... |
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import division, unicode_literals
"""
This module implements a FloatWithUnit, which is a subclass of float. It
also defines supported units for some commonly used units for energy, length,
temp... |
"""
Defines the Param pane which converts Parameterized classes into a
set of widgets.
"""
from __future__ import absolute_import, division, unicode_literals
import os
import sys
import json
import types
import inspect
import itertools
from collections import OrderedDict, defaultdict, namedtuple
from six import strin... |
import shutil
import sys
import time
import os
import argparse
"""
将源目录240天以上的所有文件移动到目标目录
"""
usage = 'python move_files_over_x_days.py -src [SRC] -dst [DST] -days [DAYS]'
description = 'Move files from src to dst if they are older than a certain number of days. Default is 240 days'
args_parser = argparse.ArgumentP... |
"""
Image manipulation and numpy arrays
====================================
This example shows how to do image manipulation using common numpy arrays
tricks.
"""
import numpy as np
import scipy
import scipy.misc
import matplotlib.pyplot as plt
face = scipy.misc.face(gray=True)
face[10:13, 20:23]
face[100:120] = 25... |
# 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 u... |
from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email')
class RegisterSerializer(serializers.ModelSerializer):
... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... |
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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,... |
"""
Declares Syncable and Reactive classes which provides baseclasses
for Panel components which sync their state with one or more bokeh
models rendered on the frontend.
"""
import difflib
import sys
import threading
from collections import namedtuple
from functools import partial
import numpy as np
import param
fr... |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.13.6
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name:... |
"""Support for SimpliSafe alarm systems."""
import asyncio
from uuid import UUID
from simplipy import API
from simplipy.entity import EntityTypes
from simplipy.errors import EndpointUnavailable, InvalidCredentialsError, SimplipyError
from simplipy.websocket import (
EVENT_CAMERA_MOTION_DETECTED,
EVENT_CONNECTI... |
'''
This module will extract tracking logs for a given course and date range
between when course enrollment start and when the course ended. For each log,
the parent_data and meta_data from the course_structure collection will be
appended to the log based on the event key in the log
'''
import pymongo
import sys
fr... |
# -*- coding: utf-8 -*-
"""
"""
import sys
import ctypes
import pytest
from rockhopper._ragged_array import slug
pytestmark = pytest.mark.order(1)
def log_range(start, stop, base):
while start < stop:
# These sequences give a quick way to test the full range of an
# integer type.
yield... |
# -*- coding: utf-8 -*-
import re
from cmyui.discord import Webhook
from cmyui.discord import Embed
from objects import glob
from objects.score import Score
from objects.score import Grade
from objects.player import Player
from objects.beatmap import Beatmap
from objects.match import Match
from objects.match import Sl... |
from pygears import gear, Intf
from pygears.lib import czip
from pygears.typing import Tuple, Uint, Union, Queue
from pygears.lib import fmap, demux, decouple, fifo, union_collapse
from pygears.lib import priority_mux, replicate
TCfg = Tuple[{'reduce_size': Uint['w_reduce_size'], 'init': 't_acc'}]
@gear
def reduce2(... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# 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 requi... |
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors.
#
# 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 appl... |
# -*- coding: utf-8 -*-
import asyncio
import copy
import random
import time
import threading
from collections import deque
from uuid import uuid4
from . import util
from .dash_msg import PRIVATESEND_ENTRY_MAX_SIZE
from .dash_ps_net import PSMixSession, PRIVATESEND_SESSION_MSG_TIMEOUT
from .dash_ps_wallet import (PSD... |
import logging
import subprocess
from multiprocessing import Process
logging.basicConfig(format='gpgeternal: %(asctime)s - %(message)s', level=logging.DEBUG)
def load_public_key(key_path):
try:
output = subprocess.check_output(['gpg2', '--import', key_path])
(output)
except Exception as e:
... |
"""Gradient interface"""
import torch
from .modules.utils import _single, _pair, _triple
import warnings
def _grad_input_padding(grad_output, input_size, stride, padding, kernel_size, dilation=None):
if dilation is None:
# For backward compatibility
warnings.warn("_grad_input_padding 'dilation' a... |
def card_value(card):
if card[0] == "2":
return 2
elif card[0] == "3":
return 3
elif card[0] == "4":
return 4
elif card[0] == "5":
return 5
elif card[0] == "6":
return 6
elif card[0] == "7":
return 7
elif card[0] == "8":
return 8
el... |
#!/usr/bin/env python
# Copyright 2015 Google Inc. 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 require... |
#!/usr/bin/env python3
from time import time
import requests
class RuqqusClient:
def __init__(
self,
client_id,
client_secret,
code=None,
access_token=None,
refresh_token=None,
):
self.headers = {}
self.url = 'https://ruqqus.com'
self.c... |
"""
HyperOne
HyperOne API # noqa: E501
The version of the OpenAPI document: 0.1.0
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
import h1
from h1.model.container_image import ContainerImage
class TestContainerImage(unittest.TestCase):
"""ContainerImage unit test... |
from django.conf.urls import url
from .views import InvitationDetailView
urlpatterns = [
url(r'^(?P<pk>[0-9]+)/$', InvitationDetailView.as_view(), name='invitations-detail')
] |
"""Provide functionality to stream video source.
Components use create_stream with a stream source (e.g. an rtsp url) to create
a new Stream object. Stream manages:
- Background work to fetch and decode a stream
- Desired output formats
- Home Assistant URLs for viewing a stream
- Access tokens for URLs for vi... |
import statistical_modeling as sm
from typing import Final
import unittest
class TestACF(unittest.TestCase):
def test(self):
s: Final = sm.Sample([1, 2, 3])
f: Final = 3
self.assertEqual(sm.ACF(s, f), sm.SampleACF(s, f)) |
# Copyright 2018 The TensorFlow Authors. 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 applica... |
#[The "BSD license"]
# Copyright (c) 2012 Terence Parr
# Copyright (c) 2012 Sam Harwell
# Copyright (c) 2014 Eric Vergnaud
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions ... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import logging
import sys
from typing import Dict
import numpy as np
from ml.rl.evaluation.evaluator import Evaluator
from ml.rl.preprocessing.preprocessor import Preprocessor
from ml.rl.preprocessing.sparse_to_dense import... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import configargparse
from onmt.utils.logging import init_logger
from onmt.utils.misc import split_corpus
from onmt.translate.translator import build_translator
import onmt.opts as opts
def main(opt):
translator = build_transl... |
import os
import argparse
from keras.models import load_model
import numpy as np
from sklearn.metrics import accuracy_score, f1_score
from data_preprocessing import *
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--model_name', default='save/RDNN.h5', type=str)
parser.add_argument('--smooth', type=boo... |
# ============================================================================
# ============================================================================
# Copyright (c) 2021 Nghia T. Vo. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... |
# -*- coding: utf-8 -*-
# Copyright 2017 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Asks users if the commit is good or bad."""
from __future__ import print_function
import os
from chromite.cros_bisect import... |
import io
from collections import Counter
from typing import Iterable
def read_input():
with io.open("input/day03") as f:
return f.read()
def most_common(bits: Iterable[str]):
c = Counter(bits)
return "0" if c["0"] > c["1"] else "1"
def least_common(bits: Iterable[str]):
c = Counter(bits)
... |
from dataclasses import dataclass
from typing import Generator
@dataclass
class Execution:
action: type
params: object
class Action:
@classmethod
def can_execute(cls, p):
return True
@classmethod
def execute(cls, p):
pass
@classmethod
def record_undo(cls, p) -> Gene... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.