content stringlengths 5 1.05M |
|---|
# !/usr/bin/python3
# -*- coding: utf-8 -*-
from PIL import Image
import os
import sys
import json
from datetime import datetime
from ImageProcess import Graphics
# 定义压缩比,数值越大,压缩越小
SIZE_normal = 1.0
SIZE_small = 1.5
SIZE_more_small = 2.0
SIZE_more_small_small = 3.0
def make_directory(directory):
"""创建目录"""
o... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import preprocessing
from sklearn.preprocessing import MinMaxScaler
from sklearn import metrics
from sklearn.metrics import confusion_matrix
import itertools
np.set_printoptions(threshold=np.inf)
def plotCf(a,b,t):
cf =confusion_m... |
from flask import Flask, jsonify, request, send_file, Response
import pymysql
#from wand.image import Image
import os.path
import glob
from mutagen import File
#TODO for back end team, check all to dos in file... add response status codes to any that are missing
# Connect to the database
connection = pymysql.connect(h... |
import rpyc
from rpyc.utils.server import ThreadedServer
from domain.connection.CheckDatabaseConnection.CheckDatabaseConnectionCommand import CheckDatabaseConnectionCommand
from domain.connection.CheckDatabaseConnection.CheckDatabaseConnectionRequest import CheckDatabaseConnectionRequest
from domain.connection.CheckDa... |
# Generated by Django 4.0.2 on 2022-02-26 21:04
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('locations', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='favoriteplace',
name='last_modified',
... |
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
print(f"Let's talk about {name}.")
print(f"He's {height} inches tall.")
print(f"He's {weight} pounds heavy.")
print("Actually that's not too heavy.")
print(f"H... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : property.py
# @Author: yubo
# @Date : 2019/12/17
# @Desc :
class Property(object):
"Emulate PyProperty_Type() in Objects/descrobject.c"
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
... |
# Large sum
with open('13.txt', 'r') as file:
content = file.read()
print(str(sum(list(map(int, content.split('\n')))))[:10])
|
#!/usr/bin/python3
# File name : LED.py
# Description : WS_2812
# Website : based on the code from https://github.com/rpi-ws281x/rpi-ws281x-python/blob/master/examples/strandtest.py
# Author : original code by Tony DiCola (tony@tonydicola.com)
# Date : 2019/02/23
import time
from rpi_ws281x import *
i... |
#!/usr/bin/env python3
import re
import requests
def get_content(url):
base_url = "https://cache.gyazo.com/%s.png"
paste_info = {
'site': 'gyazo',
'url': url,
}
m = re.search("[a-z0-9]{32}", url)
if m is None:
return
img_id = m.group(0)
content_url = base_url % im... |
"""add member column to runner table
Revision ID: 4b5ad1ebeb97
Revises: None
Create Date: 2013-05-18 12:55:01.001000
"""
# revision identifiers, used by Alembic.
revision = '4b5ad1ebeb97'
down_revision = None
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import table, column
def upgrade():
... |
# MIT License
#
# Copyright (c) 2020 Gabriel Nogueira (Talendar)
#
# 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,... |
def return_str(string):
return string
def nothing():
pass
def add(a,b):
return a+b
def addList(a):
sum = 0
for i in a:
sum += i
return sum
def addMixedTypes(a, b):
sum = 0
for i in b:
sum += i
return sum + a
class Addition(object):
def __init__(self, ... |
class ContactHelper:
def __init__(self, app):
self.app = app
def create(self, contact):
wd = self.app.wd
# init contact creation
wd.find_element_by_link_text('add new').click()
# fill contact firm
wd.find_element_by_name('lastname').click()
wd.find_ele... |
'''
Write a Python program to count the elements in a list until an element is a tuple.
'''
num = [10,20,30,(10,20),40]
ctr = 0
for n in num:
if isinstance(n, tuple):
break
ctr += 1
print(ctr) |
'''
Model Hyper Parameter Dict
April 2021
modric10zhang@gmail.com
'''
param_dict = {
'feat_dim' : 6, # feature embedding dimension
'user_field_num' : 5, # number of user feature fields
'doc_field_num' : 5, # number of doc feature fi... |
"""Calculation Class"""
class Calculation:
""" calculation abstract base class"""
# pylint: disable=too-few-public-methods
def __init__(self,values: tuple):
""" constructor method"""
self.values = Calculation.convert_args_to_tuple_of_float(values)
@classmethod
def create(cls,values: ... |
import numpy as np
from lib.test.evaluation.data import Sequence, BaseDataset, SequenceList
from lib.test.utils.load_text import load_text
class EOTBDataset(BaseDataset):
""" OTB-2015 dataset
Publication:
Object Tracking Benchmark
Wu, Yi, Jongwoo Lim, and Ming-hsuan Yan
TPAMI, 2015
... |
#!/usr/bin/env python
from htree import mkht_methods, Node
from serqu import unserializq
from tobytes import tobytes
from struct import unpack, calcsize
def bytes2bits(res):
bs = []
for r in res:
if not isinstance(r, int):
r = ord(r)
bs += [True if (r & (1 << i)) != 0 else False ... |
from brian import *
#import pygame
def minimalGame():
#template base pygame
pygame.init() #initialize module
#loading and setting the logo
logo = pygame.image.load("logo32x32.png")
pygame.display.set_icon(logo)
pygame.display.set_caption("minimal program")
#will often need a function to ... |
"""
100 DAYS OF PROGRAMMING CHALLENGE
+++++++ DAY 4 ++++++++
Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number.
Suppose the following input is supplied to the program:
34,67,55,33,12,98
Then, the output should be:
['34', '67', '5... |
import re
s = __import__('stack');
#place stack.py in same directory as this file
class InToPost(object):
def __init__(self, expression):
super(InToPost, self).__init__()
self.expression = expression
self.postFix = self.toPostFix(self.expression)
def precedence(self, operator):
if operator == '+' or operator... |
import time
import sdl2
import openvr
import numpy
from OpenGL.GL import *
from OpenGL.GL.shaders import compileShader, compileProgram
from openvr.glframework import shader_string
from sdl2 import *
# see https://github.com/cmbruns/pyopenvr
class OpenVRTest(object):
"Tiny OpenVR example with python (based on openv... |
import requests
import re
def get_java():
r = requests.get("https://java.com/en/download/")
match = re.search(r"Version [0-9]+ Update [0-9]+", r.text, re.M|re.I)
java_version = [int(s) for s in match.group().split() if s.isdigit()]
return "Java: 1.{}.0.{}".format(java_version[0], java_version[1])
def... |
from searching_alg import search
from rich.progress import track
read_file = input("What file do you want to check?: ")
write_file = input("What file do you want to write to?: ")
with open(read_file,'r') as f:
words = f.read()
f.close()
whitelist = set('abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ')... |
#!/usr/bin/env python3
"""This script adds Trados-style attributes and elements in tmx files.
BEFORE RUNNING THIS SCRIPT:
<?xml version='1.0' encoding='UTF-8'?>
<tmx version="1.4">
<header srclang="en-US" />
<body>
<tu>
<tuv xml:lang="EN-US">
<seg>The White House</seg>
</tuv>
<tuv xml... |
# -*- coding: utf-8 -*-
"""
@Author: Lyzhang
@Date:
@Description:
""" |
from .normalize import Normalize
from .tokenize import Tokenize
from .symspell import SymSpell
|
from django.views.generic import TemplateView
# Projectroles dependency
from projectroles.views import LoggedInPermissionMixin
# Listing/details views --------------------------------------------------------
class ExampleView(LoggedInPermissionMixin, TemplateView):
"""Site app example view"""
permission_r... |
# -*- coding = utf-8 -*-
# @Author:何欣泽
# @Time:2020/10/18 15:17
# @File:DNN.py
# @Software:PyCharm
import numpy as np
import librosa
import os
import tensorflow as tf
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.layers import *
from tensorflow.keras.models import Sequential
from ... |
# Copyright (c) 2006-2013 Regents of the University of Minnesota.
# For licensing terms, see the file LICENSE.
# NOTE: If you make changes to this file, be sure to restart Mr. Do!
import os
import sys
import traceback
import yaml
import conf
import g
from gwis.query_overlord import Query_Overlord
from item.feat imp... |
#!/usr/bin/python3
# coding=utf-8
"""
工具类
"""
__author__ = 'LCD'
import sys
import os
import time
import datetime
import uuid
import platform
from threading import Thread
def cd_sys_type():
"""
:return: 平台类型 0 win, 1 mac 2 Linux 3 其他
"""
"""
a = sys.platform
if a == 'win32' or a == 'win6... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2017 John Dewey
#
# 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 t... |
from rest_framework import serializers
from webapp.models import TMC
class TMCSerializer(serializers.ModelSerializer):
class Meta:
model = TMC
fields = ['titulo', 'subtitulo', 'valor', 'fecha', 'tipo']
|
# https://codeforces.com/problemset/problem/785/A
n = int(input())
sum_faces = 0
for _ in range(n):
polyhedrons = input()
if polyhedrons == 'Tetrahedron':
sum_faces += 4
elif polyhedrons == 'Cube':
sum_faces += 6
elif polyhedrons == 'Octahedron':
sum_faces += 8
elif polyhe... |
import hashlib
def get_md5(str):
md5=hashlib.md5(str.encode(encoding='UTF-8')).hexdigest()
md5=str(md5).upper()
return
|
import pytest
from src import config
@pytest.mark.quick_checks
@pytest.mark.model("N/A")
@pytest.mark.integration("dlc_developer_config")
def test_developer_configuration():
"""
Ensure that defaults are set back to normal before merge
"""
# Check dev settings
assert config.parse_dlc_developer_co... |
def is_palindrome(word):
"""
Reverse the entire word by slicing it all. Compare the reversed word
with the original word.
:param word:
:return:
"""
word = word.lower()
return word[::-1] == word
def is_anagram(word_1, word_2):
"""
Test if the parameters are anagram of themselves... |
"""Services used by anonymizer engine and anonymizers, holding general utility logic."""
|
from typing import Type
from flask import Flask
from hangman.score import GuessScorer
from hangman.gen import GuessGenerator
from hangman.check import GuessChecker
from webapp.config import config
API_PREFIX = '/api/v1'
DEPENDENCIES = 'DEP'
def create_app(config_name: str, guess_gen: GuessGenerator,
... |
# Copyright 2016 Neverware 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 agreed to in writing... |
def now(ExTime = 600):
from ntptime import settime
import setting
import utime
import time
timeserver = setting.get('timeserver')
try:
print(utime.time())
timeset = False
nn = 0
while timeset == False:
try:
if timeser... |
import os
import re
import zipfile
import requests
header = {'Authorization': 'Basic YnV0dGVyOmZseQ==', } # 'YnV0dGVyOmZseQ==' is base64.encode('butter:fly')
response = requests.get('http://www.pythonchallenge.com/pc/hex/unreal.jpg', headers=header)
private = []
for i in range(10):
print(response.headers)
i... |
#!/usr/bin/env python
from sunlight import openstates
import sys
import codecs
sys.stdout=codecs.getwriter('utf-8')(sys.stdout)
state = sys.argv[1]
kwargs = {
"state": state
}
legis = openstates.legislators(**kwargs)
for leg in legis:
search = openstates.legislators(
first_name=leg['first_name'],
... |
#
# Copyright (c) 2017 Joy Diamond. All rights reserved.
#
@gem('Topaz.ConjureTreeComment')
def gem():
require_gem('Topaz.Core')
require_gem('Pearl.ConjureTreeComment')
from Pearl import conjure_tree_comment, tree_comment_cache
def dump_tree_comment_cache():
line('=== Dump of tree_commen... |
from share.exceptions import HarvestError
# TODO replace with a more generic ConcurrencyError, or delete (SHARE-1026)
class HarvesterConcurrencyError(HarvestError):
pass
|
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.behaviors import ButtonBehavior
class MyButton(ButtonBehavior, Image):
def __init__(self, **kwargs):
super().__init__(**kwargs)
#self.source = 'atlas://data/images/defaulttheme/checkbox_off'
def on_press(self):
se... |
#! /usr/bin/env python3
"""Checks file name lengths
Copyright (C) 2019-2022 kaoru https://www.tetengo.org/
"""
import os
import subprocess
import sys
from typing import List
import list_sources
max_length: int = 80
def main(args: List[str]) -> None:
"""The main function.
Args:
args (list[str... |
import unittest
from test_a import TestA
from test_b import TestB
if __name__ == '__main__':
test_loader = unittest.TestLoader()
test_classes = [TestA, TestB]
suites = []
for test_class in test_classes:
suite = test_loader.loadTestsFromTestCase(test_class)
suites.append(suite)
bi... |
import extractors.helpers as helpers
import json
import matplotlib.pyplot as plt
import os
from scipy.spatial import distance
from scipy.interpolate import CubicSpline
import numpy as np
import csv
from scipy.signal import butter,sosfilt,filtfilt
def plot_coordinates(coordinates,subplot):
x = [p[0] for p in coord... |
print('#'*45)
print("")
print('Olá,Mundo!' )
print("")
print('Versão 1.0.1 aula 0001 13/05/2021' )
print('')
print('Estou aprendendo python!.')
print("")
print('#'*45)
|
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import os
import time
import glob
import logging
import cv2
import numpy as np
try:
import gi
gi.require_version('Gst', '1.0')
from gi.repository import GObject, Gst, GLib
except:
pass
import a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import unittest
import numpy as np
import chainer
from chainer import Variable
from models.proposal_layer import ProposalLayer
class TestProposalLayer(unittest.TestCase):
def setUp(self):
self.feat_stride = 16
self.anchor_scales = [8, 1... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: camerasense.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _r... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
import csv
import lzma
import os
from shutil import copy, rmtree
from tempfile import mkdtemp
from unittest import TestCase
from unittest.mock import patch
import numpy as np
import pandas as pd
from serenata_toolbox.chamber_of_deputies.dataset import Dataset
class TestChamberOfDeputiesDataset(TestCase):
def s... |
import time
import threading
class RemoteCallThread(threading.Thread):
def __init__(self, view, timeout=0.1, registered_funcs=['loadFile']):
'''
Parameters
----------
view : NGLWidget
timeout : float (second)
sleep every `timeout`
registered_funcs : Lis... |
"""
*Bitwise Logical Operator*
A bitwise elemental logical operator.
"""
from abc import ABCMeta
from .._operator import ArrayOperator
__all__ = ["ComputationalOperator"]
class ComputationalOperator(
ArrayOperator,
):
__metaclass__ = ABCMeta
|
#Crop the data over a specified range
#
#developed as part of the tomviz project (www.tomviz.com)
def transform_scalars(dataset):
from tomviz import utils
import numpy as np
data_py = utils.get_array(dataset) #get data as numpy array
if data_py is None: #Check if data exists
raise Run... |
"""
Author: Hung Tran
Date Created: 15 April 2021
Date Last Changed: 20 April 2021
Inherit from Enemy class, this class is for individual enemy object
"""
from entity.enemy.base import Enemy
class Goblin(Enemy):
def __init__(self, name, scene):
super().__init__(name, scene)
self.base_attack = 5
... |
import tensorflow as tf
import dnnlib.tflib as tflib
from training import dataset
from training import misc
from metrics import metric_base
class ACC(metric_base.MetricBase):
def __init__(self, num_images, minibatch_per_gpu, label_start, label_end, **kwargs):
super().__init__(**kwargs)
self.num_im... |
"""Tests individual trigger files for the raidboss Cactbot module."""
from pathlib import Path
import subprocess
import sys
from definitions import CactbotModule, DATA_DIRECTORY, PROJECT_ROOT_DIRECTORY, TEST_DIRECTORY
TRIGGER_DIRECTORY = "trigger"
TRIGGER_TEST_DIRECTORY = Path(PROJECT_ROOT_DIRECTORY, TEST_D... |
## Boolean Operators ##
# Q4
def gets_discount(x, y):
""" Returns True if this is a combination of a senior citizen
and a child, False otherwise.
>>> gets_discount(65, 12)
True
>>> gets_discount(9, 70)
True
>>> gets_discount(40, 45)
False
>>> gets_discount(40, 75)
False
>>>... |
# Prepare the web service definition by authoring
# init() and run() functions. Test the functions
# before deploying the web service.
import pandas as pd
def init():
from sklearn.externals import joblib
# load the model file
global model
model = joblib.load('dt.pkl')
def run(input_df):
impor... |
# Generated by Django 2.1.6 on 2019-02-12 16:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pokemons', '0001_initial'),
('battles', '0006_auto_20190212_1423'),
]
operations = [
migrations.Rem... |
# Copyright (c) 2020 PaddlePaddle 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 appli... |
import json
from functools import lru_cache
import pandas as pd
from .api_methods import API
from ..settings import default_namespace
@lru_cache()
def get_namespaces():
string_response = API.get_namespaces()
return json.loads(string_response)
@lru_cache()
def symbols_in_namespace(namespace: str = default_... |
__author__ = "Giulio Rossetti"
__contact__ = "giulio.rossetti@isti.cnr.it"
__license__ = "MIT"
import networkx as nx
import random
class HDemon(object):
"""
Hierarchical version of Demon algorithm as described in
M. Coscia, G. Rossetti, F. Giannotti, D. Pedreschi:
Uncovering Hierarchical and Overlap... |
# From https://github.com/crossbario/autobahn-python/tree/master/examples/asyncio/websocket
import asyncio
from autobahn.asyncio.websocket import WebSocketServerFactory
#from autobahn.twisted.websocket import WebSocketServerProtocol
from autobahn.asyncio.websocket import WebSocketServerProtocol
class MyServerProtocol... |
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + '/../lazychef')
|
#wordCloudGenerator.py
import wordcloud
from matplotlib import pyplot as plot
import tkinter
from tkinter.filedialog import askopenfile
#Reads the selected file and then draws the wordcloud
def readFileAndDrawPlot():
file = askopenfile(mode = 'rb', filetypes = [("Text Files", "*.txt")])
fileContents = ""
... |
from setuptools import setup
setup(
name='yardb',
version='0.0.2',
packages=['yardb'],
entry_points={
'console_scripts': [
'yardb = yardb.__main__:main'
]
}
) |
from typing import List, Tuple, Type, TYPE_CHECKING, Union
from ignite.distributed.comp_models.base import _SerialModel
from ignite.distributed.comp_models.horovod import has_hvd_support
from ignite.distributed.comp_models.native import has_native_dist_support
from ignite.distributed.comp_models.xla import has_xla_sup... |
import requests
import os
import base64
import uuid
import hashlib
from PIL import Image
from asyncio import sleep
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
from urllib.parse import quote
class HelperFunctions:
def verifyUrl(self, url):
val = URLVal... |
__author__, K = "LaughDonor", int(raw_input().split()[1]),
for i, p in enumerate(sorted(map(int, raw_input().split()))):
if K > p:
K -= p
else:
break
print i |
#!/usr/bin/env python
# We load Python stuff first because afterwards it will be removed to avoid error with openCV
import sys
import pathlib
import numpy as np
print("Start Module Loading...")
import csv
import cv2
import glob
import os
import xml.etree.ElementTree as ET
import shutil
SPLIT_RATIO = 0.9
print("Lo... |
from marshmallow import Schema, fields, validate
class CreatorSchema(Schema):
""" Creator Schema """
email = fields.Email(required=True)
password = fields.String(required=True, validate=validate.Length(min=6, max=255))
|
import socket
import argparse
import sys
host = 'localhost'
def echo_server(port):
sock = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET , socket.SO_REUSEADDR , 1)
sock.bind((host,port))
sock.listen(5)
while(True):
try :
print("Listening on... |
# coding: utf-8
# flake8: noqa
"""
openapi-ipify
OpenAPI client for ipify, a simple public IP address API # noqa: E501
OpenAPI spec version: 0.9.0
Contact: blah@cliffano.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
# import models into model pack... |
from sensors.Sensor import Sensor
from messages.Message import Message
from messages.object import Bearing
from messages.subject import Robot
from messages.predicate import HasHeading
class Compass(Sensor):
def __init__(self, queue):
self.queue = queue
self.initialise()
def initialise(self):... |
from srcs.sg.objects.abstract_object import AbstractObject
from srcs.errors import RuntimeASTError
class UnionContext:
def __init__(self, global_context, local_context, function_name, function_object):
self.global_context = global_context
self.local_context = local_context
self.function_n... |
from conans import CMake, ConanFile, AutoToolsBuildEnvironment, tools
import os
import shutil
class FlacConan(ConanFile):
name = "FLAC"
src_name = "flac"
version = "1.3.2"
ZIP_FOLDER_NAME = src_name + "-" + version
generators = "cmake"
settings = "os", "arch", "compiler", "build_type"
requi... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'viewDialog.ui'
#
# Created: Thu Jun 20 19:33:48 2013
# by: PyQt4 UI code generator 4.10.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf... |
from item_probability.weapon_chances_values.knive_chances import get_knive_chances
from item_probability.weapon_chances_values.sword_chances import get_sword_chances
from item_probability.weapon_chances_values.greatsword_chances import get_greatsword_chances
from item_probability.weapon_chances_values.backsword_chances... |
import numpy as np
import xarray as xr
from sklearn.cluster import KMeans
def get_nested_grid_bounds(land_cover_pth):
"""
Get the lat/lon bounds of the nested grid window (NA, EU, AS) for the inversion.
The land cover file path specifies the window.
"""
if "NA" in land_cover_pth:
if "GEOS... |
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
import copy
import os
import datetime
import shutil
from collections import OrderedDict
from itertools import product
import yaml
from numpy import uint8 # noqa: F401 (used in evaluated strings)
CURRENT_DIR = os.path.dirname(os... |
import time
import datetime
import os
from signal import signal, SIGINT, SIGTERM
from sys import exit
app_name = os.environ.get('APP_NAME', 'UNKNOWN')
def handler(signal_received, frame):
dt = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S")
message = '{} is stopping at {} signal: {}'.format(app_name, dt... |
from cosmosis.datablock import option_section
import numpy as np
import cM_models as models
import conversions as conv
def setup(options):
# The list of supported models
supported_cM_models = ['fixedc200c']
# Load the cM model specified in the config file and ensure that it is supported
cM_model_id =... |
#!/usr/bin/env python
'''
read_fuser: The read_fuser module performs several important tasks centered on forming a finished sequence for comparison to the wtDNA configuration element.
If overlapping read pairs have been acquired, read_fuser stitches these together using the read1_overlap_start, read1_overlap_end, rea... |
import os
import types
class IterableNamespace(types.SimpleNamespace):
# forward iterator to internal dict
def __iter__(self):
return self.__dict__.__iter__()
def stringify(lst):
return list(map(str, lst))
def get_sandbox(sbox_id):
unit_dir = os.path.dirname(os.path.realpath(__file__))
... |
# flake8: noqa
"""
All utils are gathered in :py:mod:`catalyst.utils` for easier access.
.. note::
Everything from :py:mod:`catalyst.contrib.utils` is included in :py:mod:`catalyst.utils`
"""
from catalyst.utils.checkpoint import (
load_checkpoint,
pack_checkpoint,
save_checkpoint,
unpack_checkpo... |
import socket
import sys
import easygopigo3
import signal
HOST = "localhost"
PORT = 5002
BUFF_SIZE = 128
try:
gopigo3 = easygopigo3.EasyGoPiGo3()
gopigo3.set_speed(100)
print("GoPiGo3 detected")
except IOError as msg:
print("GoPiGo3 failure message: " + str(msg))
sys.exit(1)
try:
print("creati... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import logging
class report :
parent_logger = None
console_handler = None
def __init__(self, parent_logger, filename = 'report.log') :
"""
Inicializa el sistema de reporte, el cual es dual, dirigido
a la consola con un reporte sumario... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@Description: 程序主入口
@Date :2021/08/14
@Author :xhunmon
@Mail :xhunmon@gmail.com
"""
import os
import sys
from ui import Ui
# 主模块执行
if __name__ == "__main__":
path = os.path.dirname(os.path.realpath(sys.argv[0]))
# path = os.path.dirname('/Use... |
#!/usr/bin/env python3
from utest import *
from pithy.fs import *
utest(True, name_has_any_ext, 'a', frozenset())
utest(True, name_has_any_ext, '.a', frozenset())
utest(True, name_has_any_ext, 'a.e', frozenset(['.e']))
utest(True, name_has_any_ext, '.a.e', frozenset(['.e']))
utest(True, name_has_any_ext, 'a.f', froz... |
from Communication import ArduinoCommunication as ac
from Communication import Mavlink as ml
#from Sensors import SpeedSensor
import math
class MotorControl(object):
'''
This class includes basic motor functions like throttling, brake etc.
The class should handle the work of sharing data with arduino using... |
from setuptools.command.test import test as TestCommand
import sys
import os
#Class that spins up various vagrant instances
#If this gets too large we'll move it out
class VMTestPass(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
def run(self):
import vagrant
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-25 13:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('taxii2', '0002_auto_20160225_1349'),
]
operations = [
migrations.AddField(
... |
import TSCaps.config as cfg
import numpy as np
import os
import matplotlib.pyplot as plt
from keras.utils import np_utils
#
#
# reading data from the txt files
#
def readucr(filename):
data = np.loadtxt(filename+".tsv", delimiter = '\t')
Y = data[:,0]
X = data[:,1:]
return X, Y
###
#
# To normali... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.