content stringlengths 5 1.05M |
|---|
import requests
from bs4 import BeautifulSoup
from pprint import pprint
url="https://www.flipkart.com/search?q=mi%20phone&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off"
page=requests.get(url)
soup=BeautifulSoup(page.text,"html.parser")
flifkart=[]
def scrap_flifkart_data():
main_div = soup.... |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
out_dir = '../../plots/time-series/'
in_dir_bases = ['re-simulations','re-simulations-nonsocial','re-processed']
non_social_dir = 're-simulations-nonsocial'
games = ['2015-01-30-20... |
import re
from bs4 import BeautifulSoup
from urllib.request import urlopen as requests
class Equake(object):
def __init__(self):
self.url = "http://irsc.ut.ac.ir/"
self.content = None
def request(self):
try:
r = requests(self.url)
except Exception as e:
... |
""" This module has functions for liquid layer detection.
"""
import numpy as np
import numpy.ma as ma
import scipy.signal
from cloudnetpy import utils
from cloudnetpy.constants import T0
def ind_base(dprof, p, dist, lim):
"""Finds base index of a peak in profile.
Return the lowermost index of profile where ... |
# Copyright 2013-2021 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)
from spack import *
class Mpileaks(AutotoolsPackage):
"""Tool to detect and report leaked MPI objects like MPI_Reque... |
from plugins.base.config_model import ConfigOperator
from .models import Configuration
import pa
import json
class DBConfigManager(ConfigOperator):
@staticmethod
def load(config_name):
try:
config = Configuration.query.filter_by(config_name=config_name).first()
if config is No... |
import select, socket, json, threading, random, discord, re
from os import path, devnull, system, remove
from sys import stdout, __stdout__
from time import sleep, time
from typing import Callable
from requests.models import Response
class ValidationError(Exception):
"""Get's raised, when validation failes"""
... |
"""
Custom implementations for the Thorlabs Kinesis SDK.
"""
import time
from msl.qt import (
QtCore,
Signal,
)
from msl.equipment.resources.thorlabs import (
MotionControl,
MotionControlCallback,
)
from . import BaseEquipment
from .. import logger
_build_device_list = True
def build_device_list():... |
# Generated by Django 3.1.1 on 2020-11-28 15:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('visitors', '0017_auto_20201127_0024'),
]
operations = [
migrations.AlterField(
model_name='visitor',
name='date',
... |
#!/usr/bin/env python
import hail as hl
from gnomad.sample_qc.ancestry import pc_project
MT_PATH = "gs://"
PCA_LOADINGS_PATH = "gs://covid19-hg-public/pca_projection/hgdp_tgp_pca_covid19hgi_snps_loadings.ht"
SAMPLE_FIELD_NAME = "s"
OUTPATH = "gs://"
def project_individuals(pca_loadings, project_mt):
"""
Proj... |
# !/usr/bin/env python
"""
HTTP C&C server for synchronization management for Storj GUI
"""
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from synchronization_core import SyncObserverWorker
import threading
SYNC_SERVER_PORT = 8234
sync_observer_worker = SyncObserverWorker()
class StorjSyncServerHandl... |
import json # Used for json databases and data storing
import os # Reads majority of files
import discord # Using Pycord
from discord.ext import commands
from utils import Reddit
####### Used Flags ########
intents = discord.Intents()
intents.messages = True
intents.bans = True
intents.guilds = True
intents.reacti... |
import math
import sys
from lxml import etree
from geopy import distance
GPX_NAMESPACE = 'http://www.topografix.com/GPX/1/0'
GROUNDSPEAK_NAMESPACE = 'http://www.groundspeak.com/cache/1/0/1'
NAMESPACES = { 'gpx': GPX_NAMESPACE }
def parse_gpx(gpx, latitude, longitude, radius):
xml = etree.parse(gpx)
for wpt in x... |
WIDTH=800
HEIGHT=800
BOARD_SIZE=20
ROW_WIDTH=WIDTH//BOARD_SIZE
COL_HEIGHT=HEIGHT//BOARD_SIZE
DELAY_TIME=0.1
DEST_COLOR=(244,220,176)
ORIGIN_COLOR=(243,202,127)
PATH_COLOR=(118,194,177)
NEIGHBOUR_COLOR=(32,172,142)
WALL_COLOR=(240,176,56)
BG_COLOR=(4,54,93)
LINE_COLOR=(15,79,130) |
#!/usr/bin/env python
from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4 import Qt
import PyQt4.Qwt5 as Qwt
import numpy as np
from datetime import datetime as date
import sys
from az_QwtDial import *
from el_QwtDial import *
import time
class main_widget(QtGui.QWidget):
def __init__(self):
supe... |
##############################################################################
#
# Mahnoor Anjum
# manomaq@gmail.com
#
# References:
# SuperDataScience,
# Official Documentation
#
#
##############################################################################
# Importing the libraries
import... |
import pathlib
import torch
from sklearn.svm import SVC
import numpy as np
import torch.nn as nn
from sklearn.ensemble import RandomForestClassifier
import torch.optim as optim
from sklearn.decomposition import PCA
import pandas as pd
from torch.optim import lr_scheduler
from torch.utils.data import DataLoader
from tor... |
from pavilion import arguments
from pavilion import commands
from pavilion import config
from pavilion import module_wrapper
from pavilion import plugins
from pavilion.result import parsers
from pavilion import system_variables
from pavilion import expression_functions
from pavilion.test_config import variables
from pa... |
import pytest
from castoredc_api_client import CastorException
from castoredc_api_import.import_data import import_data
class TestImportSurvey:
"""Tests uploading data to Castor Surveys."""
def test_import_survey_value_success(self, import_study):
"""Tests if uploading value data is successful"""
... |
#
# PySNMP MIB module BLUECOAT-SG-AUTHENTICATION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BLUECOAT-SG-AUTHENTICATION-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:22:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ... |
import numpy as np
import sys
import os
import asyncio
from collections import OrderedDict
from caproto.server import ioc_arg_parser, run, pvproperty, PVGroup
from caproto import ChannelType
import simulacrum
import zmq
from zmq.asyncio import Context
L = simulacrum.util.SimulacrumLog(os.path.splitext(os.path.basename... |
"""
Benchmarking and performance tests.
"""
import pytest
from pluggy import HookspecMarker, HookimplMarker, PluginManager
from pluggy._hooks import HookImpl
from pluggy._callers import _multicall
hookspec = HookspecMarker("example")
hookimpl = HookimplMarker("example")
@hookimpl
def hook(arg1, arg2, arg3):
ret... |
#!/usr/bin/python3
# Copyright 2021. FastyBird s.r.o.
#
# 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 re... |
"""
ccc_client entrypoint script
"""
import ccc_client.cli
if __name__ == "__main__":
ccc_client.cli.cli_main()
|
print('Today is {}. It is a {} day! It is the {} day of the week'.format('Monday', 'Nice', 1))
|
from loopfield._loopfield import *
|
from copy import deepcopy
import numpy as np
from astropy import units as u
from scipy.ndimage import gaussian_filter1d
from scipy.optimize import least_squares, curve_fit
from tqdm import tqdm
from ..spectrum import SpectrumArrayIO
from .steps import Step
class NormalizeObservationsStep(Step, SpectrumArrayIO):
... |
"""
Base class for models of periodic sources
"""
import numpy as np
from .findpeaks import peakdetect
class PeriodicModeler(object):
"""Base class for periodic modeling"""
def __init__(self, *args, **kwargs):
raise NotImplementedError("PeriodicModeler")
def fit(self, t, y, dy=None, filts=None):
... |
from django.apps import AppConfig
class ServeShinyConfig(AppConfig):
name = 'serve_shiny'
def ready(self):
from . import signals |
# Copyright 1999-2020 Alibaba Group Holding 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 a... |
# noinspection PyShadowingBuiltins,PyUnusedLocal
def compute(x, y):
x = int(0-100)
y = int(0-100)
sum = (x * y)
return(sum)
|
import os
from typing import Callable
from copy import deepcopy
from household_contact_tracing.infection import Infection
from household_contact_tracing.intervention import Intervention
from household_contact_tracing.branching_process_model import BranchingProcessModel
from household_contact_tracing.branching_process_... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2019 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions a... |
from setuptools import setup, find_packages
with open("README.md", "r") as f:
long_description = f.read()
setup(
name="alasan",
version="0.0.1",
author="Lucas Hild",
author_email="contact@lucas-hild.de",
description="Alasan helps you build Alexa skills on AWS Lambda using Python.",
long_de... |
# Copyright 2018-2020 Xanadu Quantum Technologies 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... |
from .vec2 import Vec2
from ctypes import Structure, c_uint
class WeldJointDef(Structure):
""" Represents the definition for a Weld Joint """
_fields_ = [("bodyAId", c_uint),
("bodyBId", c_uint),
("anchor", Vec2)] |
import json
from typing import List, Optional, Dict, Any
from enum import Enum
from steppygraph.serialize import to_serializable
from steppygraph.utils import filter_props
ERROR_MAX_ATTEMPTS_DEFAULT = 2
ERROR_BACKOFF_RATE_DEFAULT = 1.5
ERROR_INTERVAL_S_DEFAULT = 60
JSON_INDENT = 4
DEFAULT_TASK_TIMEOUT = 600
DEFAULT_... |
n, k = map(int, input().split())
ans = 0
while n != 0:
n //= k
ans += 1
print(ans)
|
class SecurityEvents(object):
def __init__(self, session):
super(SecurityEvents, self).__init__()
self._session = session
def getNetworkClientSecurityEvents(self, networkId: str, clientId: str, total_pages=1, direction='next', **kwargs):
"""
**List the security events for a ... |
"""
Define the hooks that are called when an entity changes.
"""
import logging
from fastly import API
from fastly.errors import *
from tiddlyweb.store import HOOKS
from .surrogates import entity_to_keys
LOGGER = logging.getLogger(__name__)
def entity_change_hook(store, entity):
environ = store.environ
... |
import pytest
pytest.register_assert_rewrite("test_lib.gpg_ctx_checks")
|
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
stringToEncrypt = input("Please enter a message to encrypt: ")
stringToEncrypt = stringToEncrypt.upper()
shiftAmount = int(input("Please enter a positive number to encrypt the message\nor enter a negative number to decrypt your code:"))
encryptedString =... |
################################################################################
# Copyright (C) 2014 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
"""
Unit tests for `gate` module.
"""
import numpy as np
from bayesp... |
from data_extractor_dc import TournamentsFullExtractor, MatchesYearlyExtractor
from datetime import datetime
def main():
tournaments_extractor = TournamentsFullExtractor()
tournaments_extractor.extract()
for year in range(1999, datetime.today().year + 1):
matches_extractor = MatchesYearlyExtracto... |
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field, Submit, Button
from django import forms
from app.models import PrintJob
class JobForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(JobForm, self).__init... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-03-30 11:45
from __future__ import unicode_literals
from django.db import migrations
def merge_suspicionreasons(apps, schema_editor):
SuspicionReasons = apps.get_model('changeset', 'SuspicionReasons')
distinct_reasons = SuspicionReasons.objects.all(... |
import sys
import numpy as np
import pandas as pd
#py 101903371.py 101903371-data.csv 1,1,1,2,2 +,-,+,-,+ 101903371-result.csv
def topsis(filename,weights,impacts,output_filename):
#Check if input file is csv
if filename.split(".")[-1]!="csv":
sys.exit("Error: Please enter a valid input csv f... |
import warnings
from django.test import TestCase
from django.template import Template, Context
from django.conf.urls import url
import absoluteuri
def view(request, *args, **kwargs):
pass
urlpatterns = [
url(r'^foo/$', view, name='view'),
url(r'^foo/(?P<foo>\w+)/$', view, name='view'),
url(r'^foo/... |
from django.conf.urls.defaults import patterns, url, include, handler404, handler500
urlpatterns = patterns("",
(r"^tags/$", "tagging_ext.views.index"),
url(r"^profiles/", include("idios.urls")),
)
|
import logging
import coreapi
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from django.db.models import Max
from django.db.models import Q
from rest_framework.response import Response
from rest_framework import status
f... |
"""Command Line Interface for MNE-BIDS."""
# Authors: Teon Brooks <teon.brooks@gmail.com>
# Stefan Appelhoff <stefan.appelhoff@mailbox.org>
#
# License: BSD (3-clause)
import sys
import glob
import subprocess
import os.path as op
import mne_bids
mne_bin_dir = op.abspath(op.dirname(mne_bids.__file__))
valid_c... |
from deepchem.feat.base_classes import MolecularFeaturizer
class RawFeaturizer(MolecularFeaturizer):
"""Encodes a molecule as a SMILES string or RDKit mol.
This featurizer can be useful when you're trying to transform a large
collection of RDKit mol objects as Smiles strings, or alternatively as a
"no-op" fe... |
from moderation.tests.utils.testsettingsmanager import SettingsTestCase
from django import VERSION
from django.core import management
from django.contrib.auth.models import User, Group
from moderation.tests.apps.test_app1.models import UserProfile,\
SuperUserProfile, ModelWithSlugField2, ProxyProfile
from moderatio... |
#!/usr/bin/env python3
# encoding: utf-8
#
# Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved.
#
# This file is part of ewm-cloud-robotics
# (see https://github.com/SAP/ewm-cloud-robotics).
#
# This file is licensed under the Apache Software License, v. 2 except as noted
# otherwise in the LIC... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, print_function, absolute_import,
unicode_literals)
__all__ = ["sample_ball", "MH_proposal_axisaligned"]
import numpy as np
# If mpi4py is installed, import it.
try:
from mpi4py import MPI
MPI = MPI
excep... |
import numpy as np
from absl import app, flags, logging
from absl.flags import FLAGS
import Arena
from MCTS import MCTS
from hex.matrix_hex_game import MatrixHexGame
from hex.graph_hex_game import GraphHexGame
from hex.graph_hex_board import GraphHexBoard
from hex.NNet import NNetWrapper as NNet, FakeNNet, value_from_... |
# MIT License
# Copyright (c) 2019 Otolith- Monterey Bay Aquarium- Conservation Research
# 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 th... |
import requests
import logging
from yarg import json2package
from yarg.exceptions import HTTPError
def fetch_pypi_server(
package: str,
pypi_server: str = "https://pypi.python.org/pypi",
version: str = None,
proxies=None,
):
if pypi_server.endswith("/"):
pypi_server = pypi_server[:-1]
... |
import os
import tempfile
from pathlib import Path
import tensorflow as tf
import pytest
from tensorflow.keras.losses import BinaryCrossentropy
from ramjet.models.single_layer_model import SingleLayerModel, SingleLayerModelWithAuxiliary
from ramjet.photometric_database.derived.toy_database import ToyDatabase, ToyData... |
# -*- coding: utf-8 -*-
#@+leo-ver=5-thin
#@+node:ekr.20050301083306: * @file ../plugins/mod_read_dir_outline.py
#@@first
#@+<< docstring >>
#@+node:ekr.20050301084207: ** << docstring >>
"""
Allows Leo to read a complete directory tree into a Leo outline. Converts
directories into headlines and puts the list of file ... |
import csv
try:
'''
with open('names.csv', 'r') as file:
csv_file = csv.reader(file) # Read the CSV File
# next(csv_file) # Iterate to the Next Line
# for line in csv_file:
# print(line[2])
## Copying Content ... |
# the phenotyping problem is annoying since you end up with 25 binary tasks; assuming that all of your prediction csv's
# are properly prefixed with the name of the task and reside within a test results folder, then this script will
# will evaluate model performance on each task, and aggregate performance
# python2 -u... |
from django.db import models
class DataDeliveryTypeManager(models.Manager):
""" Class representing data delivery type manager """
def get_all(self):
""" Get all data delivery types.
Returns:
All data delivery types.
"""
return self.model.objects.all()
|
import time
from source.databases.GameDB import GameDB
from source.databases.UserDB import UserDB
from source.games.RussianRoulette import RussianRoulette
from source.logger.LogWork import LogWork
from source.static.GameInterface import GameInterface
from source.static.StaticData import StaticData
from source.static.S... |
from django.core import serializers
from django.http import HttpResponse
from django.db.models import Q
from main_app import models
def list(request):
"""Get all user groups."""
if request.method == 'GET':
groups = models.Group.objects.all()
return _reply(groups)
else:
return _repl... |
# encoding: utf-8
from __future__ import unicode_literals
from collections import OrderedDict
from conllu.tree_helpers import TreeNode
data1_tree = [
TreeNode(
data=OrderedDict([
('id', 5),
('form', 'jumps'),
('lemma', 'jump'),
('upostag', 'VERB'),
... |
import json, os, sys, shutil, codecs
toVerifiy = ["config.json", "src/", "src/imgs/", "src/section.html", "src/style.css", "src/template.html"]
print("Verifying everything is good...\n")
# Making sure that every file needed is here
for v in toVerifiy:
if os.path.exists(v):
print("File " + v + " found!")
else:
... |
from py_ecc.fields import (
optimized_bls12_381_FQ2 as FQ2,
)
from py_ecc.optimized_bls12_381 import (
field_modulus as q,
)
G2_COFACTOR = 305502333931268344200999753193121504214466019254188142667664032982267604182971884026507427359259977847832272839041616661285803823378372096355777062779109 # noqa: E501
FQ2_... |
import random
"""Define const graphs"""
EX_GRAPH0 = {0: set([1, 2]), 1: set([]), 2: set([])}
EX_GRAPH1 = {
0: set([1, 4, 5]),
1: set([2, 6]),
2: set([3]),
3: set([0]),
4: set([1]),
5: set([2]),
6: set([])
}
EX_GRAPH2 = {
0: set([1, 4, 5]),
1: set([2, 6]),
2: set([3, 7]),
3: ... |
# Create your views here.
from django.http import HttpResponse
from django.views.decorators.clickjacking import xframe_options_exempt
from django.shortcuts import render_to_response, render
from django import forms
import tempfile
import os
import json
import codecs
import pyxform
from pyxform import xls2json
from py... |
# -*- coding: utf-8 -*-
"""jsonnnnnn derulo
Make sure your json data features jason derulo
Examples:
>>> from jsonderulo import dumps, loads
>>> dumps({"jason": 'derulo'}) # dicts
'{"jason": "derulo"}'
>>> dumps(["data", "more data"]) # lists
'["jason derulo", "data", "more data"]'
>>> loads... |
__all__ = [
"mobject",
"image_mobject",
"tex_mobject",
]
from mobject import Mobject, Group
from point_cloud_mobject import Point, Mobject1D, Mobject2D, PMobject
from vectorized_mobject import VMobject, VGroup
from image_mobject import ImageMobject |
from typing import Optional
from ..database import user_db
from ..helpers import helper
from ..models.exceptions import UserNotValid, UserAlreadyExists, UserNotFound
from ..models.models import Usuario
def register_user(user_: Usuario) -> Usuario:
try:
if helper.validate_registration(user_):
... |
#!/usr/bin/python3
import pdb
import rclpy
import time
from stepper_driver import StepperMotor
import serial
from std_msgs.msg import Int32
from std_msgs.msg import Float64
from std_msgs.msg import UInt16, String
from std_msgs.msg import Float32MultiArray, MultiArrayDimension
from rhino_servo.srv import *
from rclpy.q... |
import torch
import torch.nn as nn
import math
from torch.autograd import Variable
class Embedder(nn.Module):
def __init__(self, vocab_size:int, emb_dim:int):
super().__init__()
self.emb_dim = emb_dim
self.embed = nn.Embedding(vocab_size, emb_dim)
def forward(self, x):
return ... |
#!/usr/bin/env python3
import json
import time
import requests
def main():
while True:
url = 'http://192.168.0.129:8080/data/aircraft.json'
r = requests.get(url)
url = '' # Create a Google Cloud function and update this URL with that value
payload = {'name': 'piawareaircraft', 'da... |
#-------------------------------------------------------------------------------
#
# A simple scatter-plot template defined as a test for the template package.
#
# Written by: David C. Morrill
# (based on the original cp.plot geo_scatter_plot.py file)
#
# Date: 07/30/2007
#
# (c) Copy 2007 by Enthought, Inc.
#
#--... |
n = int(input())
for i in range(n):
pot, a, b = map(int, input().split())
if a < b:
s, l = a, b
else:
s, l = b, a
x = int(((s * pot) / (s + l)) + 0.5)
print(l * x ** 2 + (s * (pot - x) ** 2))
|
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: arista/changecontrol.v1/changecontrol.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message ... |
' July 2020 for Forschungsmodul SoSe 20 at the DDU at TU Darmstadt'
'@author: Paul Steggemann (github@ Paulinos739)'
'This binary classification model predicts the presence of a label (Arhitectural Patterns) in Floor Plan Images. '
""
# Libraries for all
from tensorflow import keras
import os
from typing import Union... |
t = int(input('Digite um nº: '))
for t0 in range(1, 11):
print('{} X {} = {}'.format(t, t0, t * t0))
|
import psycopg2
import os
from faker import Faker
from random import randint
from dotenv import load_dotenv
load_dotenv()
DATABASE = os.getenv('DATABASE')
DATABASE_USERNAME = os.getenv('DATABASE_USERNAME')
DATABASE_PASSWORD = os.getenv('DATABASE_PASSWORD')
# DATABASE_URL = os.environ.get('DATABASE_URL')
con = psycopg... |
from dataclasses import dataclass, field, asdict
from typing import Dict, List, Union, Iterable
import pandas as pd
from pandas import DataFrame
from PyQt5 import QtCore, QtGui, QtWidgets, sip
from PyQt5.QtCore import Qt
import traceback
from functools import wraps
from datetime import datetime
from pandasgui.utility i... |
from aiogram.dispatcher.filters import Text
from aiogram.types import Message
from loader import dp
from markups.text import menu, buttons
from states import Menus
from utilities import count_weekdays_by_month
@dp.message_handler(Text(equals=buttons.first_view_btn.text), state=[Menus.represent_submenu, None])
async ... |
import RPi.GPIO as GPIO
import raspberry_am2320 as AOSONG
import time
DEGREE_SIGN=u"\N{DEGREE SIGN}"
# initialize GPIO
GPIO.setmode(GPIO.BCM)
# read data using pin 17
sensor = AOSONG.AM2320_1WIRE(pin=17)
failure=0
max_fail=0
try:
while True:
try:
(t,h) = sensor.readSensor()
failur... |
# coding=utf8
import tkinter as tk
import asyncio
__all__ = ['run_loop']
async def run_loop(app, interval=0.05):
try:
while True:
app.update()
await asyncio.sleep(interval)
except tk.TclError as e:
if "application has been destroyed" not in e.args[0]:
rais... |
#!/usr/bin/env python3
""" Result """
class Result:
"""
Holds the result of a benchmark job
"""
def __init__(self, trace, stdout, stderr):
self.trace = trace
self.stdout = stdout
self.stderr = stderr
def name(self):
"""
Returns the job name
"""
... |
"""
radish
~~~~~~
The root from red to green. BDD tooling for Python.
:copyright: (c) 2019 by Timo Furrer <tuxtimo@gmail.com>
:license: MIT, see LICENSE for more details.
"""
import click
from radish.extensionregistry import extension
from radish.hookregistry import before, after
@extension
class SyslogWriter:
... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe, unittest
from attendance_extension.attendance_extension.doctype.attendance_settings.tasks import test
class TestAttendance(unittest.TestCase):
def test_attendance... |
import re
import requests
import pandas as pd
from collections import OrderedDict
from cov19.collect import DataCollector
class Austria(DataCollector):
provinces = {
'Burgenland': {'short_name': 'BL', 'search_pattern': r'^Bgl'},
'Carinthia': {'short_name': 'K', 'search_pattern': r'^Kt'},
... |
from ormar import ModelMeta
from poapbot.db import metadata, database
class BaseMeta(ModelMeta):
metadata = metadata
database = database
from .event import Event, EventCreate, EventUpdate
from .attendee import Attendee, AttendeeCreate
from .admin import Admin, AdminCreate
from .claim import Claim, ClaimCreat... |
import argparse
import coremltools as ct
from coremltools.models import MLModel
import json
import numpy as np
from pathlib import Path
from PIL import Image, ImageDraw
# Copied from: https://github.com/AIZOOTech/FaceMaskDetection/blob/master/utils/anchor_generator.py
def generate_anchors(feature_map_sizes, anchor_si... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-12 20:52
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('share', '0033_merge_20170509_1710'),
]
operations = [
migrations.CreateModel(... |
#!/usr/bin/env python3
__author__ = 'mgooch'
import click
import sys
@click.command(help="Collect Unique entries from first two columns of util file")
@click.option('--maf', type=click.File('r'), required=True, help="file to collect names from")
@click.option('--out', type=click.File('w'), required=True, help="file t... |
"""
Utilities for working with datasets in
`VOC format <http://host.robots.ox.ac.uk/pascal/VOC>`_.
| Copyright 2017-2020, Voxel51, Inc.
| `voxel51.com <https://voxel51.com/>`_
|
"""
import logging
import os
import jinja2
import eta.core.utils as etau
import fiftyone as fo
import fiftyone.constants as foc
import fif... |
from kong.executor import SerialExecutor
def test_SerialExecutor():
ex = SerialExecutor()
results = []
func = lambda n: results.append(n)
f = ex.submit(func, 1)
assert results == [1]
assert f.exception() is None
f = ex.submit(func, 42)
assert results == [1, 42]
assert f.excepti... |
"""
Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?
"""
from typing import List, Optional
from .utils import TreeNode
class Solution1:
def... |
import os
import pydocumentdb.document_client as document_client
import sys, traceback
from azure.mgmt.cosmosdb import CosmosDB
from azure.common.credentials import ServicePrincipalCredentials
from .seed_data import SeedData
# documentation for pydocument https://github.com/Azure/azure-documentdb-python/blob/master/s... |
# For logspace definitions
import numpy as np
# Clustering definitions
from sklearn.cluster import (
AffinityPropagation,
Birch,
KMeans,
MiniBatchKMeans,
MeanShift,
)
# Classifier definitions
from sklearn.svm import LinearSVC, NuSVC, SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 1 16:27:42 2020
@author: bs15ansj
"""
import tempfile
from subprocess import PIPE, Popen
import os
amino_acids = ['ALZ', 'ARZ', 'ASY', 'ASX', 'CYY', 'GLX', 'GLW', 'GLV', 'HIZ', 'HIY', 'HIX', 'ILZ', 'LEZ', 'LYY', 'MEZ', 'PHZ', 'PRZ', 'SEZ', 'THZ', ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.