text stringlengths 2 999k |
|---|
# coding: utf-8
# Copyright 2015 Eezee-It
import json
import logging
from hashlib import sha256
import urlparse
from odoo import models, fields, api
from odoo.tools.float_utils import float_compare
from odoo.tools.translate import _
from odoo.addons.payment.models.payment_acquirer import ValidationError
from odoo.ad... |
# Copyright 2018 The TensorFlow Probability 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 applicable law o... |
#
# vect3dotfun.py
# Dot product of two 3-d vectors using function in Python 3.7
#
# Sparisoma Viridi | https://github.com/dudung
#
# 20210110
# 2001 Start creating this example.
# 2002 Test it and ok.
#
# Define dot function with two arguments
def dot(a, b):
p = a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
return p
... |
from typing import Any, Dict, Union, Optional
from dataclasses import asdict, dataclass
Headers = Optional[Dict[str, Union[str, bool, int]]]
@dataclass
class APIGatewayProxyResult:
"""
Key names are expected and given by AWS APIGateway specifications and must not be changed
"""
statusCode: int
bo... |
class Status:
OK = "OK"
ERROR = "ERROR"
class Response(dict):
def __init__(self, status, data):
super().__init__()
self["status"] = status
self["data"] = data
|
# Copyright (c) 2022 Andreas Törnkvist | MIT License
import math
class worldfile:
def __init__(self, filename):
wFile = open(filename)
w = wFile.readlines()
w = [line.rstrip() for line in w]
self.A = float(w[0])
self.D = float(w[1])
self.B = float(w[2])
sel... |
# 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... |
# Copyright (C) 2015 Stefan C. Mueller
import functools
from twisted.internet import defer
def on_error_close(logger):
"""
Decorator for callback methods that implement `IProtocol`.
Any uncaught exception is logged and the connection is closed
forcefully.
Usage::
import logger
... |
# Copyright (c) 2006,2007,2008 Mitch Garnaat http://garnaat.org/
#
# 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,... |
# Copyright 2013 Lars Butler & individual contributors
#
# 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 applicab... |
import binascii
import re
import socket
from abc import ABCMeta
from hashlib import md5
from ipaddress import ip_network, _BaseNetwork
from typing import Iterable, Optional, Tuple, Generator, Dict, Iterator
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from djing.lib.decorato... |
# coding: utf-8
"""
Fabric task for deploying project on servers(production, staging, development)
"""
import os
import sys
from contextlib import contextmanager
from fabric.contrib import django
from fabric.api import local, run, lcd, cd
from fabric.tasks import Task
from fab_settings import env
sys.path.append(... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 5
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import isi_sdk_8_1_0
from i... |
# -*- coding: utf-8 -*-
"""
:copyright: Copyright 2020-2022 Sphinx Confluence Builder Contributors (AUTHORS)
:license: BSD-2-Clause (LICENSE)
"""
from tests.lib.testcase import ConfluenceTestCase
from tests.lib.testcase import setup_builder
import os
class TestConfluenceMetadata(ConfluenceTestCase):
@classmethod... |
import asyncio
import websockets
import time
import threading
players = 0
class Player:
def __init__(self, id, x = 0, y = 0, speed = 5):
self.id = id
self.x = x
self.y = y
self.dirX = 0
self.dirY = 0
self.speed = speed
print("Player criado com sucesso!")... |
__author__ = 'pulphix'
from app import TestApplication |
# coding: utf-8
from __future__ import unicode_literals
from django.contrib import admin
from .models import ThumbnailOption
from django.contrib.admin.widgets import AdminFileWidget
@admin.register(ThumbnailOption)
class ThumbnailOptionAdmin(admin.ModelAdmin):
fields = ['source', 'alias', 'options']
class Thu... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
sys.path.append("..")
try:
import os
import signal
import time
from conf import *
from lib import logger
from lib import mqtt
except Exception as e:
print(f"Import error: {str(e)} line {sys.exc_info()[-1].tb_lineno}, check requi... |
from database.adatabase import ADatabase
import pandas as pd
class SEC(ADatabase):
def __init__(self):
super().__init__("sec")
def retrieve_num_data(self,adsh):
try:
db = self.client[self.name]
table = db["nums"]
data = table.find({"adsh":adsh},{"_id":0}... |
import game_framework
from pico2d import *
import title_state
name = "StartState"
image = None
logo_time = 0.0
def enter():
global image
image = load_image('kpu_credit.png')
def exit():
global image
del(image)
def update():
global logo_time
if (logo_time > 1.0):
logo_time = 0.8
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 13 20:30:46 2020
@author: Aaronga
"""
# Datos faltantes
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv("Data.csv")
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 3].values
# Tratamiento de los NaN
from sklearn.preproc... |
from sqlalchemy.testing import assert_raises, eq_
from sqlalchemy.testing import fixtures, AssertsCompiledSQL
from sqlalchemy import (
testing, exc, case, select, literal_column, text, and_, Integer, cast,
String, Column, Table, MetaData)
from sqlalchemy.sql import table, column
info_table = None
class CaseT... |
#
# 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... |
# VARIAVEIS
# ATRIBUINDO VALOR A UMA VARIAVEL
var_teste = 1
print(var_teste)
print(type(var_teste))
#DECLARAÇÂO MULTIPLA
pessoa1, pessoa2, pessoa3 = 'Jose', 'Joao','Maria'
print(pessoa1)
print(pessoa2)
print(pessoa3)
# VARIAVEL COM ATRIBUIÇÃO
pessoa1=pessoa2=pessoa3 = 'Jose'
print(pessoa1)
print(pessoa2)
print(pesso... |
#-*- coding:utf-8 -*-
import json
import copy
import requests
import json
from flask import render_template, abort, request, url_for, redirect, g
import time
import datetime
from rrd import app
from rrd.model.screen import DashboardScreen
from rrd.model.graph import DashboardGraph
from rrd import consts
from rrd.utils... |
import torch
import torch.nn.functional as F
from torch.nn import Linear
from torch_geometric.nn import (ASAPooling,
GraphConv, global_mean_pool,
JumpingKnowledge)
class ASAP(torch.nn.Module):
def __init__(self, num_vocab, max_seq_len, node_encoder, ... |
#!/usr/bin/env python
import rospy
from duckietown_msgs.msg import WheelsCmdStamped, FSMState
class WheelsCmdSwitchNode(object):
def __init__(self):
self.node_name = rospy.get_name()
rospy.loginfo("[%s] Initializing " %(self.node_name))
# Read parameters
self.mappings = rospy.get_para... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.SettleEntity import SettleEntity
class AlipayTradeSettleReceivablesQueryModel(object):
def __init__(self):
self._biz_product = None
self._extend_params = None... |
import os
from deta import Deta
from datetime import date, datetime
from fastapi import HTTPException
import urllib
import base64
deta = Deta()
base = deta.Base("drawings")
drive = deta.Drive("drawings")
def get_all(db, query):
blob_gen = db.fetch(query)
blobs = []
for stored_blob in blob_gen:
... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... |
#!/usr/bin/env python
# Jonas Schnelli, 2013
# make sure the Africoin-Qt.app contains the right plist (including the right version)
# fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267)
from string import Template
from datetime import date
bitcoinDir = "./";
in... |
#!/usr/bin/env python
import sys
import re
import optparse
from ctypes import *
"""
This script will use the prototypes from "checkdocs.py -s" to concoct
a 1:1 Python wrapper for Allegro.
"""
class _AL_UTF8String:
pass
class Allegro:
def __init__(self):
self.types = {}
self.functions = {}
... |
"""File for Google Cloud Storage."""
import logging
import os
import urllib.parse
from pathlib import Path
import aiohttp
from aiofile import AIOFile
from gcloud.aio.storage import Storage
from google.cloud import storage
from one_barangay.local_settings import logger
async def async_upload_to_bucket(
filepath:... |
#####################################################
# Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2021.04 #
#####################################################
# python exps/LFNA/basic-same.py --srange 1-999 --env_version v1 --hidden_dim 16
# python exps/LFNA/basic-same.py --srange 1-999 --env_version v2 --hidden_dim... |
'''
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Interv... |
from rest_framework import viewsets
from periodic_tasks_api.models import CustomExtendedPeriodicTask
from periodic_tasks_api.serializers import PeriodicTaskSerializer
from periodic_tasks_api.filters import PeriodicTaskFilterSet
class PeriodicTaskView(viewsets.ModelViewSet):
queryset = CustomExtendedPeriodicTask.... |
#!/usr/bin/python3
# coding: utf-8
from network.group import Group
import paho.mqtt.client as mqtt
from threading import Thread
import time
from log import logger
import paho.mqtt.subscribe as subscribe
import json
import random
import string
class Switch(Thread):
def __init__(self, broker_ip):
Thread._... |
# coding=utf-8
########################################################################################################################
### Do not forget to adjust the following variables to your own plugin.
# The plugin's identifier, has to be unique
plugin_identifier = "bedlevelvisualizer"
# The plugin's python pa... |
#!/usr/bin/env python3
# Automatically generated file by swagger_to. DO NOT EDIT OR APPEND ANYTHING!
"""Implements the client for test."""
# pylint: skip-file
# pydocstyle: add-ignore=D105,D107,D401
import contextlib
import json
from typing import Any, BinaryIO, Dict, List, MutableMapping, Optional
import requests
i... |
# Copyright 2021 Research Institute of Systems Planning, 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 applica... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import yaml
class HexahueMap():
def __init__(self, space_color):
pink = (255, 0, 255)
red = (255, 0, 0)
green = (0, 255, 0)
yellow = (255, 255, 0)
blue = (0, 0, 255)
sky = (0, 255, 255)
white = (255, 255, 255)
gray = (128, 128, 128)
blac... |
# 7 завдання
for n in range(1, 101):
print(n, "Я не буду їсти палички Бобо на уроці")
|
"""
SoftLayer.ordering
~~~~~~~~~~~~~~~~~~
Ordering Manager
:license: MIT, see LICENSE for more details.
"""
class OrderingManager(object):
"""Manages hardware devices.
:param SoftLayer.API.Client client: an API client instance
"""
def __init__(self, client):
self.client = cl... |
# BOJ 14501
import sys
si = sys.stdin.readline
t = [0] * 17
dp = [0] * 17
n = int(si())
for i in range(1, n + 1):
m, o = map(int, si().split())
t[i] = m
dp[i] = o
def solve(n):
ans = 0
for i in range(n, 0, -1):
if i + t[i] > n + 1:
dp[i] = dp[i + 1]
else:
... |
import torch.utils.data as data
from PIL import Image
import torchvision.transforms as transforms
from torchvision.transforms import InterpolationMode
class BaseDataset(data.Dataset):
def __init__(self):
super(BaseDataset, self).__init__()
def name(self):
return 'BaseDataset'
def initiali... |
"""
Created Oct 19, 2017
@author: Spencer Vatrt-Watts (github.com/Spenca)
"""
from __future__ import unicode_literals
from django.apps import AppConfig
class TenxConfig(AppConfig):
name = 'tenx' |
import pyperclip
import math
class Affine_Cipher:
def __init__(self):
self.SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'
def check_key(self, key):
keyA = key // len(self.SYMBOLS)
keyB = key % len(self.SYMBOLS)
# Weak Key Checks
if keyA... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('stocks', '0003_auto_20151129_1623'),
]
operations = [
migrations.Alter... |
# Name: Breno Maurício de Freitas Viana
# NUSP: 11920060
# Course Code: SCC5830
# Year/Semester: 2021/1
# Assignment 5: Image Descriptors
import math
import numpy as np
import imageio
from scipy import ndimage
np.seterr(divide='ignore', invalid='ignore')
LEVELS = 256
# ----- (1) Read Parameters
# Get the locatio... |
"""Test trunk lock."""
import pytest
from tests.tesla_mock import TeslaMock
from teslajsonpy.controller import Controller
from teslajsonpy.trunk import TrunkLock
def test_has_battery(monkeypatch):
"""Test has_battery()."""
_mock = TeslaMock(monkeypatch)
_controller = Controller(None)
_data = _moc... |
import sys
from cx_Freeze import setup, Executable
setup(
name='YtMusic-Lib-Tracker',
url='https://github.com/czifumasa/ytmusic-lib-tracker',
author='Łukasz Lenart',
author_email='lukasz.lenart912@gmail.com',
version='0.1',
license='MIT',
description='Useful tools for youtube music. Exporti... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import time
CS = 5
Clock = 25
Address = 24
DataOut = 23
Button = 7
class TRSensor(object):
def __init__(self,numSensors = 5):
self.numSensors = numSensors
self.calibratedMin = [0] * self.numSensors
self.calibratedMax = [1023] * self.numSensors
... |
import connexion
from openapi_server.annotator.phi_types import PhiType
from openapi_server.get_annotations import get_annotations
from openapi_server.models.error import Error # noqa: E501
from openapi_server.models.text_date_annotation_request import \
TextDateAnnotationRequest # noqa: E501
from openapi_server.... |
#-*- encoding: utf-8 -*-
import sys
import Tkinter as tk
import service
import keycode
if sys.platform == 'win32':
from ctypes import wintypes, byref, windll
import win32con
def handle_hotkey(root, callback):
msg = wintypes.MSG()
if windll.user32.GetMessageA(byref(msg), None, 0, 0) != 0:... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import logging
from .lr_scheduler import WarmupMultiStepLR
def make_optimizer(cfg, model):
logger = logging.getLogger("fcos_core.trainer")
params = []
for key, value in model.named_parameters():
if not value.requi... |
# -*- coding: utf-8 -*-
"""Patched version of PyPi Kitchen's Python 3 getwriter function. Removes
extraneous newlines."""
import codecs
from kitchen.text.converters import to_bytes
def getwriter(encoding):
"""Return a :class:`codecs.StreamWriter` that resists tracing back.
:arg encoding: Encoding to use for... |
input = """
colored(2,g) :- not diff_col(2,g).
colored(2,y) :- not diff_col(2,y).
colored(3,g) :- not diff_col(3,g).
colored(3,y) :- not diff_col(3,y).
diff_col(2,g) :- colored(2,y).
diff_col(3,g) :- colored(3,y).
diff_col(2,y) :- colored(2,g).
diff_col(3,y) :- colored(3,g).
no_stable :- colored(2,2), color... |
import logging
from datetime import datetime
import botocore.loaders
import botocore.regions
from boto3 import Session as Boto3Session
from botocore.exceptions import ClientError
from .exceptions import CLIMisconfiguredError, DownstreamError
LOG = logging.getLogger(__name__)
BOTO_CRED_KEYS = ("aws_access_key_id", "... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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 cop... |
#!/usr/bin/env python3
# Very basic bitstream to SVF converter
# This file is Copyright (c) 2018 David Shah <dave@ds0.me>
import sys
import textwrap
max_row_size = 100000
def bitreverse(x):
y = 0
for i in range(8):
if (x >> (7 - i)) & 1 == 1:
y |= (1 << i)
return y
def bit_to_svf(bi... |
#!/usr/bin/env python2
# -*-: coding utf-8 -*-
import ConfigParser
from coffeehack.coffeehack import CoffeeHack
from hermes_python.hermes import Hermes
import io
import Queue
CONFIGURATION_ENCODING_FORMAT = "utf-8"
CONFIG_INI = "config.ini"
MQTT_IP_ADDR = "localhost"
MQTT_PORT = 1883
MQTT_ADDR = "{}:{}".format(MQTT_... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2011 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://babel.edgewall.org/wiki/License.
#
# This software consists... |
# Copyright 2013-2020 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)
"""Manages the details on the images used in the build and the run stage."""
import json
import os.path
#: Global variable... |
# Name: VolumeExtractChannel
import inviwopy as ivw
import numpy as np
class VolumeExtractChannel(ivw.Processor):
def __init__(self, id, name):
ivw.Processor.__init__(self, id, name)
self.inport = ivw.data.VolumeInport("inport")
self.addInport(self.inport, owner=False)
self.outpor... |
# Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
# General Public License as public by the Free Software Foundation; version 2.0
# or (at your option) any later version. You can redistribute it and/or
# modify it under the terms of either of these two licenses.
#
# Unless required by applica... |
# -*- test-case-name: twisted.web2.test.test_httpauth -*-
from twisted.cred import credentials, error
from twisted.web2.auth.interfaces import ICredentialFactory
from zope.interface import implements
class BasicCredentialFactory(object):
"""
Credential Factory for HTTP Basic Authentication
"""
imple... |
from couchbase.management.admin import Admin
from couchbase_core.mapper import BijectiveMapping, \
StringEnum, Identity, Timedelta, Bijection, StringEnumLoose
from ..options import OptionBlockTimeOut, forward_args
from couchbase.management.generic import GenericManager
from typing import *
from couchbase_core impor... |
"""
This module implements the core class hierarchy for implementing EO tasks. An EO task is any class the inherits
from the abstract EOTask class. Each EO task has to implement the execute method; invoking __call__ on a EO task
instance invokes the execute method. EO tasks are meant primarily to operate on EO patches ... |
from kol.request.GenericRequest import GenericRequest
from kol.manager import PatternManager
import kol.Error as Error
from kol.util import Report
class RespondToTradeRequest(GenericRequest):
def __init__(self, session, tradeid, items=None, meat=0, message=""):
super(RespondToTradeRequest, self).__sup... |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Caps(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "volume"
_path_str = "volume.caps"
_valid_props = {"x", "y", "z"}
# x
# -
@propert... |
# 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... |
import json
import logging
import sys
from redash.query_runner import *
from redash.utils import JSONEncoder
logger = logging.getLogger(__name__)
try:
from pyhive import hive
enabled = True
except ImportError, e:
enabled = False
COLUMN_NAME = 0
COLUMN_TYPE = 1
types_map = {
'BIGINT': TYPE_INTEGER,
... |
class Buffer:
def __init__(self):
self.lst = list()
def add(self, *a):
for value in a:
self.lst.append(value)
while len(self.lst) >= 5:
s = 0
for i in range(5):
s += self.lst.pop(0)
print(s)
def get_current_part(self)... |
class GeometryObject(APIObject, IDisposable):
""" The common base class for all geometric primitives. """
def Dispose(self):
""" Dispose(self: APIObject,A_0: bool) """
pass
def Equals(self, obj):
"""
Equals(self: GeometryObject,obj: object) -> bool
Determines... |
import os
import math
import argparse
import gym
from agents.q_agent import Q, Agent, Trainer
RECORD_PATH = os.path.join(os.path.dirname(__file__), "./upload")
def main(episodes, render, monitor):
env = gym.make("CartPole-v0")
q = Q(
env.action_space.n,
env.observation_space,
bin... |
import os
import subprocess
import numpy as np
from tqdm import tqdm
from typing import Dict
MAX_FREQ = 7999
def to_str(v):
if isinstance(v, tuple):
s = " ".join(str(x) for x in v)
elif isinstance(v, float) or isinstance(v, int):
s = str(v)
else:
assert False
return s
def ... |
#!/usr/bin/env python
# Copyright 2014 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
import logging
import os
import sys
import tempfile
import shutil
import unittest
import re
# Import this first before manipulatin... |
# -*- Python -*-
# This file is licensed under a pytorch-style license
# See frontends/pytorch/LICENSE for license information.
import torch
import npcomp.frontends.pytorch as torch_mlir
import npcomp.frontends.pytorch.test as test
# RUN: %PYTHON %s | FileCheck %s
dev = torch_mlir.mlir_device()
t0 = torch.randn((4,4... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
from rest_framework.permissions import SAFE_METHODS, BasePermission
class IsAdminOrReadOnly(BasePermission):
"""
The request is authenticated as an Admin user or is Read Only
"""
def has_permission(self, request, view):
return bool(
request.method in SAFE_METHODS or
re... |
#!/usr/bin/env python3
import argparse
import io
import sys
from urllib.request import urlopen
import urllib.error
import time
import datetime
from retrying import retry
URL = "http://unreliable.labs.crossref.org/error"
ONE_SECOND=1000
ONE_HOUR=((ONE_SECOND*60)*60)
ONE_DAY=(ONE_HOUR*24)
@retry(wait_exponential_mul... |
# url="http://www.baidu.com/?page=/wd=xiaopangzi"
'''
url1="www.baidu.com/?page="
url2="wd=xiaopangzi"
while(1):
for i in range(1,100):
print(url1,i,url2)
i=i+1
break
for i in range(100):
part1=www.baidu.com/?page=
res = part1 +
'''
'''
A1=[1,1,1,1,1,2,2,2,2,2,3]
a1=[]
for i i... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 8
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import isi_sdk_8_2_1
from i... |
#
# Copyright (C) 2019 Databricks, 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 or agreed to i... |
import argparse, subprocess, os, re
from jinja2 import Environment, FileSystemLoader
def GetBaseName(full_path):
return os.path.basename(full_path)
class PlantUMLCodeGeneration():
class StateType():
def __init__(self):
self.entry = None
self.during = None
self.exit... |
"""
====================
Build image pyramids
====================
The ``pyramid_gaussian`` function takes an image and yields successive images
shrunk by a constant scale factor. Image pyramids are often used, e.g., to
implement algorithms for denoising, texture discrimination, and scale-
invariant detection.
"""
im... |
# Copyright (c) Facebook, Inc. and its 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 required by applicable law or ... |
from flask_socketio import SocketIO
from flask import Flask, make_response, request, session
from flask import render_template, session, url_for, redirect
from threading import RLock
from threading import Thread
from utilslib import list_to_HTML_table
from time import sleep
from ClientStorage import Clients, User
fr... |
from torch.utils.data import Dataset, DataLoader
import glob
import os
import numpy as np
import cv2
import torch
from torchvision import transforms, utils
from skimage.transform import resize
class SegDataset(Dataset):
"""Segmentation Dataset"""
def __init__(self, root_dir, imageFolder, maskFolder, transfor... |
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
import pytest
import vtk
import numpy as np
import sksurgeryvtk.utils.polydata_utils as pdu
import sksurgeryvtk.models.vtk_surface_model as vbs
def test_overlapping_bounds():
radius_0=10.0
radius_1=7.0
centre_1=5.0
radius_2=4.0
centre_2=15.0
rad... |
import string
import random
# --- Defining Variables ---
LOWER_ALPHABET = list(string.ascii_lowercase)
DIGITS = list(string.digits)
UPPER_ALPHABET = list(string.ascii_uppercase)
SYMBOLS = list(string.punctuation)
SYMBOLS_DELETE = ['"', "'", "(", ")", ",", ".", ":", ";", "[", "]", "|", "`", "{", "}"]
for x in SYMBOLS... |
"""
An implementation for the gilded rose kata as I understand it.
https://github.com/NotMyself/GildedRose
"""
from collections import namedtuple
import unittest as ut
from ruleta import Rule, ActionSet
from ruleta.combinators import ALSO
import re
ItemRecord = namedtuple("ItemRecord",["name", "quality", "quality... |
# type: ignore
import json
import uuid
from json import JSONDecodeError
from typing import Tuple, Dict, List
import boto3
from melange.drivers.interfaces import Queue, Topic, MessagingDriver, Message
class AWSDriver(MessagingDriver):
def __init__(self, **kwargs):
super().__init__()
self.max_num... |
'''
Created on 23.08.2017
@author: falensaa
'''
import logging
import sys
import imsnpars.nparser.features
import imsnpars.nparser.network
import imsnpars.nparser.graph.features as gfeatures
from imsnpars.nparser.graph import task, decoder
from imsnpars.nparser.graph.mst import cle
from imsnpars.nparser.labels impor... |
# 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.22
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Bout (read bank-out) extracts transactions from pdf bank statements.
_ _
(_) (_)
(_) _ _ _ _ _ _ _ _ _ (_) _ _
(_)(_)(_)(_)_ _ (_)(_)(_) _ (_) (_)(_)(_)(... |
from colored import *
import staticconf
"""
You might find the colored documentation very useful:
https://pypi.python.org/pypi/colored
"""
ENABLE_COLORIZER = staticconf.read_string('enable_colorizer', default='false').lower() == 'true'
def colorizer_enabled(function):
"""do not colorize if it's not enabled"""
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
from datetime import timedelta
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth.models import User
from django.utils import timezone
from allauth.account.models import EmailAddress
from rest_framework import status
from rest_framework.test import APITestCase, APIClient
from challenges.model... |
# copyright 2022 @Ansaku
# Telegram @AnkiSatya
# Instagram @satya_ask
import telebot
import requests
from telebot.types import InlineKeyboardButton
# Fillout Here The BotToken it gets from botfather further queries @AnkiSatya 0n telegram
bot = telebot.TeleBot('**********************')
while True:
try:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.