content stringlengths 5 1.05M |
|---|
from django.contrib import admin
from reports.models import DailyReport ,Cp ,Weather,Wind ,Activity ,Area ,ReportActivity
from account.models import Account ,Discipline
# Register your models here.
admin.site.register(Weather)
admin.site.register(Wind)
admin.site.register(Cp)
admin.site.register(Account)
admin.site.re... |
from aiohttp import web
import json
import pytest
from unittest.mock import Mock
from smashtheque.smashtheque import Smashtheque
from smashtheque.errors import *
from smashtheque.models.character import *
from smashtheque.models.player import *
from smashtheque.models.team import *
# FAKE SERVER
yoshi = {
"id... |
from iqoptionapi.ws.chanels.base import Base
import time
class Get_Balances(Base):
name = "sendMessage"
def __call__(self):
"""
:param options_ids: list or int
"""
data = {"name":"get-balances",
"version":"1.0"
}
self.send_webs... |
import shutil
import unittest
import sys
from pathlib import Path
# give the test runner the import access
pysixdesk_path = str(Path(__file__).parents[2].absolute())
sys.path.insert(0, pysixdesk_path)
from pysixdesk.lib.study_params import StudyParams
from pysixdesk.lib.study_params import set_input_keys
from pysixdesk... |
"""
=============================
The object-oriented interface
=============================
A pure OO (look Ma, no pyplot!) example using the agg backend.
"""
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
fig = Figure()
# A canvas must be manually ... |
# -*- coding:utf-8 -*-
'''
Created on 2015年3月12日
@author: wanhao01
'''
import os
class SpiderFileUtils(object):
'''
deal with file related operations.
'''
def __save_page(self, data, url, outputdir):
'''
save the page content with the specific url to the local p... |
from datetime import datetime, timedelta
import tkinter as tk
import sys
top = tk.Tk()
top.geometry("80x40+300+300")
top.resizable(0, 0)
top.overrideredirect(1)
entry = tk.Entry(top, justify='center')
entry.configure(font=("Times New Roman", 20, "bold"))
entry.pack()
def readTime():
time = input("Current Time: ")
... |
import numpy as np
import servo2
import math
import time
savedir="Camera_Data/"
map_A = np.load(savedir+'servoA.npy')
map_B = np.load(savedir+'servoB.npy')
steps = len(map_A)
wait = 0.3
def vect_to_deg(x, y):
servo_A, servo_B = 0, 0
try:
A = list(map(lambda k: k >= y, map_A)).index(True)-1
if map_A[A] == ... |
import clr
clr.AddReference('RevitAPI')
clr.AddReference('RevitAPIUI')
from Autodesk.Revit.DB import *
app = __revit__.Application
doc = __revit__.ActiveUIDocument.Document
#Firt thing we need to load the family into the doc (insert -> load family)
t = Transaction(doc, 'Create family instance.')
t.Start()
#... |
#
# PySNMP MIB module ACLEXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ACLEXT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:57:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... |
from pyStaticAnalyzer import kernel, checker
dir = 'test_linter/'
k = kernel.ProjectKernel(dir, ignored={'venv', '.idea', '__pycache__'})
# Tests for project kernel
k.print_structure(indent_count=8)
k.print_folder(dir + '1')
k.print_all_asts()
k.print_folder_asts(dir + '1')
k.print_file_ast(dir + '1/11/111/first.py'... |
#####################################################################################
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the root of th... |
"""
"""
import numpy as np
from astropy.utils.misc import NumpyRNGContext
default_desired_logm_completeness = 9.75
__all__ = ('synthetic_logmpeak',)
def synthetic_logmpeak(mpeak_orig, desired_logm_completeness=default_desired_logm_completeness,
nout_max=np.inf, c0=5.5, c1=-0.15,
lowm_fit=11.... |
# -*- coding: utf-8 -*-
import unittest.mock
import pytest
import pycamunda.task
import pycamunda.variable
from tests.mock import raise_requests_exception_mock, not_ok_response_mock
def test_setassignee_params(engine_url):
set_task_assignee = pycamunda.task.SetAssignee(url=engine_url, id_='anId', user_id='anUs... |
print(100>>5+90<<80)
#0 |
#!/usr/bin/python3
"""
Init file that starts the models module
"""
from models.engine.file_storage import FileStorage
from models.base_model import BaseModel
storage = FileStorage()
storage.reload()
|
import pytest
from eth.db.atomic import AtomicDB
from eth.db.backends.level import LevelDB
from eth.tools.db.base import DatabaseAPITestSuite
from eth.tools.db.atomic import AtomicDatabaseBatchAPITestSuite
@pytest.fixture(params=['atomic', 'level'])
def atomic_db(request, tmpdir):
if request.param == 'atomic':
... |
from marshmallow_sqlalchemy import ModelSchema
from marshmallow import fields
from toko.models.proposta_model import PropostaModel
class PropostaSchema(ModelSchema):
class Meta:
model = PropostaModel
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('user_accounts', '0002_auto_20150503_0800'),
('ourcalendar', '0001_initial'),
]
operations = [
... |
import numpy as np
import random
def random_int_matrix(elem, upper, lower = 0):
X = np.array([random.randint(lower, upper)
for _ in range(elem ** 2)])
return np.reshape(X, (elem, elem))
|
import json
from chargebee_v2.model import Model
from chargebee_v2 import request
from chargebee_v2 import APIError
class Download(Model):
fields = ["download_url", "valid_till"]
|
#!/usr/bin/python
#
# Created on Aug 25, 2016
# @author: Gaurav Rastogi (grastogi@avinetworks.com)
# Eric Anderson (eanderson@avinetworks.com)
# module_check: supported
# Avi Version: 17.1.1
#
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the te... |
from covid19_data_analyzer.data_functions.data_utils import (
translate_funkeinteraktiv_fit_data,
)
from covid19_data_analyzer.data_functions.scrapers import ALLOWED_SOURCES
from covid19_data_analyzer.data_functions.analysis.logistic_curve import (
batch_fit_logistic_curve,
)
from covid19_data_analyzer.data_f... |
# -*- coding: utf-8 -*-
import unittest
from google.appengine.ext import testbed
class PalletTestCase(unittest.TestCase):
'''
予報の段階
'''
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.setup_env(
ADDR_FROM='from@example.jp',
... |
import torch
from os import path
from sys import version_info
from collections import OrderedDict
from torch.utils.model_zoo import load_url
# Download the VGG-19 model and fix the layer names
print("Downloading the VGG-19 model")
sd = load_url("https://web.eecs.umich.edu/~justincj/models/vgg19-d01eb7cb.pth")
map = {... |
print("single quote here \'. new line \n double quote here \"")
print("backslash \\");
print("tab \tspace");
print("back \bspace (\\b)");
print("otacl code \133\134");
print("hexa code \x32 \x25");
|
from plotter_utils import smooth, reformat_large_tick_values, csv_to_list, npy_to_list, extrapolate, running_mean
import numpy as np
import os
import matplotlib.cm as cm
import matplotlib.ticker as tick
import matplotlib.pyplot as plt
import csv
import matplotlib
matplotlib.use('TkAgg')
np.set_printoptions(suppress=Tru... |
import discord
import random
import asyncio
import json
import quiz_settings
# notes :
# * the quiz will mess up on the first !q and say the user is wrong.
# it is ok. it goes away after that and doesn't happen often....i think.
# * i added numbers, so this file name kind of doesn't make sense-ish.
# it is... |
import sys
import pandas as pd
training_data = sys.argv[1]
df = pd.read_csv(training_data, sep=' ', header=None)
df = df.rename(
columns={
0: 'baseball_game_on_TV',
1: 'watch_TV',
2: 'out_of_cat_food',
3: 'feed_the_cat'
})
# node baseball
num_days = len(df)
num_baseball = d... |
from django.db.migrations import Migration as BaseMigration, AlterField
from django.db.models import URLField
class Migration (BaseMigration):
dependencies = [
('lookout', '0002_v0_1_2'),
]
operations = [
AlterField(
model_name='report',
name='url',
field=URLField(help_text='The address of the docu... |
from setuptools import setup
setup(
name='amused',
version='0.11.4',
zip_safe=False,
packages=['amused'],
package_data={'': ['*.csv', '*.pickle']},
url='',
license='MIT',
author='Paweł Skórzewski',
author_email='pawel.skorzewski@amu.edu.pl',
description='AMUSED – Adam Mickiewicz... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# A spider example on using reactor.callLater()
# for delays and repetition.
# for scrapy 0.24
import scrapy
from twisted.internet import reactor, defer
from scrapy import Request, log
class Delay(scrapy.Spider):
name = 'delay'
allowed_domains = ["localhost"]... |
"""Gene annotations (gene_annotate module)
This module concatenates previously fetched GDSC1000 files into a
single data frame that can be converted into a BEM and fed into the
ANOVA analysis step of gdsctools.
If needed, this script has the option to convert CNA and
methylation data from their ID values to their ge... |
from threading import Semaphore
from utils.db_connection import DatabaseConnectionBase
class Sequencer:
def __init__(self, db_connection: DatabaseConnectionBase):
self.__db_conn = db_connection
self.__semaphore = Semaphore(value=1)
def get_id(self):
return self.__db_conn.get_id()
... |
class Camera:
"""Project Ledas camera object"""
def __init__(self, path, debug_obj):
self.debug = debug_obj
self.debug.write("Camera: initialized with path '{!s}'".format(path))
def capture(self, timeStamp):
self.debug.write("Camera: capture with timestamp {!s}".format(timeStamp))
... |
#!/usr/bin/env /home/john1990/MGLTools-1.5.6/bin/pythonsh
#
#
#
# $Header: /opt/cvs/python/packages/share1.5/AutoDockTools/Utilities24/prepare_flexreceptor4.py,v 1.7 2009/10/09 18:19:00 rhuey Exp $
#
import os
from MolKit import Read
from MolKit.protein import ProteinSet, ResidueSet
from MolKit.molecule import BondS... |
from scipy.optimize import fmin_cobyla
import openopt
from openopt.kernel.setDefaultIterFuncs import *
from openopt.kernel.ooMisc import WholeRepr2LinConst, xBounds2Matrix
from openopt.kernel.baseSolver import baseSolver
from numpy import inf, array, copy
#from openopt.kernel.setDefaultIterFuncs import SMALL_DELTA_X, ... |
# Copyright 1999-2018 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... |
import difflib
print difflib.SequenceMatcher(
None, "1 2 3 4", "12 3 4").ratio()
|
import argparse
import os
import sys
import torch
from download import write_line_by_line
from transformers import (
AutoConfig, AutoModelWithLMHead, AutoTokenizer,
DataCollatorForLanguageModeling, set_seed,
TextDataset, Trainer, TrainingArguments)
# used in both finetune and generate_captions so make it g... |
"""This module contains the general information for AdaptorHostPort ManagedObject."""
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class AdaptorHostPortConsts:
OPER_STATE_ACCESSIBILITY_PROBLEM = "accessibility-problem"
OPER_STATE_AUTO... |
from functools import lru_cache
from typing import Any, Optional
from rest_framework.exceptions import AuthenticationFailed, NotAuthenticated, ValidationError
from rest_framework.fields import HiddenField, empty
from rest_framework.request import Request
from .tokens import AccessToken
__all__ = [
"A... |
from datetime import datetime, timedelta
from pymongo import MongoClient
import pickle
import zlib
import random
from pprint import pprint
from pymongo.errors import BulkWriteError
class MongoCache:
def __init__(self, client=None, expires=-1):
self.client = MongoClient('mongodb://user:password@127.0.0.1:2... |
#
# Python SDK for Xooa
#
# Copyright 2018 Xooa
#
# 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 t... |
import logging
from discord.ext import commands
from discord.ext.commands import Cog, Context
from xythrion.bot import Xythrion
from xythrion.utils import DefaultEmbed
log = logging.getLogger(__name__)
class Warnings(Cog, command_attrs=dict(hidden=True)):
"""Warning the user about specific actions taken."""
... |
import pytest
# СНАЧАЛА ПРО SCOPE!
# @pytest.fixture(autouse=True)
# def function_fixture(request):
# print(f"\n Hello from {request.scope} fixture!")
# def fin():
# print(f"\n Finalize from {request.scope} fixture!")
# request.addfinalizer(fin)
#
# @pytest.fixture(scope="class", autouse=True)
# ... |
#!/usr/bin/env python3
# Different representation, where we only save the counts of fish
# with certain days to breed
fish = [0 for i in range(9)]
with open('input', 'r') as data:
parse = data.read().split(',')
for x in parse:
fish[int(x)] += 1
def simulate(fish):
# make a real copy!
old_fish ... |
import re
from pandas import read_html
state_names = [
"Alabama",
"Alaska",
"Arizona",
"Arkansas",
"California",
"Colorado",
"Connecticut",
"Delaware",
"District of Columbia",
"Florida",
"Georgia",
"Hawaii",
"Idaho",
"Illinois",
"Indiana",
"Iowa",
"... |
from latexpp.fix import BaseFix
class AddPreamble(BaseFix):
r"""
Include arbitrary LaTeX code before ``\begin{document}``.
Arguments:
- `preamble`: the additional code to include before ``\begin{document}``.
"""
def __init__(self, preamble=None, fromfile=None):
super().__init__()
... |
import os
import re
import requests as req
# Reading the pdf
# os.system('less Springer\ Ebooks.pdf >> pdfDecode.txt')
##Decoding of pdf may vary system to system. So I have provided it.
## catching Source url
file=open('pdfDecode.txt','r')
contents=file.read()
urls=re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pandas as pd
import numpy as np
import requests
from lxml import etree
headers = {
'authorization':' ', #括号中填上你的authorization
'User-Agent':' ', #括号中填上你的User-Agent
}
url = "https://otcbtc.com/"
# r = requests.get(url,headers = headers).text #加上header
r = reque... |
# Copyright 2020 University of New South Wales, University of Sydney, Ingham Institute
# 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
# Unle... |
from common import common, database
import json
import os
logger = None
def handler(event, context):
global logger
args = common.get_parameters(event, ["table-name"])
logger = common.initialise_logger(args)
connection = database.get_connection(args)
script_dir = os.path.dirname(__file__)
... |
import pytest
@pytest.mark.int
@pytest.mark.vagrant
def test_int_vagrant(helpers):
vagrant_dir = 'examples/vagrant'
helpers.run(
'vagrant up',
cwd=vagrant_dir,
expected_lines=['Machine booted and ready!'],
)
helpers.run(
'pyinfra @vagrant vagrant.py',
cwd=vagr... |
from dataclasses import dataclass
from bindings.csw.linear_ring_type import LinearRingType
__NAMESPACE__ = "http://www.opengis.net/gml"
@dataclass
class LinearRing(LinearRingType):
class Meta:
namespace = "http://www.opengis.net/gml"
|
import logging
import tenacity
import time
import os
import ynab_client
import n26.api
import n26.config
import pandas as pd
from datetime import datetime
from src.paths import get_n26_token_data_filepath
from src.config import load_ynab_config, get_n26_account_config
from src.exceptions import (
BudgetNotFoundE... |
import os
import subprocess
import shutil
import yaml
import re
import sys
import time
def clone_config_repo(**kwargs):
"""
Helper function to clone git repo
"""
if "git_username" not in kwargs.keys():
kwargs["git_username"] = ""
if "git_password" not in kwargs.keys():
kwargs["git... |
import sys
import string
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('input', type=str)
parser.add_argument('out', type=str)
parser.add_argument('--duration', type=float, required=True)
args = parser.parse_args();
with open(args.input) as f:
t = string.Template(f.read())
... |
# Different integrator splittings have different maximum tolerated timesteps that achieve the same error threshold
import os
import numpy as np
from simtk import unit
from benchmark import DATA_PATH
from benchmark.testsystems import dhfr_constrained
from benchmark.experiments.driver import ExperimentDescriptor, Expe... |
"""4- Escribir una funcion que reciba un string con nombre y apellido y devuelva un string con el nombre y apellido pero con capitalizacion(primera letra mayuscula)."""
def myfunction(fullname):
capitalizeName = fullname
capitalizeName = capitalizeName.title()
return capitalizeName |
import sys
import re
import os
PATH = os.path.abspath(sys.stdin.read()[:-1])
NEW_PATH = '/mnt/datos/Camila/A-nowcasting-model-for-Medellin-city/train/images/'
#'/mnt/datos/Camila/A-nowcasting-model-for-Medellin-city/train/images/train/'
mode = 'test' if 'test' in PATH else 'train'
fil = open(PATH, 'r').read()
reg1... |
"""Module for reading and processing Vaisala / Lufft ceilometers."""
from itertools import islice
from typing import Optional, Union
import netCDF4
from cloudnetpy import output
from cloudnetpy.instruments.cl61d import Cl61d
from cloudnetpy.instruments.lufft import LufftCeilo
from cloudnetpy.instruments.vaisala impor... |
import os
import tensorflow as tf
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np
import onnxruntime
import tf2onnx
import onnxruntime as rt
# image pr... |
# -*- coding: utf-8 -*-
#
from .surface_base import SurfaceBase
class Disk(SurfaceBase):
def __init__(self, x0, radius0, radius1=None, char_length=None):
super(Disk, self).__init__()
assert len(x0) == 3
if radius1 is not None:
assert radius0 >= radius1
self.x0 = x0
... |
from flask import Flask, request, render_template, g, url_for, jsonify, flash, redirect
import requests
from requests.auth import HTTPBasicAuth
from datetime import datetime, timedelta
app = Flask(__name__)
auth = ("admin", "admin")
@app.route("/", methods=["GET"])
def homepage():
""" redirect to index """
re... |
'''
John has collected various rocks. Each rock has various minerals embeded in it. Each type of mineral is designated by a lowercase letter in the range . There may be multiple occurrences of a mineral in a rock. A mineral is called a gemstone if it occurs at least once in each of the rocks in John's collection.
Give... |
#!/usr/bin/env python
#
# Jiao Lin <jiao.lin@gmail.com>
#
from .base import Component as base
class Component(base):
def _get_histogram(self):
return get_histogram(self._cpp_instance)
def get_histogram( monitor ):
from mcstas2.utils.carray import bpptr2npyarr
core = monitor.core()
nx =... |
###########################################################################################
# Script to generate Moving MNIST video dataset (frame by frame) as described in:
# [1] arXiv:1502.04681 - Unsupervised Learning of Video Representations Using LSTMs
# Srivastava et al
# Adapted version of Tencia Lee (https:... |
sample_rate = 32000
window_size = 1024
hop_size = 500 # So that there are 64 frames per second
mel_bins = 64
fmin = 50 # Hz
fmax = 14000 # Hz
frames_per_second = sample_rate // hop_size
audio_duration = 10 # Audio recordings in DCASE2019 Task5 are all 10 seconds
frames_num = frames_per_second * audio... |
#
# @(!--#) @(#) ghpush.py, version 001, 29-january-2020
#
# a Python windows version of the ghpush expect script
#
########################################################################
import sys
import os
import threading
import time
import subprocess
import pyautogui
###########################################... |
from pydantic import BaseModel
from typing import List, Optional
class Role(BaseModel):
name: str
description: Optional[str] = None
class User(BaseModel):
pk: str
sk: str
email: str
password: str
class CreateUserInput(BaseModel):
email: str
password: str
class DeleteUserInput(Bas... |
import math
import time
import unittest
from functools import wraps
import numpy as np
import torch
from propel_loss import PROPEL, h_function, g_function
# Define EPS for numerical stability
eps = 7.0/3 - 4.0/3 - 1
# set deterministic seed
torch.manual_seed(15)
np.random.seed(15)
# define some decorators for opti... |
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
def sp500_level(data=None):
sns.lineplot(data['Date'].astype('datetime64[ns]'),
data['SP500'])
def per_year_boxplot(data=None):
fig, ax = plt.subplots(figsize=(6.4*2, 4.8))
sns.boxplot(x=data[data['len']==1]['year'],
... |
import psycopg2
from galvanalyser.database import Row
class HarvesterRow(Row):
def __init__(self, machine_id,
harvester_name,
is_running=False,
last_successful_run=None,
periodic_hour=None, id_=None):
self.machine_id = machine_id
s... |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('tagging', '0001_initial'),
('fringe', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='fringe',
name='colo... |
"""
Convenient Pointcloud processing functions
@note: Most functions are accelerated by numba and thus compiled to machine code with LLVM,
Thus the first call of functions with decorator @nb.njit is typically very long (up to a few seconds)
"""
import numba as nb
import numpy as np
from numba import prange
... |
# -*- coding: utf-8 -*-
# File : commands.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 12/03/2018
#
# This file is part of dotfiles.
import os
import os.path as osp
import subprocess
import contextlib
from .filters import ConditionalCallable
from .logging import get_logger
logger = get_logg... |
#!/bin/python3
from datetime import datetime as dt
# Complete the time_delta function below.
def time_delta(t1, t2):
time_fmt = '%a %d %b %Y %H:%M:%S %z'
return str(int(abs((dt.strptime(t1, time_fmt) -
dt.strptime(t2, time_fmt)).total_seconds())))
if __name__ == '__main__':
t = int(i... |
"""Utility methods for EvalML pipelines."""
import logging
from woodwork import logical_types
from . import (
TimeSeriesBinaryClassificationPipeline,
TimeSeriesMulticlassClassificationPipeline,
TimeSeriesRegressionPipeline,
)
from .binary_classification_pipeline import BinaryClassificationPipeline
from .m... |
# Copyright 2015 IBM Corp.
#
# 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 a... |
#!/usr/bin/env python3
#
# Copyright 2019 Canonical 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 o... |
from bluepy.btle import Peripheral
from datetime import datetime, timedelta
from logging import getLogger
from time import time, sleep
from .exception import FlowerCareException
_BYTE_ORDER = 'little'
_HANDLE_DEVICE_NAME = 0x03
_HANDLE_DEVICE_TIME = 0x41
_HANDLE_DATA_READ = 0x35
_HANDLE_MODE_CHANGE = 0x33
_HANDLE_FI... |
"""View functions for citation retrieval GUI."""
import logging
from math import log as log_, floor
from urllib.parse import unquote_plus
import json
from django.db.models.query import QuerySet
from django.urls import reverse
from django.http import QueryDict
from django.http.response import Http404
from django.http.... |
"""Golden tests cases for testing liquid's `decrement` tag."""
from liquid.golden.case import Case
cases = [
Case(
description="named counter",
template=r"{% decrement foo %}{{ foo }} {% decrement foo %}{{ foo }}",
expect="-1-1 -2-2",
),
Case(
description="increment and dec... |
import numpy as np
from numpy import genfromtxt
import requests
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, InputLayer, Dropout, BatchNormalization, TimeDistributed
from tensorflow.keras.optimizers import Adam
import sys, os, random
import tensorflow... |
#
# -*- coding: utf-8 -*-
__author__ = "Collin Petty"
__copyright__ = "Carnegie Mellon University"
__license__ = "MIT"
__maintainer__ = ["Collin Petty", "Peter Chapman"]
__credits__ = ["David Brumely", "Collin Petty", "Peter Chapman", "Tyler Nighswander", "Garrett Barboza"]
__email__ = ["collin@cmu.edu", "peter@cmu.ed... |
from setuptools import setup, find_packages
setup(
name='xwppy',
version='0.1',
packages=find_packages(exclude=['tests*']),
license='MIT',
description='A wordpress python to CLI conversion library',
long_description=open('README.md').read(),
install_requires=['os'],
url='https://github.... |
#!/usr/bin/env python
from subprocess import Popen, PIPE
from time import sleep
from fcntl import fcntl, F_GETFL, F_SETFL
from os import O_NONBLOCK, read
import argparse
def set_defaut_route(p=None, iface='wifi', gw='0.0.0.0'):
print 'setting default route iface=%s gw=%s\n' % (iface, gw)
p.stdin.write('confi... |
#!/usr/bin/env python3
# This example shows a simple launcher with PyQt that shows the output of Minecraft in a text filed
from PyQt6.QtWidgets import QApplication, QWidget, QPlainTextEdit, QLabel, QLineEdit, QPushButton, QComboBox, QMessageBox, QHBoxLayout, QVBoxLayout
from PyQt6.QtCore import QProcess
import minecraf... |
import json
from tqdm import tqdm
import numpy as np
import pandas as pd
import cv2
import os
import argparse
def numbers2coords(list_of_numbers):
"""Convert list of numbers to list of tuple coords x, y."""
bbox = [[list_of_numbers[i], list_of_numbers[i+1]]
for i in range(0, len(list_of_numbers), ... |
from toolbox import is_prime, all_primes_below
def is_left_truncatable(number_string):
for i in range(1, len(number_string)):
if not is_prime(int(number_string[i:])):
return False
return True
def is_right_truncatable(number_string):
for i in range(1, len(number_string)):
if not... |
"""
Generate argument list for benchmark random forest
"""
from sklearn.model_selection import ParameterGrid
from util import write_config_file
import argparse
parser = argparse.ArgumentParser(description="Generate configuration file for bench_rf")
parser.add_argument('tool', help="configuration for which tool", choi... |
"""
Test Enterprise DC/OS Signal Service
TODO: this test only differs from upstream in the services that it checks for, rather
find a method such that we do not need to duplicate so much code
"""
import json
import logging
import os
import subprocess
from pathlib import Path
from test_helpers import get_expanded_c... |
"""
Functions used to save model data and to perform analysis
"""
import numpy as np
from parameters import *
from sklearn import svm
import time
import pickle
def analyze_model(trial_info, y_hat, h, syn_x, syn_u, model_performance, weights):
"""
Converts neuronal and synaptic values, stored in lists, into 3... |
import random
from individual import Individual
from population import Population
class SimpleDemoGA:
def __init__(self, numberOfIndividuals, numberOfGenes):
self.numberOfGenes = numberOfGenes
self.population = Population(numberOfIndividuals, numberOfGenes)
self.generationCount = 0
def... |
from .queue import get_dowonload_queue
from cone.tools import get_md5
class Request(dict):
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36'}
def __init__(self, url=None, callback=None, method='GET', headers=No... |
from datetime import datetime
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class Timeline:
accepted: Optional[datetime] = field(default=None)
available: Optional[datetime] = field(default=None)
printed: Optional[datetime] = field(default=None)
online: Optional[dateti... |
#Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros
metros = float(input('Digite o valor a ser convertido em metros: '))
cm = metros * 100
mm = metros * 1000
km = metros / 1000
hm = metros / 100
dam = metros / 10
dm = metros * 10
print('O valor em metros é {}m, em cm {:.0f... |
from flask import Flask
from flask_restful import Resource, Api
from pymongo import MongoClient
app = Flask(__name__)
api = Api(app)
server = MongoClient("159.89.231.140")
db = server.container
class Magazine(Resource):
def get(self):
results = {}
result_all = db.detected
x = result_all.f... |
from __future__ import unicode_literals
import re
from core.observables import Observable
class MacAddress(Observable):
regex = r'(?P<search>(([0-9A-Fa-f]{1,2}[.:-]){5,7}([0-9A-Fa-f]{1,2})))'
exclude_fields = Observable.exclude_fields
DISPLAY_FIELDS = Observable.DISPLAY_FIELDS
@classmethod
de... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.