content stringlengths 5 1.05M |
|---|
import argparse
import os
import tempfile
import subprocess
import sys
def run(args):
current_dir = os.path.realpath(__file__)
current_dir = current_dir[:current_dir.rindex('/')]
with tempfile.TemporaryFile('w+') as unweighted_formula:
# Call DeWeight with the provided arguments
... |
# Import the necessary modules
import numpy as np
import matplotlib.pyplot as plt
import seaborn
# In this script we will look at the time to diffuse a given distance as
# a function of time. To begin, let's define our diffusion constant.
D = 10**7 # in units of micron squared per second.
# Now we'll set up an array... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import datetime
import time
from jd_assistant import Assistant
if __name__ == '__main__':
"""
重要提示:此处为示例代码之一,请移步下面的链接查看使用教程👇
https://github.com/tychxn/jd-assistant/wiki/1.-%E4%BA%AC%E4%B8%9C%E6%8A%A2%E8%B4%AD%E5%8A%A9%E6%89%8B%E7%94%A8%E6%B3%95
"""
d... |
import asyncio
ip_address = '161.31.67.111'
ip_port = 5000
# The VP-734 is very quirky. When you power it off through the LAN connection, it will lose its
# connection, and in order to reestablish communication with it, you will need to close the socket
# and open another. Additionally, if DHCP is enabled, it seems ... |
# -*- coding: utf-8 -*-
import textwrap
from perftest.config import default
modules = default.modules | {'/users/jenkins/easybuild/tave/modules/all/CMake/3.12.4'}
cmake_command = default.cmake_command + [
'-DBOOST_ROOT=/project/c14/install/kesch/boost/boost_1_66_0']
def sbatch(command):
# We allocate the ... |
# coding: utf-8
from pyramid_dogpile_cache2 import get_region
import dogpile.cache.util
import pyramid_dogpile_cache2.cache
def test_key_generator_handles_type_annotations():
def function_with_annotations() -> None:
pass
gen = pyramid_dogpile_cache2.cache.key_generator(None, function_with_annotations... |
from setuptools import setup
import webproj
with open("README.md") as f:
readme = f.read()
setup(
name="webproj",
version=webproj.__version__,
description="REST API for PROJ Transformations",
license="MIT",
keywords="PROJ transformations geodesy projections",
author="Kristian Evers",
... |
import pytest
from mongoengine import connect, disconnect
@pytest.fixture
def test_app():
from app import app
return app
@pytest.fixture
def client(test_app):
return test_app.test_client()
@pytest.fixture(scope="function")
def database(test_app):
with test_app.app_context():
disconnect()... |
import requests
import telebot
import json
import settings
import text as txt
import sqlite3
import datetime
import text
import menu
import random
import traceback
list_order_payment = []
num_order = None
balance_dict = {}
class Balance:
def __init__(self, user_id):
self.user_id = ... |
'''
Source codes for PyTorch 1.0 Reinforcement Learning (Packt Publishing)
Chapter 2: Markov Decision Process and Dynamic Programming
Author: Yuxi (Hayden) Liu
'''
import torch
capital_max = 100
n_state = capital_max + 1
rewards = torch.zeros(n_state)
rewards[-1] = 1
print(rewards)
gamma = 1
threshold = 1e-10
head... |
# primeira opção, utilizando o for
for x in range(1, 101):
print(x)
# print vazio para organizar
print()
# segunda opção, utilizando o while
n1 = 0
while n1 < 100:
n1 += 1
print(n1)
# terceira opção, não existe do while
|
# Copyright (c) 2018, Palo Alto Networks
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS... |
# GUI Application automation and testing library
# Copyright (C) 2006 Mark Mc Mahon
#
# 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 License, or (at your opti... |
""" Script for removing all but the best weights for a training run, to save
several gigabytes of disk storage
"""
from glob import glob
import os.path
import numpy as np
import click
from folder import runs_path
@click.command()
@click.option("--dataset", default="sweden2", help="Name of dataset")
@click.option... |
import re
import tempfile
import os
import tarfile
from urllib.parse import urlparse
from shutil import copyfile
from astroutilities import customRequests
from astroutilities.urlUtilities import extract_filename
class CustomFileManager:
warehouse_dir = f"{tempfile.gettempdir()}/warehouse"
work_dir = f"{tempfi... |
#!/usr/bin/env python
import json
import os
import subprocess
from pathlib import Path
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT_DIR = os.path.dirname(BASE_DIR)
HOME = str(Path.home())
PROJECT_NAME = 'daangn-market'
PROJECT_DIR = os.path.dirname(ROOT_DIR)
PROJECT_DIR = os.path.join(R... |
name = input('name')
excluded = 0
class_year = 1
grades_sum = 0
while True:
if excluded > 1:
break
if class_year > 12:
break
grade = float(input())
if grade >= 4:
class_year += 1
grades_sum += grade
else:
excluded += 1
if excluded > ... |
#%%
import pathlib
import os
from docx import Document
#%%
pathlib.Path('certificates').mkdir(parents=True, exist_ok=True)
#%%
fname = pathlib.Path("names.txt")
#%%
with open(fname) as f:
name_list = f.readlines()
#%%
for name in name_list:
name = name.strip()
document = Document()
document.add... |
import pandas as pd
import random
def data_frame(user_id=300, k=50000, conv_rate=0.4):
""" """
channels = [
"Direct",
"Direct",
"Facebook",
"Facebook",
"Facebook",
"Google Search",
"Google Search",
"Google Search",
"Google Search",
... |
from aisoccer.brains.DefendersAndAttackers import *
from aisoccer.graphics.field import *
game = Game(DefendersAndAttackers(), BehindAndTowards())
field = Field(game)
field.start_game()
|
from flask_wtf import Form
from wtforms import StringField, IntegerField
from wtforms.validators import DataRequired, NumberRange
class MyForm(Form):
name = StringField('Name', description='Name',
validators=[DataRequired(message="You're not listening, are you?")])
class WanderingForm(For... |
# Authentication & API Keys
# Many APIs require an API key. Just as a real-world key allows you to access something, an API key grants you access to a particular API. Moreover, an API key identifies you to the API, which helps the API provider keep track of how their service is used and prevent unauthorized or maliciou... |
from lib.util import mapping_to_namedtuple
import importlib
import os
class ConfigLoader:
""" A class for loading the configuration from lib.config.*, according
to the environment passed in the environment variable `envvar`. The
default environment is always loaded; the secondary environment
overwri... |
"""
Title: Image segmentation with a U-Net-like architecture
Author: [fchollet](https://twitter.com/fchollet)
Date created: 2019/03/20
Last modified: 2020/04/20
Description: Image segmentation model trained from scratch on the Oxford Pets dataset.
"""
"""
## Download the data
"""
"""shell
curl -O http://ww... |
"""Logging functionalities."""
import logging
class Logger(object):
"""Class encapsulating logging functionalities."""
def __init__(self, path="root.log", name="root", level="info"):
self.logger = logging.getLogger(name)
self._configure_logging(path, level)
def _configure_logging(self, p... |
from urllib.parse import urlsplit, parse_qs
from .base import Model, Nested, String
def key_or_none(qs, key):
iterable = qs.get(key, [None])
return iterable[0]
class AuthInfo(Model):
root_tag = 'mrw:AuthInfo'
franchise_code = String('mrw:CodigoFranquicia')
subscriber_code = String('mrw:CodigoA... |
#!/usr/bin/python2
# -*- coding: utf-8 -*-
from time import sleep
import copy
import atexit
from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate
from GlyphSprites import Sprites
import requests
import dateutil.parser
lcd = Adafruit_CharLCDPlate()
atexit.register(lcd.stop)
lcd.backlight(True)
lcd.createChar(0, Spr... |
# Copyright 2017 VMware, Inc.
#
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
from utils.model import Perceptron
from utils.all_utils import prepare_data, save_plot, save_model
import pandas as pd
OR = {
"x1": [0,0,1,1],
"x2": [0,1,0,1],
"y": [0,1,1,1],
}
df = pd.DataFrame(OR)
X,y = prepare_data(df)
ETA = 0.3 # 0 and 1
EPOCHS = 10
model_OR = Perceptron(eta=ETA, epochs=EPOCHS)
mo... |
"""
Library for processing SHARAD data
Author: Cyril Grima <cyril.grima@gmail.com>
"""
import numpy as np
import pandas as pd
import raw
from scipy.interpolate import splrep, splev
import matplotlib.pyplot as plt
import scipy.constants as ct
from planetbody import mars, ellipsoid
import rsr.utils
import rsr.fit
import... |
import os
import json
from paddleocr import PaddleOCR
import numpy as np
import re
import time
import sys
from multiprocessing import Process, Queue
from paddlenlp.transformers import LayoutXLMTokenizer
tokenizer = LayoutXLMTokenizer.from_pretrained("layoutxlm-base-uncased")
def get_all_chars(tokenizer):
all_ch... |
import PIL.ImageGrab
from PIL import Image
import time
import win32api
import win32con
zero_count = 0
t = None
while True:
time.sleep(0.2)
im = PIL.ImageGrab.grab()
#im.show()
#im.save('example.bmp')
#im = Image.open('example.bmp')
#nim = im.crop((929,72,1338,481))
... |
#/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Red Hat, Inc.
#
# 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
... |
from typing import Union, List, Dict
import argparse
import logging
import os
import pandas as pd
import numpy as np
from rgnn_at_scale.helper.local import setup_logging, build_configs_and_run
from rgnn_at_scale.data import prep_graph, split
from rgnn_at_scale.helper import ppr_utils as ppr
from rgnn_at_scale.helper.io... |
from requests import get, post, delete
from workerInfra.models import Settings
from .common import RestSql
from typing import List
from json import loads
class SettingsTable(RestSql):
def __init__(self):
# pull from env
self.baseUrl = self.__getApiUri__()
self.uri: str = f"{self.baseUrl}/v... |
#----------------------------------------------------------------------------
# Name: datetimeparser.py
#
# Purpose: - Instantiate datetime.datetime/date instance from a string
# date representation.
# Uses dateutil from http://labix.org/python-dateutil.
#
# - ... |
import os
import subprocess
import inspect
import signal
import shutil
from cloudmesh.common.Shell import Shell
from cloudmesh.common.console import Console
from cloudmesh.common.util import path_expand
class Viewer:
platform = Shell.terminal_type()
import cloudmesh.viewer as viewer_pkg
base_dir = inspec... |
# This file is part of QuSoliton: Quantum Soliton toolbox.
#
# Copyright (c) 2022 and later, Claudio Conti.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of so... |
#==========================================
# Main for Training Reward Predictor Model
# Author: Nasim Alamdari
# Date: Dec. 2020
#==========================================
import os, glob
import numpy as np
import librosa
import librosa.display
import math
import random
from random import randint
import matplotli... |
# -------------------------------------------------------------------------------
# Name: sfp_wigle
# Purpose: Query wigle.net to identify nearby WiFi access points.
#
# Author: Steve Micallef <steve@binarypool.com>
#
# Created: 10/09/2017
# Copyright: (c) Steve Micallef
# Licence: MIT
# ---... |
class Solution:
def numMatchingSubseq(self, S: 'str', words: 'List[str]') -> 'int':
str = {}
for s in range(len(S)):
if S[s] not in str:
str[S[s]] = []
str[S[s]].append(s)
total = 0
for word in words:
sub, exist = -1, True
... |
from time import sleep
import logging
logger = logging.getLogger(__name__)
def submit_content_download_form(browser, email=None, firstname=None, lastname=None, company_size=None, agree=None):
if '/templates/expense-reports' in browser.get_current_url():
browser.click(xpath="//a[@id='download-excel']")
... |
#!/usr/bin/python
# Copyright (C) 2016, 2016 Carlos R. Lacerda
#%
#% $Id: PurePursuit.py 2016-08-08 12:09:23Z carlosrl_at_gmail_dot_com $
#%
#% This software is distributed under the GNU General Public
#% Licence (version 2 or later); please refer to the file
#% Licence.txt, included with the software, for det... |
import os
import logging
import subprocess
import sys
import feedparser
import collections
import threading
from atexit import register
import time
import requests
import json
from myutils import query_config, replace_invalid_filename_char
logger = logging.getLogger('pystuff')
class Podcast:
def __init__(self,ti... |
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright 2021 Canonical Ltd.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License version 3 as published by the Free Software Foundation.
#
# This program is distributed in t... |
from output.models.nist_data.atomic.positive_integer.schema_instance.nistschema_sv_iv_atomic_positive_integer_min_inclusive_3_xsd.nistschema_sv_iv_atomic_positive_integer_min_inclusive_3 import NistschemaSvIvAtomicPositiveIntegerMinInclusive3
__all__ = [
"NistschemaSvIvAtomicPositiveIntegerMinInclusive3",
]
|
'''#runs tasks on schedule
#should read tasks from configuration
#examples: when to discover. when to monitor. when to ...
#will run tasks by sending command (raising event)
'''
import datetime
import time
from helpers.queuehelper import QueueName, QueueEntry
from helpers.taskschedule import TaskSchedule
from backend.f... |
from quart import Quart, request
import traceback
import inc.api
import inc.api_properties
import inc.api_classes
import inc.api_types
import util_log
util_log.init("Wikidata_Endpoint_API.log")
app = Quart(__name__)
app.debug = False
@app.route('/test')
async def routeTest():
# res = await inc.api.get_type_lst(... |
import os
import numpy as np
import sys
import torch
# import model
sys.path.append(os.path.abspath("."))
import pclpyd as pcl
from visualizer.OpencvVis import CVis
import importlib
# pcd_dir = "../datasets/3dvisionpcl/.XYZ"
def set_datactr(datactr):
datactr.vis = CVis(grab_pcl_fuc=datactr.get_data,
... |
#!/usr/bin/env python
import random
vocabulary = dict()
originalVocabulary = dict()
articles = list()
def readVocabulary(input, default):
print(input)
with open(input) as fin:
for line in fin:
word = line.rstrip('\n')
if not word or word[0] == ';': continue
vocabul... |
# Check if a DNA sequence contains a stop codon
# DNA sequence given
dna = "GTT GCA CCA CAA CCG TAG TAA TGA"
# Check if the sequence contains one possible stop codon
if "TAG" in dna:
print("TAG found")
# Check if the sequence contains any of the 3 stop codons
if ("TAG" in dna) or ("TAA" in dna) or ("TGA" in dna)... |
import pkg_resources
PROGRAM_NAME = 'ocrmypdf'
VERSION = pkg_resources.get_distribution('ocrmypdf').version
# These imports are for v4.x backward compatibility for consumers of ocrmypdf
# (if any). They are deprecated and will be removed in v5.x.
from .exec import ghostscript, qpdf, tesseract, unpaper, get_program
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
from mutation import AddConnectionMutation,AddNodeMutation,ChangeNodeMutation,ChangeConnectionMutation,ToggleConnectionMutation,ToggleNodeMutation,tests
from gene import ConnectionGene, NodeGene, PseudoGene, tests
from genome import Genome, tests
from phenome import Phenome, tests
from fitness import Fitness, tests
fro... |
from typing import Tuple
from hypothesis import given
from shewchuk import (Expansion,
vectors_dot_product)
from . import strategies
@given(strategies.floats_octuplets)
def test_basic(octuplet: Tuple[float, float, float, float, float, float, float,
float]) -> Non... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import argparse
import json
import logging
import os
import argparse
import boto3
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
sm_client = boto3.client("sagemaker")
org_client = bot... |
import boto3
import click
from newrelic_lambda_cli import api, integrations, permissions
from newrelic_lambda_cli.cli.decorators import add_options, AWS_OPTIONS, NR_OPTIONS
from newrelic_lambda_cli.cliutils import done, failure
@click.group(name="integrations")
def integrations_group():
"""Manage New Relic AWS L... |
"""
* 빗물 트래핑
높이를 입력받아 비 온 후 얼마나 많은 물이 쌓일 수 있는지 계산하라
- 입력
[0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
- 출력
6
"""
from typing import List
class Solution:
def trap(self, height: List[int]) -> int:
stack = []
volume = 0
for i in range(len(height)):
# 변곡점을 만나는 경우
while stack a... |
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^$', 'templatesadmin.views.listing', name='templatesadmin-overview'),
url(r'^edit(?P<path>.*)/$', 'templatesadmin.views.modify', name='templatesadmin-edit'),
)
|
#
# Unit tests for the `drf_haystack.filters` classes.
#
import json
from datetime import date, datetime, timedelta
from unittest import skipIf
from django.test import TestCase
from rest_framework import status
from rest_framework import serializers
from rest_framework.test import APIRequestFactory
from drf_haysta... |
#!/usr/bin/env python
import functools
import os
import multiprocessing as mp
import glob
import time
import itertools
import sys
import pickle
import numpy as np
import scipy as sci
import pandas as pd
import subprocess
import plotly
import plotly.graph_objs as go
import json
import re
from scipy.stats import pearson... |
from .http import HttpRequest
class Client:
def __init__(self, loop = None):
self.http = HttpRequest(self)
self.loop = asyncio.get_event_loop() if loop is None else loop
self.cmd = []
self.cmd_now = []
def dispatch(self, name, *args, **kwargs):
try:
... |
"""Provide a class for ODT descriptions export.
Copyright (c) 2022 Peter Triesberger
For further information see https://github.com/peter88213/aeon3odt
Published under the MIT License (https://opensource.org/licenses/mit-license.php)
"""
from aeon3odtlib.odt_aeon import OdtAeon
class OdtLocationSheets(OdtAe... |
# Defination for mathematical operation
def math(token_ip_stream,toko):
if token_ip_stream[0][0] == 'INOUT' and token_ip_stream[1][0] == 'IDENTIFIRE' and token_ip_stream[2][1] == "=" and token_ip_stream[3][1] == toko[0][0] and token_ip_stream[5][1] == toko[1][0] and token_ip_stream[6][0] == "STATEMENT_END" :
... |
from unittest import TestCase
import numpy as np
from data_loader import DATA, ROLE_FIELDS
from ahyper.annotated_hypergraph import AnnotatedHypergraph
class ConstructionTests(TestCase):
"""
Basic tests for the construction of Annotated Hypergraphs.
"""
def test_record_constructor(self):
"""... |
import os, subprocess,fnmatch
from shutil import copy2
from ehive.runnable.IGFBaseProcess import IGFBaseProcess
from igf_data.utils.fileutils import get_temp_dir,remove_dir
from igf_data.igfdb.baseadaptor import BaseAdaptor
from igf_data.igfdb.collectionadaptor import CollectionAdaptor
from igf_data.igfdb.runadaptor im... |
import random
import time
import uuid
from cassandra import ConsistencyLevel
from cassandra.query import SimpleStatement
from tools.assertions import assert_invalid, assert_length_equal, assert_one
from dtest import Tester, create_ks, create_cf
from tools.data import rows_to_list
from tools.decorators import since
... |
#!/bin/python
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import collections
from math import log
import sys
# Python 3 backwards compatibility tricks
if sys.version_info.major > 2:
def xrange(*args, **kwargs):
return iter(ra... |
import ftplib
from subprocess import Popen, check_output
from configparser import SafeConfigParser
from datetime import datetime, date
from queue import Queue
from uuid import getnode
import random
import threading
import time
import platform
import sys
import socket
import os
current_dir = os.path.dirname(os.path.rea... |
# MINLP written by GAMS Convert at 05/07/21 17:13:01
#
# Equation counts
# Total E G L N X C B
# 249 5 0 244 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc si
# ... |
import pandas as pd
def smooth(data, apply_columns=None, window=1):
""" Smooth the data.
Arguments:
data (pandas.DataFrame): Data.
apply_columns (list of str): List of columns to apply smoothing. If the
value is "None", all numeric series will be smoothed.
window (int): Si... |
from multitaskpinn.utils.tensorboard import Tensorboard
from multitaskpinn.utils.output import progress
from multitaskpinn.model.deepmod import DeepMoD
from typing import Optional
import torch
import time
import numpy as np
from torch.distributions.studentT import StudentT
from sklearn.linear_model import Bayesi... |
import discord, base64, re
from redbot.core import checks, commands
from redbot.core import Config
from redbot.core.data_manager import bundled_data_path
from PIL import Image, ImageDraw
from io import BytesIO
BaseCog = getattr(commands, "Cog", object)
class Sketch(BaseCog):
def __init__(self,bot):
self.b... |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... |
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
import unittest
from databuilder.models.graph_serializable import (
RELATION_END_KEY, RELATION_END_LABEL, RELATION_REVERSE_TYPE, RELATION_START_KEY, RELATION_START_LABEL,
RELATION_TYPE,
)
from databuilder.models.query.que... |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# ^^ required by pep-0263 for "¿?"
# Copyright 2014 Netflix, 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
#
# ... |
# apis_v1/urls.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
"""
This is called from config/urls.py like this:
url(r'^apis/v1/', include('apis_v1.urls', namespace="apis_v1")),
"""
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from a... |
from typing import List
from storage_system import StorageSystem
import typing
_storage_system_swift_supported = False
try:
import swiftclient
_storage_system_swift_supported = True
except ImportError:
_storage_system_swift_supported = False
def is_available() -> bool:
return _storage_system_swift_... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 24 18:01:43 2021
@author: LENOVO
"""
import os
import sys
from PyQt5 import QtWidgets
import pandas as pd
import sqlite3
from sqlite3 import OperationalError
from main import MainWindow
class bug_report(MainWindow):
def bugs(self, enable):
if enable:
... |
#Josué Laguna Alonso
#08/02/2018
mano_der = "movil"
mano_izq = "bocadillo"
mano_extra = "nada"
|
import os
import json
from pathlib import Path
from typing import List
from pyspark.sql import SparkSession, functions as f
from pyspark.sql.dataframe import DataFrame
from pyspark.sql.window import Window
from pyspark.sql.types import StructType, BooleanType
from input_schemas import (
MPNS_V8_PLANTS,
MPNS_... |
import numpy as np
import pytest
from astropy import units as u
from hypothesis import given, strategies as st
from eniric.atmosphere import Atmosphere
from eniric.legacy import RVprec_calc_masked, RVprec_calc_weights_masked, mask_clumping
def test_RV_prec_masked(test_spec):
"""Test same precision results betwee... |
import requests
import json
import time
import sys
import blescan
import bluetooth._bluetooth as bluez
import conf
from datetime import datetime
import threading
def main():
PHONES_STATUS = conf.PHONES
dev_id = 0
try:
sock = bluez.hci_open_dev(dev_id)
print "{} - ble thread started".forma... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 31 16:23:13 2018
@author: samschott
"""
import os
import logging
import threading
# external packages
from PyQt5 import QtCore, QtWidgets, QtGui, uic
from PyQt5.QtCore import QAbstractItemModel, QModelIndex, Qt, QVariant
# maestral modules
from ma... |
"""Compare instance reservations and running instances for AWS services."""
import click
import pkg_resources
from check_reserved_instances.calculate import (
calculate_ec2_ris, calculate_elc_ris, calculate_rds_ris)
from check_reserved_instances.config import parse_config
from check_reserved_instances.report impo... |
from datetime import date
nome = input("Qual seu nome? ")
hoje = date.today()
dia = input("Qual o dia do seu aniversário? ")
mes = input("Qual o mês do seu aniverssário? ")
ano = input("Qual o ano do seu aniversario? ")
hoje = str(hoje)
dia_h = int(hoje[8:])
mes_h = int(hoje[5:7])
ano_h = int(hoje[:4])
sua_idade =... |
from NJ_tree_analysis_functions import start_gui_explorer
# nov v omegaCen?
objs = [
140305003201095, 140305003201103, 140305003201185, 140307002601128, 140307002601147, 140311006101253,
140314005201008, 140608002501266, 150211004701104, 150428002601118, 150703002101192
]
# nov v NGC6774
objs = [
14070700... |
import multiprocessing
bind = '0.0.0.0:9000' # 绑定ip和端口号
workers = multiprocessing.cpu_count() * 2 + 1 # 进程数
worker_class = "gevent"
worker_connections = 2048
access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"' # 设置gunicorn访问日志格式,错误日志无法设置
accesslog = "logs/gunicorn_access.log" # 访问日志文件
... |
from struct import pack, unpack
from ..command_packet import CommandPacket
class GATT_ReadCharValue(CommandPacket):
def __init__(self, conn_handle, handle):
super().__init__(
CommandPacket.OpCode.GATT_READ,
GATT_ReadCharValue._params_to_binary(conn_handle, handle)
)
@... |
from django import forms
from .models import Post, BlogComment
from django.contrib.auth.models import User
class NewCommentForm(forms.ModelForm):
class Meta:
model = BlogComment
fields = [
'blogpost_connected',
'user',
'comment_con... |
import numpy as np
from ..network_likelihoods import dynamic_network_loglikelihood
__all__ = ['posterior_expected_vi', 'time_averaged_posterior_expected_vi',
'minimize_posterior_expected_vi']
def nonvectorized_posterior_expected_vi(labels, cooccurrence_proba):
"""non-vectorized expected VI used for ... |
# torch
import torch
import torch.nn as nn
# locals
from .utils import OneHotEncode
from .encoders import SENNEncoder, StyleEncoder, VAEEncoder
from .decoders import SENNDecoder
class SENNConceptizer(nn.Module):
"""Class to reproduce Senn conceptizer architecture
Args:
n_concepts: number of concepts
... |
"""Config flow for ZHA."""
from __future__ import annotations
import os
from typing import Any
import serial.tools.list_ports
import voluptuous as vol
from zigpy.config import CONF_DEVICE, CONF_DEVICE_PATH
from homeassistant import config_entries
from homeassistant.const import CONF_HOST, CONF_NAME
from homeassistan... |
import os
class Config:
DEBUG = False
JWT_SECRET_KEY = os.getenv('JWT_SECRET_KEY')
DATABASE_URL = os.getenv("DATABASE_URL")
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
DEBUG = True
TESTING = True
class ProductionConfig(Config):
DEBUG = False
TESTING = F... |
from django.urls import path
from otapiui import views
urlpatterns = [
path("", views.index, name="home"),
path("status", views.system_status, name="system_status"),
path("systemStatusJson", views.systemStatusJson, name="systemStatusJson"),
path("fleetLatestLocation", views.fleetLatestLocation, name="f... |
# Copyright 2020 Alexis Lopez Zubieta
#
# 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, publi... |
#! /usr/bin/env python
import requests
from requests.auth import HTTPBasicAuth
import yaml
class BacdiveClient(object):
def __init__(self, credentials):
self.headers = {'Accept': 'application/json'}
USERNAME = credentials['login']
PASSWORD = credentials['password']
self.credential... |
# Generated by Django 3.1.4 on 2021-02-06 02:25
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("app", "0013_auto_20210206_0324"),
]
operations = [
migrations.RemoveField(
model_name="user",
... |
def clean_input(input_data):
clean_data = []
for d in input_data:
input_values, output_values = d.split(' | ')
input_values = ["".join(sorted(s)) for s in input_values.split(' ')]
output_values = ["".join(sorted(s)) for s in output_values.split(' ')]
clean_data.append([input_val... |
from oct2py import octave as oct
oct.eval("cd ../")
oct.eval("pglib_opf_case3_lmbd")
oct.eval("save -v7 experiments/pglib_opf_case3_lmbd.mat")
#ptr = oct.pull('bus')
res = oct.feval("pglib_opf_case3_lmbd")
print(res)
from scipy.io import loadmat
D = loadmat("pglib_opf_case3_lmbd.mat")
print(D)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.