content stringlengths 5 1.05M |
|---|
# encoding: UTF-8
'''
vnpy.api.okex的gateway接入
更新OKEX V3
By Chenzhipei
'''
import os
import json
from datetime import datetime, timedelta
from time import sleep
import time as td
from copy import copy
from threading import Condition
from queue import Queue
from threading import Thread
from time import sleep
import tra... |
from fabric.api import *
from fabric.contrib.files import *
from cloudbio.flavor import Flavor
from cloudbio.custom.shared import (_fetch_and_unpack)
import sys
# This flavour installs the Seal toolkit for processing high-throughput
# sequencing data on Hadoop.
# http://biodoop-seal.sf.net/
#
# It pulls in quite ... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 json
from Acquisition import aq_inner
from five import grok
from zope import schema
from zope.component import getUtility
from zope.lifecycleevent import modified
from plone.dexterity.content import Container
from plone.namedfile.interfaces import IImageScaleTraversable
from plone.supermodel import model
from ... |
import unittest
import numpy as np
import openmdao.api as om
from openmdao.utils.assert_utils import assert_rel_error
class TestNonlinearCircuit(unittest.TestCase):
def test_nonlinear_circuit_analysis(self):
import numpy as np
import openmdao.api as om
class Resistor(om.ExplicitCompon... |
""" Timeflux """
# Fix Ctrl-C handling in Windows
import os
os.environ["FOR_DISABLE_CONSOLE_CTRL_HANDLER"] = "1"
# Versioning
try:
from setuptools_scm import get_version
__version__ = get_version(root="..", relative_to=__file__)
except:
try:
from .version import version
__version__ = ve... |
from models.base.connection.ConnectionQueueBase import ConnectionQueueBase
from typing import List
from sqlalchemy import Column, String, Integer, ForeignKey
from sqlalchemy.orm import relationship
from models.base.connection.ConnectionDatabaseBase import ConnectionDatabaseBase
from models.base.connection.ConnectionFi... |
from .extensions import db, ma
from celery import Celery
from flask import Flask
from flask import g
from flask_bootstrap import Bootstrap
from .config import config, SELECTED_CONFIG
from .views import recipes
def create_celery_app(app=None):
app = app or create_app()
celery = Celery(__name__, broker=app.conf... |
#
# 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... |
"""
Various views for the app.
"""
from datetime import datetime
import json
from flask import (
render_template,
request
)
from bookmarks import (
app,
util,
)
from bookmarks.db import (
db,
Bookmark,
BookmarkEncoder,
)
config_file = "config.json"
config = {}
@app.before_first_request... |
import cv2
import pafy
face_cascade=cv2.CascadeClassifier("haarcascade_frontalface_alt2.xml")
ds_factor=0.6
class VideoCamera(object):
def __init__(self):
video_url = "https://www.youtube.com/watch?v=cCXB97tRouM"
youtube_url = pafy.new(video_url)
stream_url = youtube_url.getbest(preftype="... |
'''
Author: yangzuo
Date: 2021-04-20 15:48:37
Email: yangzuo@tencent.com
LastEditors: yangzuo
LastEditTime: 2021-04-20 15:51:18
FilePath: /leetcode_solution/solutions/Tree/104.py
'''
'''
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ ... |
# -*- coding: utf-8 -*-
from flask import jsonify, request, session, Blueprint
from models.account import User, AnonymousUser
from utils.decorators import login_required
from weblist import db
auth = Blueprint('auth', __name__, url_prefix='/api/auth')
@auth.route('/register/', methods=['POST'])
def register():
... |
from time import ctime
from flask import Flask
from flaskext.enterprise import Enterprise
from controller import user_controller
from mongoengine import *
import config
app = Flask(__name__)
connect('db')
enterprise = Enterprise(app)
String = enterprise._sp.String
Integer = enterprise._sp.Integer
Boo... |
import unittest
from dcp.problems.daily.first_missing import first_missing1
class Test_FirstMissing1(unittest.TestCase):
def setUp(self):
pass
def test_case1(self):
assert first_missing1([3, 4, -1, 1]) == 2
def test_case2(self):
assert first_missing1([1, 2, 0]) == 3... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
def load_file_lines (file):
""" Loads a file as a list of lines.
Args:
file (str): The path of the file.
Returns:
list of str: A list of lines in the file.
"""
data = []
with open(file, mode='r') as target:
for line in target:
data.append(line.rstrip('\n'))
... |
import copy
import unittest
import requests_mock
import zeep.exceptions
from tbk.soap.requestor import SoapRequest
from tbk.soap.soap_client import SoapClient
from tbk.soap.exceptions import InvalidSignatureResponse, TypeDoesNotExist, SoapServerException, MethodDoesNotExist
from tbk.soap.utils import load_key_from_d... |
"""3D cone shape settings."""
from ctypes import byref, c_float
from .fmodobject import _dll
from .utils import ckresult
class ConeSettings:
"""Convenience wrapper class to handle 3D cone shape settings for simulated
occlusion which is based on direction.
"""
def __init__(self, sptr, class_name):
... |
import pygame
from pprint import pprint
import glob
from progress.bar import Bar
from classes.deck import Deck
from classes.cards import Card
from classes.player import Player
from classes.dealer import Dealer
from classes.table import Table
from classes.game import Game
def load_imgs(folder):
files = glob.glob(f... |
# from django.test import TestCase
# from .models import Project,Rating
# from django.contrib.auth.models import User
# # Create your tests here.
# class ProjectTestClass(TestCase):
# # Set up method
# def setUp(self):
# # Creating a new location and saving it
# self.new_user=User(username='ma... |
import numpy as np
class Part(object):
"""
얼굴 일부분 인식 후 x,y 좌표 반환
"""
FACE_TOP = [21, 22]
FACE_BOTTOM = [7, 8, 9]
FACE_LEFT = [0, 1, 2, 3]
FACE_RIGHT = [13, 14, 15, 16]
def __init__(self, landmarks, side):
self.frame = None
self.region_list = None
self.x = Non... |
# First install spidev:
# Enable SPI (sudo raspi-config)
# $ sudo apt-get update
# $ sudo apt-get upgrade
# $ sudo apt-get install python-dev
# $ sudo reboot
# $ wget https://github.com/doceme/py-spidev/archive/master.zip
# $ unzip master.zip
# $ cd py-spidev-master
# $ sudo python setup.py install
from spidev import ... |
import py, os
class NullPyPathLocal(py.path.local):
def join(self, *args):
return self.__class__(py.path.local.join(self, *args))
def open(self, mode):
return open(os.devnull, mode)
def __repr__(self):
return py.path.local.__repr__(self) + ' [fake]'
|
import os
import random
import glob
import numpy as np
random.seed(1234)
data_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'VCTK')
print(data_dir)
pathlist = glob.glob(os.path.join(data_dir, "**", "*.spec.npy"))
pathlist = [path for path in pathlist if "whisperized" not in path]
# filter o... |
from itertools import count
# ideone.com/aVndFM
def postponed_sieve(): # postponed sieve, by Will Ness
yield 2; yield 3; yield 5; yield 7; # original code David Eppstein,
sieve = {} # Alex Martelli, ActiveState Recipe... |
# coding: utf-8
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019-Present Datadog, Inc.
from __future__ import absolute_import
import unittest
import datad... |
# ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University at Buffalo
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copy... |
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.linear_model import LassoCV
from sklearn.linear_model import Lasso
from sklearn.model_selection import KFold
from sklearn.model_selection import GridSearchCV
diabetes = datasets.load_diabetes()
X =... |
# _*_ coding:utf-8 _*_
import logging
import re
from pyquery import PyQuery as pq
from app.spider_store.utils.content_cleaner import cleaner
from app.spider_store.common import (get_content,)
"""***中华网爬虫***"""
def zhonghua_news_download(url):
i = 1
content_list = []
title = None
source = None
t... |
'''
# Traffic light detection
'''
import cv2
import numpy as np
import time
from rmracerlib import config as cfg
from rmracerlib.cv.func import sign_direction, direction_check, valid_range
## FILTERS
# brightness filter
#brightness_lower = np.array([0, 0, 255])
#brightness_upper = np.array([180, 255, 255])
brightne... |
#!/usr/bin/env python
import os
import sys
from DIRAC import S_OK, S_ERROR, gConfig, gLogger, exit
from DIRAC.Core.Base import Script
import DIRAC
usageMsg = '''Get squids for a site.
{0} [option|cfgfile] site'''.format(Script.scriptName)
Script.setUsageMessage(usageMsg)
Script.parseCommandLine(ignoreErrors=False)
... |
class Solution(object):
def trap(self, height):
if len(height) < 3:
return 0
max_idx = 0
cur_max = 0
for i in range(len(height)):
if height[i] > cur_max:
cur_max = height[i]
max_idx = i
sum_arr = [0]
... |
#!/usr/bin/python
# ==============================================================================
# Author: Tao Li (taoli@ucsd.edu)
# Date: Jun 4, 2015
# Question: 043-Multiply-Strings
# Link: https://leetcode.com/problems/multiply-strings/
# ==================================================================... |
# Encoding: utf-8
""" Module to interact with the Matlab GUI for spine segmentation
and pulling out time courses from the data
"""
from __future__ import print_function
import copy
import logging
import os
import sys
import itertools
from builtins import zip
from builtins import map
import SimpleITK as... |
"""
Preprocessing worker class for parallel text processing.
"""
import multiprocessing as mp
import re
import logging
from ..utils import merge_dict_sequences_inplace
from ._common import ngrams, vocabulary, vocabulary_counts, doc_frequencies, sparse_dtm, \
glue_tokens, remove_chars, transform, _build_kwic, expa... |
#!/usr/bin/env python
# coding: utf-8
# # LCR in series
# 
# Resonating frequency
# \begin{equation}
# f_0=\frac{1}{2\pi\sqrt{LC}}
# \end{equation}
# Quality factor
# \begin{equation}
# Q=\frac{1}{R}\sqrt{\frac{L}{C}}
# \end{equation}
# Inductive reactance
# \begin{equation}
# X_L=2\pi fL
# \end{equ... |
import json
class BaseNamespace(object):
name = None
def __init__(self, server):
self.server = server
self.clients = []
super(BaseNamespace, self).__init__()
def get_name(self):
""" Get namespace name """
return self.name
def _register_client(self, client):
... |
"""
.. module:: test_offers_list
"""
from django.test import Client
from django.test import TestCase
from apps.volontulo.factories import OfferFactory
from apps.volontulo.factories import OrganizationFactory
from apps.volontulo.factories import UserFactory
class TestOffersList(TestCase):
"""Class responsible fo... |
import unittest
import numpy as np
import time
from src.classes.ElasticsearchManager import ElasticsearchManager
from src.classes.Evaluator import Evaluator
from src.classes.TestPoint import TestPoint
class EvaluationTest(unittest.TestCase):
elasticsearch_manager = ElasticsearchManager()
data2index = [{'song... |
"""
Contains a class as a datastore for model parameters
"""
import random
import typing
import mesh_tensorflow as mtf
import tensorflow as tf
from tensorflow.python.tpu.device_assignment import DeviceAssignment
class BlockConfig:
def __init__(self, config, memory_reduction_strategy: str):
if isinstance(... |
import numpy as np
from datetime import datetime
import pandas as pd
import pyodbc
class Config:
def __init__(self):
self.server='iZ1wll9swpj1hbZ\SQLEXPRESS'
self.database = '39F'
self.username ='harryyan'
self.password ='Aa12345678'
class EXC:
def __init__(self):
self.aa... |
"""
Contains useful constants.
"""
KMD_AUTH_HEADER = "X-KMD-API-Token"
"""str: header key for kmd requests"""
ALGOD_AUTH_HEADER = "X-Algo-API-Token"
"""str: header key for algod requests"""
INDEXER_AUTH_HEADER = "X-Indexer-API-Token"
"""str: header key for indexer requests"""
UNVERSIONED_PATHS = ["/health", "/versions"... |
from sqlalchemy import select
from src.repositories.irepository import IRepository
from src.models import Base
class SqlRepository(IRepository):
model = Base
async def get_all(self):
async with self.session_factory() as session:
result = await session.execute(select(self.model))
... |
"""
Data Loader for Pathology image data files.
##################
License: Apache License 2.0
author: Caner Mercan, 2018
"""
import pdb
import numpy as np
from .directory import DataDir as DD
from . import dataNames as DN
import scipy.io as sio
class Cases():
"""
Loading all case IDs and names into memory.... |
#
# author: Jungtaek Kim (jtkim@postech.ac.kr)
# last updated: September 24, 2020
#
"""It defines wrappers for Bayesian optimization."""
import time
import numpy as np
from bayeso import bo
from bayeso import constants
from bayeso.utils import utils_bo
from bayeso.utils import utils_common
from bayeso.utils import ut... |
'''
A sensor is a callable taking no arguments,
returning a humidity and a temperature.
It is constructed with a `source' parameter.
'''
from functools import partial
def sensor(func):
'''
The sensor decorator converts a function
taking a source parameter into a sensor.
>>> @sensor
... def test(s... |
__author__ = 'Scott Gramig'
__program__ = 'Paper-Rock-Scissors-Lizard-Spock'
import random
import os
#global variables to track w/l/t
win = 0
loss = 0
tie = 0
def greeting(): # greets player and tells rule
print("Let's play Rock-Paper-Scissors-Lizards-Spock!!")
print("Rules:")
print("0: Rock-------->beats Scis... |
from germanium.annotations import login
from germanium.test_cases.client import ClientTestCase
from germanium.tools import assert_contains
from .test_case import HelperTestCase, AsSuperuserTestCase
class UIOrderingTestCase(AsSuperuserTestCase, HelperTestCase, ClientTestCase):
ISSUE_UI_URL = '/issue/'
@login... |
import numpy as np
from numpy.linalg import cholesky, inv
class SigmaSets(object):
"""
Generates sigma points and weights using one of several available
methods.
Parameters
----------
sqrt_method : function(ndarray)
The matrix square root used to compute sigma points.
add ... |
"""
This file updates the data format as of 03/24 to add the filters to
schematics change
proposed in : https://github.com/facebookresearch/fairo/pull/276
issue: https://github.com/facebookresearch/fairo/issues/219
changeset: https://www.internalfb.com/phabricator/paste/view/P335720205
"""
import argparse
import json
i... |
from django.apps import AppConfig
class BadgifyConfig(AppConfig):
name = 'badgify'
verbose_name = 'Badgify'
def ready(self):
super(BadgifyConfig, self).ready()
self.module.autodiscover()
|
from tempfile import TemporaryDirectory
import pytest
from nebullvm.base import DeepLearningFramework
from nebullvm.inference_learners.onnx import ONNX_INFERENCE_LEARNERS
from nebullvm.optimizers.onnx import ONNXOptimizer
from nebullvm.optimizers.tests.utils import get_onnx_model
@pytest.mark.parametrize(
("out... |
import golly as g
s1 = g.getstring("Enter stack size:", "233")
s2 = g.getstring("Enter stdin buffer starting address:", "290")
s3 = g.getstring("Enter stdout buffer starting address:", "790")
RAM_NEGATIVE_BUFFER_SIZE = int(s1)
QFTASM_RAMSTDIN_BUF_STARTPOSITION = int(s2) + RAM_NEGATIVE_BUFFER_SIZE
QFTASM_RAMSTDOUT_BUF... |
#!/usr/bin/python
#
# 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 or ag... |
#
# 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
# distributed under t... |
import RtAudio
import numpy
import time
# ID of the output device. You can find this from printIODevices.py
deviceId = 2
sampleRate = 44100
bufferSize = 1024
rate = 0.005
def sawGen(bufferSize):
""" Make a numpy array with a saw wave in """
lastValue = 0
while 1:
sawValues = []
for i in... |
import unittest
from fizzbuzz import *
class FizzBuzzTest(unittest.TestCase):
def setUp(self):
self.maxDiff = None
def test_fizzbuzz(self):
model = FizzBuzzModel()
self.assertEquals(self.__solution(), model.solve())
@staticmethod
def __solution():
solution = []
... |
dna_seq1 = 'ACC'
nucl_count = {'A': 0,
'C': 0,
'G': 0,
'T': 0}
# Iterate through each nucleotide in turn:
for nucl in dna_seq1:
# Print current state of nucl_count dictionary:
print('Dictionary at start of loop: ' + str(nucl_count))
# Print current value of nucl:... |
"""The Logitech Squeezebox integration."""
import logging
from openpeerpower.components.media_player import DOMAIN as MP_DOMAIN
from openpeerpower.config_entries import ConfigEntry
from openpeerpower.core import OpenPeerPower
from .const import DISCOVERY_TASK, DOMAIN, PLAYER_DISCOVERY_UNSUB
_LOGGER = logging.getLog... |
import os
import sys
import json, csv
from bs4 import BeautifulSoup
import xml.etree.ElementTree as ET
from copy import copy
def dictify(r,root=True):
if root:
return {r.tag : dictify(r, False)}
d=copy(r.attrib)
if r.text:
d["_text"]=r.text
for x in r.findall("./*"):
if x.tag n... |
# Copyright (c) 2015 Riverbed Technology, Inc.
#
# This software is licensed under the terms and conditions of the MIT License
# accompanying the software ("License"). This software is distributed "AS IS"
# as set forth in the License.
import unittest
import steelscript.netshark.core.filters as filters
class Filt... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright(c) 2021 The MITRE 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 copy of the License at:
# http://www.apache.org/lice... |
#!/usr/bin/env python2
CHANNEL_FREQUENCIES = {
1: 2412,
2: 2417,
3: 2422,
4: 2427,
5: 2432,
6: 2437,
7: 2442,
8: 2447,
9: 2452,
10: 2457,
11: 2462,
12: 2467,
13: 2472,
36: 5180,
40: 5200,
44: 5220,
48: 5240,
52: 5260,
56: 5280,
60: 5300,
64: 5320,
100: 5500,
104: 5520,
108: 5540,
112: 5560
}
D... |
# Runtime: 56 ms, faster than 52.34% of Python3 online submissions for Richest Customer Wealth.
# Memory Usage: 14.2 MB, less than 61.78% of Python3 online submissions for Richest Customer Wealth.
# https://leetcode.com/submissions/detail/591520867/
class Solution:
def maximumWealth(self, accounts: List[List[int]]... |
# Copyright (c) 2013, Craft and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
columns = get_columns()
sales_data = frappe.db.sql('''select
'Customer' as party_type,
... |
from pythonforandroid.toolchain import PythonRecipe, shprint, current_directory, ArchAndroid
from os.path import exists, join
import sh
import glob
class PySDL2Recipe(PythonRecipe):
version = '0.9.3'
url = 'https://bitbucket.org/marcusva/py-sdl2/downloads/PySDL2-{version}.tar.gz'
depends = ['sdl2']
rec... |
######################################################################################
# Author: Srijan Verma, BITS Pilani, India #
# Code developed in Sirimulla Research Group (http://sirimullaresearchgroup.com/) #
# University of Texas at El Paso, Tx, USA ... |
# -*- coding: utf-8 -*-
"""
This code is auto generated from troposphere_mate.code_generator.__init__.py scripts.
"""
import sys
if sys.version_info.major >= 3 and sys.version_info.minor >= 5: # pragma: no cover
from typing import Union, List, Any
import troposphere.cloudwatch
from troposphere.cloudwatch impor... |
from math import sqrt, ceil
r, x, y, nx, ny = map(int, input().split())
print(ceil(sqrt((nx - x)**2 + (ny - y)**2) / (2*r)))
|
import json
from json import JSONDecodeError
from urllib.parse import quote
import requests
class RestClient:
"""
Use this class to communicate with otto pi navigator
"""
def __init__(self, url=None):
self.end_point_url = 'http://localhost/' if url is None else url
def post(self, path, d... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 19 22:47:23 2015
@author: Joakim
Python version: 3.4.1
Reads a website, determines wheter a package is old or new.
If package is old, downloads a newer one.
Else, does nothing.
NOTE:
This is a raw version, it does not work in conjunction with other codes.
Yet.
"""
i... |
import copy
from .utils import print_json
'''
Prints out websites list with fixed data
'''
def task_three(websites):
index = 0
incorrect_elements = list()
for website in websites:
try:
if 'https://' in website['url'] and website['secure'] == False:
website['secure'] = T... |
import auto_derby
from auto_derby import single_mode
class Plugin(auto_derby.Plugin):
"""Earn second name `努力の天才`"""
def install(self) -> None:
class Training(auto_derby.config.single_mode_training_class):
def score(self, ctx: single_mode.Context) -> float:
ret = super().s... |
supervised_learning = False
options = dict(requires_training_frame=False)
def class_extensions():
@staticmethod
def from_file(file=str):
"""
Creates new Generic model by loading existing embedded model into library, e.g. from H2O MOJO.
The imported model must be supported by H2O.
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-15 20:30
from __future__ import unicode_literals
from django.db import migrations, models
import profiles.util
class Migration(migrations.Migration):
dependencies = [
('profiles', '0023_remove_profile_has_profile_image'),
]
operati... |
#def fonksiyon():
# a=5
# print(a)
#fonksiyon()
#a=10
#def fonksiyon():
#a=5
#print(a)
#fonksiyon()
#print(a)
a=5
def fonksiyon():
global a
a=2
print(a)
fonksiyon()
print(a)
|
# coding: utf-8
"""
NetBox API
API to access NetBox # noqa: E501
OpenAPI spec version: 2.8
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class VirtualMachineInterface(object):
"""NOTE: This class is auto generated ... |
from tqdm import tqdm
import torch
from torch.utils.data import DataLoader
from language.utils.log import get_logger
logger = get_logger()
class Evaluator:
def __init__(self, evaluator_cfg, val_dataset):
"""
:param evaluator_cfg: dict, evaluator config.
:param val_dataset: torch datase... |
from datetime import date
from dateutil.relativedelta import relativedelta
from unittest import TestCase
from todone.parser.format import (
ApplyFunctionFormat,
DateFormat,
PassthroughFormat,
)
class TestPassthroughFormat(TestCase):
def test_values_are_left_untouched(self):
formatter = Passth... |
import os
def get_last_modified(directory):
if os.path.isfile(directory):
return os.path.getmtime(directory)
else:
return None
# does not check for circular dependencies
def _recurse_dependency_list(project_dir, dependency_dict, files_to_check):
if files_to_check:
for file in fil... |
# coding=utf-8
# Copyright 2019 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 or agreed to ... |
import boto3
aws_ebs_client = boto3.client('ebs')
|
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 16 17:21:49 2021
@author: suhar
"""
# Regresyon genelde tahmindir,
# x bağımsız, y bağımlı
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Linea... |
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
"""This demo connects to a magic light and has it do a colorwheel."""
from rainbowio import colorwheel
import adafruit_ble
import _bleio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
fro... |
import math
PI = math.pi
E = math.e
input = [1, 2, 3, 4]
input_len = len(input)
L = 1
M = input_len
root = math.floor(math.sqrt(input_len))
for i in range(root, 0, -1):
if input_len % i == 0:
L = i
M = int(input_len / i)
break
input_2d = []
output_2d = []
for i in range(L):
input_2d.a... |
# coding: utf8
import asyncio
import logging
import time
from copy import deepcopy
from typing import List
import pywikibot
from pywikibot import output
from api import entryprocessor
from api.config import BotjagwarConfig
from api.model.word import Entry
from api.output import Output
from api.servicemanager import D... |
from ... import Printable
from . import FieldType
class FieldValue(Printable):
field_value: None
ratio: 0
count: 0
next_field: FieldType
def get_field_value(self):
return self.field_value
|
"""
Script that perform the first-level analysis of a dataset of the FIAC
Last updated by B.Thirion
Author : Lise Favre, Bertrand Thirion, 2008-2009
"""
import os
from configobj import ConfigObj
from os.path import join
import glob
import GLMTools
import Contrast
# ---------------------------------------------------... |
import gc
import time
from contextlib import contextmanager
from unittest import mock
import objgraph
from dagit.subscription_server import DagsterSubscriptionServer
from dagster import execute_pipeline, pipeline, solid
from dagster.core.test_utils import environ, instance_for_test
from dagster.core.workspace.context ... |
import pygame
import pygame.freetype
class Keys:
def __init__(self):
"""Stores the state of a keyboard"""
self.up = False
self.left = False
self.down = False
self.right = False
self.shift_up = False
self.shift_down = False
class SteeringWheel:
def __in... |
"""
Example code for using Elpis/Kaldi from Python
Start Elpis Docker container, share a volume containing your dataset, e.g.:
docker run --rm -it -p 5001:5001/tcp \
-v ~/sandbox/datasets:/datasets \
-v ~/sandbox/state:/state \
-v ~/sandbox/elpis:/elpis \
--entrypoint /bin/zsh \
coedl/elpis:latest
Change d... |
from typing import TypeVar, Type, BinaryIO
from PIL import Image as PImage
from sprite_unpack.types import Color, Box
ImageType = TypeVar("ImageType", bound="Image")
class Image:
image: PImage
def __init__(self, image: PImage) -> None:
self.image = image.convert("RGBA")
self.pix_data = sel... |
# import cryptography
import argparse
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
def rsa_gen_key(keysize:int):
priv= rsa.generate_pr... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
import os
import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
login_manager = LoginManager()
login_manager.init_app(app)
app.config.from_object(os... |
#
# Copyright (c) 2017 GigaSpaces Technologies Ltd. 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
"""
Generate different flavors of input assembly for testing.
"""
import os.path
import itertools
from common import set_basename, gcc, disasm, grep, strip_binary, find_address
set_basename(os.path.basename(__file__))
for gdb, pic, strip in itertools.product([False, True],
... |
from zope.interface import implementer
from zope.component.interfaces import IObjectEvent
class IPreRequestProcessingEvent(IObjectEvent):
""" notify before the request is processed and
before the transaction is beginning.
"""
@implementer(IPreRequestProcessingEvent)
class PreRequestProcessingEvent(o... |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# SQLALCHEMY_DATABASE_URL = "mysql+mysqlconnector://root:123456@192.168.1.24:3306/sql_alembic?charset=utf8"
# SQLALCHEMY_DATABASE_URL = "mysql+mysqlclient://root:123456@192.168.1.24:3306... |
import random
# For the lab, complete modexp(), RSA_enc(), and RSA_dec().
# HW 2 will allow you to submit the fully completed code from the lab,
# as well as egcd(), mulinv(), and keygen(), for extra credit on the
# assignment.
# You must work independently since this assignment will be part of HW 2.
# te... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.