content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import sys, textwrap, bisect
from ..util import TerminalColors256
class TaggedTextDocument(object):
"""
Class representing a document as a list of TaggedTextBlocks
"""
def __init__(self, blocks=None):
self.blocks = [] if blocks is None else blocks
def __repr__(self):
return '\n\n'... | python |
def for_Q():
for row in range(7):
for col in range(6):
if ((col==0 or col==4) and (row!=0 and row!=6)) or (col>0 and col<4) and (row==0 or row==6) or (row>2 and row-col==1):
print("*",end=" ")
else:
print(end=" ")
print()
def while_Q... | python |
#!/usr/bin/env python
import os
tags = ["infra"]
try:
with open("/etc/infra/tags", "r") as f:
for line in f.readlines():
tags.append(line.strip())
except IOError:
pass
try:
for filename in os.listdir("/etc/infra/tags.d"):
tags.append(filename)
except OSError:
pass
line =... | python |
import os
import numpy as np
import csv
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
import cv2
def extract_samples(samples):
with open('../data/driving_log_processed.csv') as csvfile:
reader = csv.reader(csvfile)
next(reader, None) #this is necessary to s... | python |
#!/usr/bin/env python
from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL import *
import sys
name = 'ball_glut'
def main():
glutInit(sys.argv)
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
glutInitWindowSize(400,400)
glutCreateWindow(name)
glClearColor(0.,0.,0.,1.)
... | python |
#!/usr/bin/python
# encoding: utf-8
from logicbit.logic import *
from threading import Thread
import time
# Author Cleoner S. Pietralonga
# e-mail: cleonerp@gmail.com
# Apache License
class Clock(Thread):
def __init__(self, Method, Frequency=1, Samples=1):
Thread.__init__(self)
self.__th_clk = Tr... | python |
import sys
# TODO 4 change the exit code
sys.exit (120)
| python |
from keras.models import Sequential, load_model
from keras.layers import ConvLSTM2D, MaxPooling3D, Dense, TimeDistributed, Flatten
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
import pandas as pd
import tensorf... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Chris Griffith"
from pathlib import Path
import pkg_resources
name = "AV1 (SVT AV1)"
requires = "libsvtav1"
video_extension = "mkv"
video_dimension_divisor = 8
icon = str(Path(pkg_resources.resource_filename(__name__, f"../../data/encoders/icon_svt_av1.png"... | python |
"""
1) find the client with the highest aggregate amount of purchase
"""
from config import *
x = purchase.groupby(['cid'])['amount'].sum()
x = x.reset_index()
x = x.rename(columns=dict(amount='total_purchase'))
printn(x, 'grouped')
max_purchase = x.total_purchase.max()
printn(max_purchase, 'max purchase')
mask = x.... | python |
from typing import Any, Tuple
import torchvision.datasets as datasets
from torch.utils.data import Dataset
class MNISTDataset(Dataset):
"""
`MNIST <http://yann.lecun.com/exdb/mnist/>`_ Dataset. Built using TorchVision Dataset class.
Args:
transform (callable, optional): A function/transform that ... | python |
import pandas as pd
series = pd.Series([21, 23, 56, 54])
print(series)
print(series.index)
print(series.values)
print(series.dtype)
brands = ['BMW', 'Jaguar', 'Ford', 'Kia']
quantities = [20, 10, 50, 75]
series2 = pd.Series(quantities, index=brands)
print(series2)
# Access via index
print(f'series[1]: {series[1]}')... | python |
# iban.py - functions for handling Spanish IBANs
# coding: utf-8
#
# Copyright (C) 2016 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the Licens... | python |
from sklearn.datasets import *
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import OneHotEncoder, StandardScaler
import numpy as np
import matplotlib.pyplot as plt
from net import Net
from dataloader import train_loader
from functional impo... | python |
from rdflib import Literal, XSD
from rdflib.plugins.sparql.evalutils import _eval
from rdflib.plugins.sparql.operators import numeric
from rdflib.plugins.sparql.datatypes import type_promotion
from rdflib.plugins.sparql.compat import num_max, num_min
from decimal import Decimal
"""
Aggregation functions
"""
def _... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 1 10:13:27 2019
@author: adamreidsmith
"""
'''
ManifoldNet neural network based of an algorithm presented here:
https://arxiv.org/abs/1809.06211
Trains on SO(3) matrices.
'''
import torch
import numpy as np
from torch import nn
from torch.nn... | python |
#! /usr/local/bin/python3
"""Secrets generator."""
import argparse
import base64
import hashlib
import secrets
def setup_args_parser():
"""Parse command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
'-l',
choices=[256, 512, 1024, 2048, 4096],
help='R... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-09-25 12:17
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('content... | python |
import pandas as pd
from pathlib import Path
import datetime
df = pd.read_csv(Path('Data Collection/Data/final_data.csv'), parse_dates=['date_local'])
# df['date_local'] = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in df['date_local']]
df.sort_values(by=['date_local'], inplace=True)
df['New Cases'] = df.gr... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from app.comm.psql_wrapper import PostgresqlWrapper
from app.models.sync_model import SyncModel
class CustomFields(SyncModel):
"""Acts as a client to query and modify information from and to database"""
def __init__(self, db_params: dict, table_names: dict):
... | python |
import os
import tensorflow as tf
from tensorflow.keras.layers import (
Conv2D,
AveragePooling2D,
Flatten,
Dense,
BatchNormalization,
Activation,
Softmax,
add,
)
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import SGD
from tensorflow.keras import backend as... | python |
import torch
import torch.nn as nn
from catalyst.contrib.models import SequentialNet
from catalyst.contrib.modules import LamaPooling
class StateNet(nn.Module):
def __init__(
self,
main_net: nn.Module,
observation_net: nn.Module = None,
aggregation_net: nn.Module = None,
):
... | python |
from .Connection1 import Connection
| python |
import torch
import numpy as np
import time
import traceback
import logging
from copy import deepcopy
class NoValidResultsError(Exception):
pass
class UnsupportedError(Exception):
pass
# Logger
logger = logging.getLogger(__name__)
algorithm_defaults = {'n_steps': 30,
'executor': Non... | python |
from django.apps import AppConfig
class MovimentacoesConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'movimentacoes'
| python |
"""
- 集爬取、清洗、分类与测试为一体的STAFF采集队列自动化更新组件
- 需要本机启动系统全局代理,或使用“国外”服务器部署
"""
from .sspanel_checker import SSPanelStaffChecker
from .sspanel_classifier import SSPanelHostsClassifier
from .sspanel_collector import SSPanelHostsCollector
__version__ = 'v0.2.2'
__all__ = ['SSPanelHostsCollector', "SSPanelStaffChecker", ... | python |
# ------------------------------------------------------------ Imports ----------------------------------------------------------- #
# System
import os
# Local
from .utils import Utils
from .texts import new_class, new_enum, new_license, new_file, new_flow, gitignore, readme
# ---------------------------------------... | python |
import httpx
from docs_src.tutorial.dependencies.tutorial_001 import app
from xpresso import Dependant
from xpresso.testclient import TestClient
def test_client_injection():
async def handler(request: httpx.Request) -> httpx.Response:
assert request.url == "https://httpbin.org/get"
return httpx.R... | python |
import unittest
from click.testing import CliRunner
from stable_world import errors
from stable_world.script import main
from fixture import CLITest
class Test(CLITest):
def test_main(self):
runner = CliRunner()
obj = self.application_mock()
# User exists
obj.client.token.retur... | python |
import nnabla as nn
import numpy as np
import os
from .identity import IdentityConverter
from .helpers import GraphInfo
class BatchNormalizationFoldedConverter(IdentityConverter):
"""
Single `Convolution -> BatchNormalization` pass is folded into one `Convolution`.
If there is a `Convolution -> BatchNo... | python |
"""
sift image matching then infer the position of tufts.
"""
import numpy as np
import cv2 as cv
import xml.etree.ElementTree as ET
from scipy.spatial.kdtree import KDTree
import os
def parse_xml(xml_path):
"""parse xml file and calculate center point of each bounding box
Args:
xml_path (str): path... | python |
from django.core.management.base import BaseCommand
from optparse import make_option
from django.template.loader import render_to_string
from aspc.sagelist.models import BookSale
from datetime import datetime, timedelta
class Command(BaseCommand):
args = '[max age in days, default: 6*30]'
help = 'expires book... | python |
# These values are used for creating request arguments
# We group them together so they're near each other
# when using --debug
URL = "url"
BRANCH = "branch"
TAG = "tag"
COMMIT = "commit"
COMMITTED_AT = "committed_at"
PULL_REQUEST = "pull_request"
SERVICE = "service"
PROJECT_HOST = "project_host"
PROJECT_OWNER = "proje... | python |
import os
import winshell
class startup():
def __init__(self):
self.startupdirectory()
def startupdirectory(self):
return winshell.startup()
if __name__ == "__main__":
print(startup())
with open(os.path.join(winshell.startup(), 'test.py'), 'w') as file:
file.write('import te... | python |
import logging
import os
from files.user_file_storage import UserFileStorage
from utils import file_utils
RESULT_FILES_FOLDER = 'uploadFiles'
LOGGER = logging.getLogger('script_server.file_upload_feature')
class FileUploadFeature:
def __init__(self, user_file_storage: UserFileStorage, temp_folder) -> None:
... | python |
from enum import Enum
class MetricType(Enum):
Absolute = "absolute"
Relative = "relative" | python |
__author__ = 'Mariusz'
from pyltes import devices
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import math
class Printer:
"""Class that prints network deployment"""
def __init__(self,parent):
self.parent = parent
self.tilesInLine = 100
self.imageMatrixValid = Fa... | python |
import math
def isPrime(n):
if n > 0:
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
return False
def isCirculerPrime(n):
string = str(n)
length = len(string)
for i in range(length):
if not isPrime(n):
... | python |
# -*- coding: UTF-8 -*-
from flask import Blueprint
__author__ = 'longo'
train = Blueprint('train', __name__)
from . import views | python |
from rlalgos.pytorch.mf import dqn as dqn_pytorch, sac as sac_pytorch, td3 as td3_pytorch, \
categorical_dqn as c51_pytorch, qr_dqn as qr_dqn_pytorch
from rlalgos.pytorch.mf.atari import categorical_dqn as c51_pytorch, dqn as atari_dqn_pytorch, \
qr_dqn as atari_qr_dqn_pytorch
from rlalgos.pytorch.offline impor... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import gi
import sqlite3
import zlib
import datetime
testing = True
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
from engineers.mikeUtil import MikeGtk
from widgets.widgets_quiz21 import WidgetsConstructor
from model.model_quiz21 import s... | python |
from loguru import logger
from kirsche.connect import append_connections
import json
class DataViews:
def __init__(self, data) -> None:
if not data:
logger.warning("No data provided!")
self.data = []
else:
self.data = data
@property
def json_full(self):... | python |
class OneLayerActiveScriptGen:
def __init__(self, args):
layernames = args.split(':')
self.lgroups = "app.activeDocument.layerSets.getByName('" + layernames[0] + "')"
if len(layernames) > 1:
for x in range(1,len(layernames)):
self.lgroups = self.lgroups + ".l... | python |
# Python program to check whether a string is numeric.
string = "Cla73829re"
count = 0
string2 = ''
for i in string:
if (i.isnumeric()) == True:
count +=1
else:
string2 +=i
print(string2)
print(count) | python |
KEY_ATTR_MAPPER = {
"GAME_ID": "game_id",
"GAME_DATE_EST": "date",
"HOME_TEAM_ID": "home_team_id",
"VISITOR_TEAM_ID": "visitor_team_id",
"GAME_STATUS_TEXT": "status",
}
class StatsNbaGameItem(object):
"""
Class for game data from stats.nba.com
:param dict item: dict with game data
... | python |
"""Testes para GetUserController"""
from unittest.mock import patch
from pytest import raises
from mitmirror.errors import HttpNotFound, HttpBadRequestError, HttpUnprocessableEntity
from tests.mocks import mock_user
user = mock_user()
def test_handler(get_user_controller, user_repository_spy, fake_user):
"""Tes... | python |
import torch as t
import torch.nn as nn
import torch.nn.functional as F
from warnings import warn
from torch.optim.adam import Adam
from components.reduction.selfatt import BiliAttnReduction
from components.sequence.CNN import CNNEncoder1D
from components.sequence.LSTM import BiLstmEncoder
from utils.training import e... | python |
# coding=utf-8
"""Horner's method for polynomial evaluation in O(n) time Python implementation."""
def horner(poly, x):
result = poly[0]
for i in range(1, len(poly)):
result = result * x + poly[i]
return result
if __name__ == '__main__':
poly = [2, -6, 2, -1]
x = 3
print(horner(poly,... | python |
from .clock import Clock
# H-H M-M S-S
# +-+-+ +-+-+ +-+-+
# 2^3=8 |1|2| |1|2| |1|2|
# 2^2=4 |3|4| |3|4| |3|4|
# 2^1=2 |5|6| |5|6| |5|6|
# 2^0=1 |7|8| |7|8| |7|8|
# +-+-+ +-+-+ +-+-+
def launch():
root = Clock()
root.title("BinaryClock")
root.resizable(... | python |
import base64
import datetime
import json
import logging
import re
from typing import Dict, List
from flask import g, session, url_for
from flask_babel import lazy_gettext as _
from flask_jwt_extended import current_user as current_user_jwt
from flask_jwt_extended import JWTManager
from flask_login import current_user... | python |
#csvsckit tagger
from RecoBTag.CSVscikit.csvscikit_EventSetup_cff import *
from RecoBTag.CSVscikit.pfInclusiveSecondaryVertexFinderCvsLTagInfos_cfi import *
from RecoBTag.CSVscikit.pfInclusiveSecondaryVertexFinderNegativeCvsLTagInfos_cfi import *
from RecoBTag.CSVscikit.pfCombinedSecondaryVertexSoftLeptonCvsLJetTags... | python |
#!/usr/bin/env python
# ---------------------------------------------------------------------------------------------
"""
local/api.py
The API for the example customer support system.
Copyright (c) 2015 Kevin Cureton
"""
# ---------------------------------------------------------------------------------------------
... | python |
# coding: utf-8
"""
InfluxDB OSS API Service.
The InfluxDB v2 API provides a programmatic interface for all interactions with InfluxDB. Access the InfluxDB API using the `/api/v2/` endpoint. # noqa: E501
OpenAPI spec version: 2.0.0
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_... | python |
"""Support for Verisure devices."""
from __future__ import annotations
from contextlib import suppress
import os
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EVENT_HOMEASSISTANT_STOP, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import Con... | python |
from .bert import *
#from .language_model import BERTLM
| python |
# pyLattice.py
"""
class module for the Lattice class to be used with pyNFC
"""
import numpy as np
class Lattice(object):
"""
define the layout and adjacency of the LBM lattice
"""
def __init__(self,Nx,Ny,Nz):
"""
basic constructor
Nx - number of lattice points in ... | python |
import click
import os.path
import src.clipping
import src.anki
@click.command()
@click.option("--clippings", default="", help="path to My Clippings.txt file")
def import_clippings(clippings):
if not os.path.isfile(clippings):
raise click.ClickException("Clippings file not found")
try:
print("... | python |
#! /usr/bin/env python3
# coding: utf-8
from __future__ import annotations
import pytest
from gargbot_3000 import __main__
def test_main():
with pytest.raises((SystemExit, Exception)):
__main__.main()
| python |
import math
from typing import List, Optional
import numpy as np
__all__ = ["line_length", "is_closed", "interpolate", "crop_half_plane", "crop", "reloop"]
def line_length(line: np.ndarray) -> float:
"""Compute the length of a line."""
return float(np.sum(np.abs(np.diff(line))))
def is_closed(line: np.nda... | python |
class Solution:
res_set = set()
def subsetsWithDup(self, nums):
nums = sorted(nums)
return self.subsetsWithDup2(nums)
def subsetsWithDup2(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) == 1:
return [[num... | python |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
# Test case ID : C15096737
# Test Case Title : Verify that a change in the default material library material i... | python |
from django.db import models
from django.contrib.auth.models import User
from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
from django.utils import timezone
import os
STATUS = (
(0, "Draft"),
(1, "Publish"),
(2, "Withdrawn"),
)
RESPONSE = (
(0, "NOT ... | python |
# Generated by Django 2.1.7 on 2019-04-01 09:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0005_auto_20190331_1036'),
]
operations = [
migrations.AddField(
model_name='pictures',
name='ipAddress',
... | python |
import sys
import os
if sys.version_info < (3, 8):
raise ImportError("nanobind does not support Python < 3.8.")
def include_dir() -> str:
"Return the path to the nanobind include directory"
return os.path.join(os.path.abspath(os.path.dirname(__file__)), "include")
def cmake_dir() -> str:
"Return the ... | python |
from typing import Optional, Tuple, List
import tensorflow as tf
import numpy as np
from tensorflow.keras.layers import CuDNNLSTM as LSTM
from tensorflow.keras.layers import Embedding, Dropout
from sacred import Ingredient
from rinokeras.layers import Stack
from .AbstractTapeModel import AbstractTapeModel
lstm_hpar... | python |
from flask import current_app as app
from flask import send_from_directory
@app.route('/')
@app.route('/<path:path>')
def send_file(path = ""):
if("login" in path and "." in path):
return send_from_directory('./hidden/', path)
elif("login" in path):
return send_from_directory('./hidden/', path + "/index.html")
... | python |
'''
Loads the SVHN Datasets.
Note: this uses the 2011 version
Paper: http://ufldl.stanford.edu/housenumbers/nips2011_housenumbers.pdf
Website: http://ufldl.stanford.edu/housenumbers/
'''
import os
import cv2
from scipy.io import loadmat
import glob
import random
import numpy as np
from bunch import Bu... | python |
# Blender import system clutter
import sys
from pathlib import Path
UTILS_PATH = Path.home() / "Documents/python_workspace/data-science-learning"
SRC_PATH = UTILS_PATH / "graphics/l_systems"
sys.path.append(str(UTILS_PATH))
sys.path.append(str(SRC_PATH))
import LSystem
import importlib
importlib.reload(LSystem)
from ... | python |
# example of usage exceptions as break point
class Exitloop(Exception):
pass
try:
while True:
while True:
for i in range(10):
if i > 3:
raise Exception
print('loop3: {}'.format(i))
print('loop2')
print('loop1')
ex... | python |
import functools
from sentry.utils.strings import (
soft_break,
soft_hyphenate,
)
ZWSP = u'\u200b' # zero width space
SHY = u'\u00ad' # soft hyphen
def test_soft_break():
assert soft_break('com.example.package.method(argument).anotherMethod(argument)', 15) == \
ZWSP.join(['com.', 'example.', '... | python |
#!/usr/bin/env python
# encoding: utf-8
"""
A Python interface to the The Echo Nest's web API. See
http://developer.echonest.com/ for details.
"""
import os
from decorators import memoized
import config
import util
class Track(object):
def __init__(self, identifier):
if len(identifier)==18:
s... | python |
class DoubleNode:
def __init__(self, value):
self.value = value
self.next = None
self.previous = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def append(self, value):
if self.head == None:
self.head = Dou... | python |
"""
Test 'RadioRedirect'
"""
from simx.base.testutil import import_assert_functions
import_assert_functions(globals())
from simx.base import TossimBase
from simx.base import Node
from TOSSIM import Tossim
_tossim = Tossim([])
tossim = None
radio = None
a = None
b = None
c = None
def setUp():
global tossim, radi... | python |
# Copyright 2020 The Bazel 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 applicable la... | python |
import numpy as np
"iterative LQR with Quadratic cost"
class iterative_LQR:
"""
iterative LQR can be used as a controller/trajectory optimizer.
Reference:
Synthesis and Stabilization of Complex Behaviors through Online Trajectory Optimization
https://homes.cs.washington.edu/~todorov/papers/TassaI... | python |
from django.apps import AppConfig
class PoemConfig(AppConfig):
name = 'Poem.poem'
verbose_name = 'POEM'
| python |
import random as ra
import matplotlib.pyplot as plt
import numpy as np
overall_max = []
overall_prop = []
for k in range(10000):
peter = []
paul = []
max_peter = 0
prop_count = 0
for i in range(40):
roll = ra.random()
if roll < 0.5:
peter.append(-1)
paul.app... | python |
from django.db import models
from django.contrib.auth.models import User
class Contact(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default='')
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField()
hp_no = ... | python |
"""
Code used by checkviewaccess management _output
"""
from django.conf import settings
from django.contrib.auth import get_user_model
from django.utils import timezone
try:
from django.utils.translation import gettext as _
except:
from django.utils.translation import ugettext as _
from django_roles_access.mo... | python |
# Init
import os
import sys
import platform
import json
import smtplib
import zipfile
import shutil
import logging
import random
import email.mime.text
import email.utils
import email.header
import urllib.request
# Init-Version
version_list = json.loads(open('version.json', encoding = 'utf8').read())
print('Version... | python |
"Exit codes we can use to describe different error conditions programatically."
CONNECTION_ERROR = 1
RESOURCE_MISSING = 2
| python |
import time
from pynamodb.constants import (CAMEL_COUNT, ITEMS, LAST_EVALUATED_KEY, SCANNED_COUNT,
CONSUMED_CAPACITY, TOTAL, CAPACITY_UNITS)
class RateLimiter(object):
"""
RateLimiter limits operations to a pre-set rate of units/seconds
Example:
Initialize a RateLi... | python |
n = int(input())
print(n)
res = (n // 50) * 7
n = n % 50
if n >= 30:
res += 4
res += (res-30)//10
else:
res += res//10
print(res)
| python |
import sys
import csv
import math
from gensim.test.utils import common_texts
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
args = sys.argv
dir = args[2]
vec_dir = args[3]
print("Reading preprocessed test cases ...", file=sys.stderr)
texts = []
with open(args[1]) as table_file:
reader = csv.reader(tab... | python |
import requests ## libreria para hacer el request a los navegadores
from bs4 import BeautifulSoup ## libreria utilizada para parsear el html
from flask import Flask, jsonify ## librerias de flask a utilizar
import os ## libreria para el manejo de files.
import sqlite3 ##
app = Flask(__name__)
DATABASE = '../test/d... | python |
# Author : Relarizky
# Github : https://github.com/relarizky
# File Name : help/exception.py
# Last Modified : 01/25/21, 11:23 PM
# Copyright © Relarizky 2021
class ValueLengthError(Exception):
"""
raised when user input value with invalid length
"""
def __init__(self, message: str) -> None:
... | python |
from setuptools import find_packages, setup
setup(
name='smisc',
version='0.1-alpha',
packages=find_packages(),
author='sakurain',
author_email='1457488119@qq.com',
description='just utils',
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: Apa... | python |
#utils.py
import socket, json
from data import addPoints
import urllib.request
from init import saveData
import cfg
import time, _thread
def openSocket():
s = socket.socket()
s.connect((cfg.HOST, cfg.PORT))
s.send(("PASS " + cfg.PASS + "\r\n").encode('utf-8'))
s.send(("NICK " + cfg.NICK + "\r\n").encod... | python |
import pipe
import DynamicPassword
class DiskOP:
DiskArray = []
VolumeArray = []
def __init__(self,IP,Port,Password):
self.p_Diskpart = pipe.RemotePipe(IP,Port,DynamicPassword.DynamicPassword(Password,8)+"diskpart.exe".encode("GB2312"))
def GetDiskList(self):
CMDresult = self.p_Diskpart.... | python |
#! /usr/bin/python
# $Id: setup.py,v 1.3 2012/03/05 04:54:01 nanard Exp $
#
# python script to build the libnatpmp module under unix
#
# replace libnatpmp.a by libnatpmp.so for shared library usage
from distutils.core import setup, Extension
from distutils import sysconfig
sysconfig.get_config_vars()["OPT"] = ''
syscon... | python |
import time, os, requests, re, csv, time
from lxml import etree
from selenium import webdriver
img_folder = 'D:\\dataset_object_detect\\open_image_dataset\\train_00\\train_00'
img_files = list()
for root, dirs, files in os.walk(img_folder):
for name in files:
file_path = os.path.join(img_folder, name)
... | python |
from picamera import PiCamera
import time
import cv2
import numpy as np
from config import WIDTH, HEIGHT, CHANNEL, MINIMUM_DISTANCE, CP_WIDTH, CP_HEIGHT
from ultrasonic import getDistance
camera = PiCamera()
def getImage():
camera.resolution = (HEIGHT, WIDTH)
errors = False
im = np.empty(( WIDTH, HEIGHT, 3), dtype... | python |
def list_max(input_list):
max_val = input_list[0]
for i in range(1, len(input_list), 1):
if(input_list[i] > max_val):
max_val = input_list[i]
return max_val
list1 = [-2, 1, 2, -10, 22, -10]
max_val = list_max(list1)
print(max_val)
| python |
#!/usr/bin/python
"""
WARNING: This is an automatically generated file.
It is based on the EPW IDD specification given in the document
Auxiliary EnergyPlus Programs - Extra programs for EnergyPlus,
Date: November 22 2013
Do not expect that it actually works!
Generation date: 2014-12-01
"""
from collections import Or... | python |
import xml.etree.ElementTree
import os.path
class FMI3ModelDescription:
fmu_name="unknown"
fmi_version="unknown"
model_name="unknown"
instantiation_token="{0}"
fmu_var_dict=dict()
def parse_model_description( self, fmu_name, fmu_path ):
self.fmu_name=fmu_name
# Parse and store... | python |
"""Build and check configuration for quattor documentation."""
import os
from vsc.utils import fancylogger
from repo import Repo
logger = fancylogger.getLogger()
def build_repository_map(location):
"""Build a repository mapping for repository_location."""
logger.info("Building repository map in %s.", locatio... | python |
import logging
from typing import List
from typing import NamedTuple
from typing import Optional
import phue
log = logging.getLogger(__name__)
#: Maximum hue light brightness
MAX_BRIGHTNESS = 254
LightGroupStatus = NamedTuple('LightGroupStatus', [
('group_id', int),
('is_on', bool),
('brightness', int)... | python |
"""
Tests for the attrdict module
"""
| python |
#
# Copyright (c) 2019 One Identity
#
# 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, di... | python |
#
# PySNMP MIB module ADTRAN-AOS-OVER-TEMP-PROTECTION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-AOS-OVER-TEMP-PROTECTION-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:58:49 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Usi... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.