content stringlengths 5 1.05M |
|---|
from threading import Thread
from .data_writer import DataWriter, DataWriterException, PlayerList
from pathlib import Path
from PIL import Image
class ScoredImageWriterException(DataWriterException):
pass
class WriteThread(Thread):
def __init__(self, scored_player_list: PlayerList,
save_dir... |
import numpy as np
from qtpy.QtCore import *
from qtpy.QtGui import *
from qtpy.QtWidgets import *
from xicam.core import msg
from xicam.core.data import load_header, NonDBHeader
from xicam.plugins import GUIPlugin, GUILayout, manager as pluginmanager
import pyqtgraph as pg
from functools import partial
from xicam.gu... |
from pathlib import Path
from slugify import slugify
from watchdog.events import RegexMatchingEventHandler
from kart.miners import DefaultMarkdownMiner
from kart.utils import KartDict
try:
from yaml import CSafeLoader as YamlLoader
except ImportError:
from yaml import SafeLoader as YamlLoader
import importl... |
from flask import session
session['var']='oi'
app.run()
app.secret_key = 'minha chave' (vai no main, tem q fazer isso antes de dar app.run)
#lista de funcionarios no depto
#objeto de depto no funcionario
#inserir admin no formulario (criar um admin padrao com TRUE ja)
#listar projetos > ver detalhes do projeto > (li... |
from chalice import Chalice
import requests as rq
import boto3
import os
import json
from datetime import date, timedelta
NYCOD = os.environ.get('NYCOPENDATA', None)
BUCKET, KEY = 'philipp-packt', '311data'
resource = 'fhrw-4uyv'
time_col = 'Created Date'
def _upload_json(obj, filename, bucket, key):
S3 = boto3.c... |
from django.shortcuts import render, get_object_or_404
from django.views.generic import (DetailView, UpdateView)
from django.contrib.auth.mixins import (LoginRequiredMixin,
PermissionRequiredMixin)
from .models import Company
class CompanyDetailView(LoginRequiredMixin, DetailView):
"""Detalle de una empresa... |
import numpy as np
from skimage._shared import testing
from skimage._shared.testing import assert_equal
from skimage.util._label import label_points
def test_label_points_coords_dimension():
coords, output_shape = np.array([[1, 2], [3, 4]]), (5, 5, 2)
with testing.raises(ValueError):
label_points(co... |
from mirage.libs import mosart,utils,io
from mirage.libs.common.hid import HIDMapping
from mirage.core import module
class mosart_keylogger(module.WirelessModule):
def init(self):
self.technology = "mosart"
self.type = "attack"
self.description = "Keystrokes logger module for Mosart keyboard"
self.args = {
... |
import torch
from PIL import Image
import matplotlib.pyplot as plt
from torchvision import transforms
# Set up the matplotlib figure
f, axes = plt.subplots(1, 2, figsize=(7, 7), sharex=True)
# Generate a random univariate dataset
img_data = Image.open("../data/Test/Snow100K-L/synthetic/beautiful_smile_00003.jpg").co... |
#!/usr/bin/env python3
from olctools.accessoryFunctions.accessoryFunctions import combinetargets, filer, GenObject, MetadataObject, \
make_path, run_subprocess, write_to_logfile
from olctools.accessoryFunctions.metadataprinter import MetadataPrinter
from genemethods.typingclasses.resistance import ResistanceNotes
f... |
'''
MIT License
Copyright (c) 2020 Georg Thurner
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,... |
import subprocess
import re
def subprocess_runner(cmd_list, exercise_dir):
with subprocess.Popen(
cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=exercise_dir
) as proc:
std_out, std_err = proc.communicate()
return (std_out.decode(), std_err.decode(), proc.returncode)
def r... |
import os
import time
import math
from tkinter import *
import tkinter.ttk as ttk
from ClientEdit import *
from ClientInsert import *
from ClientView import *
class ClientList(Tk):
def label_combo(self, text, frame=None):
if frame == None:
frame = self.__frame_border
frame = Frame(fra... |
# coding=utf-8
from django.test import TestCase
from django.test.utils import override_settings
class SlugFieldTest(TestCase):
def test_slugfield_allow_unicode_kwargs_precedence(self):
from wshop.models.fields.slugfield import SlugField
with override_settings(WSHOP_SLUG_ALLOW_UNICODE=True):
... |
#!/usr/bin/env python
"""Use to reset pose of model for simulation."""
import rospy
from gazebo_msgs.msg import ModelState
def set_object(name, pos, ori):
msg = ModelState()
msg.model_name = name
msg.pose.position.x = pos[0]
msg.pose.position.y = pos[1]
msg.pose.position.z = pos[2]
msg.pose.... |
# pylint: disable=W0212
# type: ignore
"""深度封装Action方法
函数只能在群消息和好友消息接收函数中调用
"""
import sys
from .action import Action
from .collection import MsgTypes
from .exceptions import InvalidContextError
from .model import FriendMsg, GroupMsg
from .utils import file_to_base64
def Text(text: str, at=False):
"""发送文字
:p... |
# coding:utf-8
# --author-- binglu.wang
import zfused_api
import zfused_maya.core.record as record
def get_assets():
_assets = {}
_project_id = record.current_project_id()
_project_assets = zfused_api.asset.project_assets([_project_id])
# print _project_assets
for _asset in _project_assets:
... |
INPUTPATH = "input.txt"
#INPUTPATH = "input-test.txt"
with open(INPUTPATH) as ifile:
filetext = ifile.read()
data = [chunk for chunk in filetext.strip().split("\n\n")]
from typing import Tuple
IntervalPair = Tuple[int, int, int, int]
def parse_rule(line: str) -> Tuple[str, IntervalPair]:
field, right = line.split... |
from __future__ import print_function, with_statement, absolute_import
import shutil
import torch
import logging
import os
from warnings import warn
from ..version import __version__
from .deployer_utils import save_python_function
logger = logging.getLogger(__name__)
def create_pytorch_endpoint(clipper_conn,
... |
# Generated by Django 3.1.5 on 2021-02-09 19:59
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='DJIAIndexComposition',
fields=[
('id', mode... |
import glob
import os
from Bio import SeqIO
from Bio.Seq import Seq
output_dir_merge = '/scratch/users/anniz44/genomes/donor_species/vcf_round2/merge/details'
genus_cutoff = 3 # >= 3 genera as core
allgenome = output_dir_merge + '/summary/all.genome.gene.faa'
allgenome_denovo = output_dir_merge + '/summary/all.denovo.... |
from __future__ import print_function
import numpy as np
from scipy.sparse.linalg import gmres
import scipy.sparse.linalg as spla
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torch.backends.cudnn as cudnn
import os
import argparse
from tqdm import tqdm
cla... |
import cv2
import numpy as np
from util import *
from copy import deepcopy
def get_horizontal_lines (img):
#=====[ Step 1: set parameters ]=====
num_peaks = 5
theta_buckets_horz = [-90, -89]
theta_resolution_horz = 0.0175 #raidans
rho_resolution_horz = 6
threshold_horz = 5
#=====[ Step 2: find lines in (rho, ... |
from . import VEXObject
class IRStmt(VEXObject):
"""
IR statements in VEX represents operations with side-effects.
"""
__slots__ = ['arch', 'tag']
def __init__(self, c_stmt, irsb):
VEXObject.__init__(self)
self.arch = irsb.arch
# self.c_stmt = c_stmt
self.tag = in... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
#
# Copyright 2021 The NiPreps Developers <nipreps@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may... |
# this is a python script because handling Ctrl+C interrupts in batch
# scripts seems to be impossible
#
# This should always run in the same python that Porcupine uses.
from __future__ import annotations
import subprocess
import sys
import colorama
colorama.init()
prog, directory, command = sys.argv
print(colorama... |
import io
import os
import urllib
import boto3
import botocore
import shutil
import subprocess
import tempfile
from google.protobuf import json_format
from pathlib import Path
from threading import Timer
from urllib.parse import urlparse
class NotReadableError(Exception):
pass
class NotWritableError(Exception... |
import random
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Rectangle
class Point():
def __init__(self, x, y, label):
self.x = x
self.y = y
self.label = label
def get_x(self):
return self.x
def get_y(self):
retur... |
import argparse
import sys
import csv
import os
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
FLAGS = None
BATCH = 8000
Gs = 2 # num of dynamic dims
Gin= 2 # num of input signal dims
TIMESTEP = 0.25
time_points = 200
def Hill_model(x,b,K,links):
# x, current input and state [BATCH,Gin+... |
from keras.models import load_model
from keras.preprocessing.sequence import pad_sequences
from numpy import mean
from sklearn.metrics import accuracy_score
from classifier_load_data import tokenizer, sequence_length
def prob_to_class(probs):
return [1 if p >= 0.5 else 0 for p in probs]
# Passing in the relati... |
# Copyright 2022 Huawei Technologies Co., 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 agreed to... |
from .schema_base import SchemaBase
|
# -*- coding: utf-8 -*-
# Copyright (c) 2010, 2011, Sebastian Wiesner <lunaryorn@googlemail.com>
# 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 source code must retain the... |
## @ingroup Core
# DiffedData.py
#
# Created: Feb 2015, T. Lukacyzk
# Modified: Feb 2016, T. MacDonald
# Jun 2016, E. Botero
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
from copy import deepcopy... |
import json
from unittest import TestCase
from GeneralTests.EMInfraResponseTestDouble import ResponseTestDouble
from OTLMOW.Facility.FileFormats.EMInfraDecoder import EMInfraDecoder
from OTLMOW.Facility.OTLFacility import OTLFacility
from OTLMOW.OTLModel.Classes.Omvormer import Omvormer
class EMInfraDecoderTests(Tes... |
import logging
import pathlib
class Endpoint:
def __init__(self, source_file, addr, port):
self.name = pathlib.Path(source_file).stem
self.addr = addr
self.port = port
def __repr__(self):
return f'{self.name}@{self.addr}:{self.port}'
class EndpointRegistry:
registry = di... |
"""Plugin for emitting ast."""
__all__ = [
"DebugAstOptions",
"DebugAstEmitter",
"debug_ast",
]
from dataclasses import dataclass
from beet import Context, configurable
from beet.core.utils import required_field
from pydantic import BaseModel
from mecha import AstRoot, CompilationDatabase, Mecha, Visi... |
#!/usr/bin/env python
"""
CREATED AT: 2021/9/14
Des:
https://leetcode.com/problems/reverse-only-letters
https://leetcode.com/explore/item/3974
GITHUB: https://github.com/Jiezhi/myleetcode
Difficulty: Easy
"""
from tool import print_results
class Solution:
@print_results
def reverseOnlyLetters(self, s: str) -... |
import pytest
# Local Functions
from fexception.util import set_caller_override
# Local Methods
from fexception.util import KeyCheck
__author__ = 'IncognitoCoding'
__copyright__ = 'Copyright 2022, test_util'
__credits__ = ['IncognitoCoding']
__license__ = 'MIT'
__version__ = '0.0.2'
__maintainer__ = 'IncognitoCodin... |
from math import sqrt
class SomeClass:
'''Some class that certainly does things.
Args:
foo (str): Some string.
'''
def __init__(self, foo: str = 'foo'):
self.msg = f'Here comes {foo}!'
def is_msg_large(self, msg: str):
msg_size = len(msg)
is_large = msg_size > 256... |
from fractions import Fraction
def roll(dices, times):
counter = {}
for d in dices:
counter[d] = 1
for t in range(1, times):
acc = {}
for k, v in counter.items():
for d in dices:
acc[k + d] = acc.get(k + d, 0) + v
counter = acc
return counter
... |
__author__ = 'faisal'
|
import os
import importlib
from functools import partial
KNOWN_MODULES = {
# datasets
'opencv_video_seq_dataset': 'hyperseg.datasets.opencv_video_seq_dataset',
'img_landmarks_transforms': 'hyperseg.datasets.img_landmarks_transforms',
'seg_transforms': 'hyperseg.datasets.seg_transforms',
'transform... |
"""Module that provides a data structure representing a quantum system.
Data Structures:
QSystem: Quantum System, preferred over QRegistry (can save a lot of space)
Functions:
superposition: join two registries into one by calculating tensor product.
"""
import numpy as np
from qsimov.structures.qstructure im... |
from panoramic.cli.husky.service.select_builder.graph_search import (
sort_models_with_heuristic,
)
from panoramic.cli.husky.service.utils.taxon_slug_expression import TaxonSlugExpression
from tests.panoramic.cli.husky.test.mocks.husky_model import (
get_mock_entity_model,
get_mock_metric_model,
)
from test... |
import unittest
import_error = False
try:
from ...tables.base import Base
except ImportError:
import_error = True
Base = None
class TestCase00(unittest.TestCase):
def test_import(self):
self.assertFalse(import_error)
class TestCase01(unittest.TestCase):
def setUp(self):
self.bas... |
"""Utility functions."""
import pycountry
def eu_country_code_to_iso3(eu_country_code):
"""Converts EU country code to ISO 3166 alpha 3.
The European Union uses its own country codes, which often but not always match ISO 3166.
"""
assert len(eu_country_code) == 2, "EU country codes are of length 2, yo... |
from info import *
from choice import *
from rich.console import Console
from rich.table import Table
import time
from rich import print
from rich.panel import Panel
from rich.progress import Progress
def banner():
print(r"""
_ ___ ____ ____ __ _ _
| | | \ \/ /\ \ / / \/ | __ _/ |... |
import os
import sys
from copy import deepcopy
from distutils.version import LooseVersion
import h5py
import numpy as np
import pytest
from ...util.functions import random_id
from ...model import Model
from ...model.tests.test_helpers import get_realistic_test_dust
from .. import (CartesianGrid,
Spher... |
class Config:
redis = {
'host': '127.0.0.1',
'port': '6379',
'password': None,
'db': 0
}
app = {
'name': 'laravel_database_gym',
'tag': 'swap'
}
conf = Config()
|
# Copyright 2018 ZTE Corporation.
#
# 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 ... |
#!/usr/bin/python
"""
Broker for MQTT communication of the agent.
Copyright (C) 2017-2022 Intel Corporation
SPDX-License-Identifier: Apache-2.0
"""
import logging
import json
from typing import Optional
from diagnostic.ibroker import IBroker
from diagnostic.diagnostic_checker import DiagnosticChecker
fro... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: https://github.com/monero-project/mininero
# Author: Dusan Klinec, ph4r05, 2018
# see https://eprint.iacr.org/2015/1098.pdf
import logging
from monero_glue.xmr import common, crypto
from monero_serialize import xmrtypes
logger = logging.getLogger(__name__)
de... |
import os
from dataclasses import dataclass, field
from di import Container, Dependant
@dataclass
class Config:
host: str = field(default_factory=lambda: os.getenv("HOST", "localhost"))
class DBConn:
def __init__(self, config: Config) -> None:
self.host = config.host
async def controller(conn: DB... |
from beaker._compat import pickle
import logging
from datetime import datetime
from beaker.container import OpenResourceNamespaceManager, Container
from beaker.exceptions import InvalidCacheBackendError
from beaker.synchronization import null_synchronizer
log = logging.getLogger(__name__)
db = None
class GoogleNa... |
# Generated by Django 3.1.5 on 2021-05-01 09:50
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_depende... |
parrot = "Norwegian Blue"
letter = input('Enter a char: ')
if letter in parrot:
print('it is in there')
else:
print('not there')
activity = input("What would you like to do today? ")
# I want to go to Cinema
if "cinema" not in activity.casefold(): # casefold handles some languages better
print("But I wa... |
from __future__ import absolute_import
from .node import Node
from .edge import Edge
from .domain import URI, Domain
from .file import File, FileOf
from .ip_address import IPAddress
from .process import Launched, Process
from .registry import RegistryKey
from .alert import Alert
__all__ = [
"Node",
"Edge",
... |
#!/usr/bin/env python3
# Advent of Code 2016 - Day 13, Part One & Two
import sys
from itertools import chain, combinations, product
# test set
# start = (1, 1)
# goal = (7, 4)
# magic = 10
# part one & two
start = (1, 1)
goal = (31, 39)
magic = 1352
def is_valid(coord):
x, y = coord
if x < 0 or y < 0:
... |
def extractWwwScribblehubCom(item):
'''
Parser for 'www.scribblehub.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
if len(item['tags']) == 2:
item_title, item_id = item['tags']
if item_id.isdigit():
... |
from taichi.profiler.kernelprofiler import \
KernelProfiler # import for docstring-gen
from taichi.profiler.kernelprofiler import get_default_kernel_profiler
|
from setuptools import setup
# Convert README.md to README.rst because PyPI does not support Markdown.
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst', format='md')
except:
# If unable to convert, try inserting the raw README.md file.
try:
with open('README.md', enco... |
from sanic import Sanic
from sanic.response import text
from sanic_plugin_toolkit import SanicPluginRealm
#from examples.my_plugin import my_plugin
from examples import my_plugin
from examples.my_plugin import MyPlugin
from logging import DEBUG
app = Sanic(__name__)
# mp = MyPlugin(app) //Legacy registration example
... |
from time import sleep
from procs.makeTree import rel2abs
# 수행부
def loadSet(): # 유저가 구성한 매크로 불러오기 코드
try:
f = open("macro.brn", 'r')
except FileNotFoundError:
return
try:
lines = f.readlines()
for line in lines:
spite_line = line.split()
list_make = ... |
from __future__ import print_function
import math, json, os, pickle, sys
import keras
from keras.callbacks import CSVLogger, EarlyStopping, ModelCheckpoint, LambdaCallback
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.layers import Conv2... |
#This is an exercise program which shows example how while loop can be utilized.
password = ''
while password != 'python123':
password = input("Enter password:")
if password == 'python123':
print("You are logged in!")
else:
print("Try again.") |
import argparse
import random
from typing import Any, Dict, List, Sequence, Tuple
import segmentation_models_pytorch as smp
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.transforms.functional import (InterpolationMode, hflip,
resized_... |
import sys
from cx_Freeze import setup, Executable
build_exe_options = {"packages": ["os"]}
base="Win32GUI"
setup( name="NPSerialOscilloscopeGUI",
version="1.0",
description="potato",
options = {"build_exe": build_exe_options},
executables = [Executable("oscilloscope_gui.py", base=base)]) |
"""
Problem Statement:
Implement a function, `find_first_unique(lst)` that returns
the first unique integer in the list.
Input:
- A list of integers
Output:
- The first unique element in the list
Sample Input:
[9,2,3,2,6,6]
Sample Output:
9
"""
def find_first_unique(lst):
is_unique = {}
for i, v in enum... |
#!/usr/bin/env python
import itertools
with open('input') as f:
serial_number = int(f.read())
# Puzzle 1
def get_power_level(x, y, serial_number):
rack_id = x + 10
power_level = ((rack_id * y) + serial_number) * rack_id
power_level = (power_level // 100 % 10) - 5
return power_level
def get_total_... |
import os
import nose
import ckanext.dcatapit.interfaces as interfaces
from ckanext.dcatapit.commands.dcatapit import DCATAPITCommands
eq_ = nose.tools.eq_
ok_ = nose.tools.ok_
class BaseOptions(object):
def __init__(self, options):
self.url = options.get("url", None)
self.name = options.get("... |
from .Solver import Solver
|
#!/usr/bin/env python
# Copyright 2016 Criteo
#
# 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 agree... |
"""Location cards."""
import logging
from onirim.card._base import ColorCard
from onirim import exception
from onirim import util
LOGGER = logging.getLogger(__name__)
class LocationKind(util.AutoNumberEnum):
"""
Enumerated kinds of locations.
Attributes:
sun
moon
key
"""
... |
import logging
import argparse
import transaction
from pyramid.paster import bootstrap
from .actions import proceed_contest
from .db import Config
def process_queue():
parser = argparse.ArgumentParser()
parser.add_argument("config", help="config file")
args = parser.parse_args()
logging.basicConfig()... |
#!/usr/bin/env false
"""Generate script to activate project."""
# Internal packages (absolute references, distributed with Python)
# External packages (absolute references, NOT distributed with Python)
# Library modules (absolute references, NOT packaged, in project)
# from src_gen.script.bash.briteonyx.source import... |
from HTML import Curve_Write_HTML
from Data import Curve_Write_Data
from SVG import Curve_Write_SVG
class Curve_Write(
Curve_Write_HTML,
Curve_Write_Data,
Curve_Write_SVG
):
##!
##!
##!
def sifsdifdsgf(self):
return 0
|
"""
Python script containing methods for building machine learning model
"""
import utils.text_processing as tp
def classifier(X, y, tokenizer, config):
word_ind_dict = tokenizer.word_index
glove_path = config.get("glove_path")
vocab_size = config.get("vocab_size")
seq_len = config.get("seq_len")
... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: proto/diff-img.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.... |
"""Example training a nobrainer model for brain extraction."""
import nobrainer
# Instantiate object to perform real-time data augmentation on training data.
# This object is similar to `keras.preprocessing.image.ImageDataGenerator` but
# works with volumetric data.
volume_data_generator = nobrainer.VolumeDataGenerat... |
from bflib import dice, movement, units
from bflib.attacks import AttackSet, Bite, Gaze
from bflib.attacks import specialproperties
from bflib.characters import specialabilities
from bflib.characters.classes.fighter import Fighter
from bflib.monsters import listing
from bflib.monsters.appearingset import AppearingSet
f... |
import requests
from bs4 import BeautifulSoup
address = []
def get_html(url):
r = requests.get(url, headers={
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/97.0.4692.99 Safari/537.36',
'accept': '*/*'})
return r... |
# Copyright 2018 Braxton Mckee
#
# 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... |
from blinker import NamedSignal, signal
from sagas.nlu.events import ResultDataset, RequestMeta
from sagas.conf.conf import cf
import sagas.tracker_fn as tc
from pprint import pprint
watch = signal('watch')
# evts=[watch]
@watch.connect
def console_watch(sender, **kw):
import datetime
from sagas.nlu.nlu_tool... |
import numpy as np
class SpatioTemporalSignal(object):
"""
This Class is used to create a group of N signals that interact in space
and time. The way that this interaction is carrieud out can be fully
determined by the user through a SpatioTemporal matrix of vectors that
specify how the signals mix... |
from . import Token
class TreeNode(object):
# dictionary mapping {str: TreeNode}
id_treeNodes = {}
def getTreeNode(idx):
return TreeNode.id_treeNodes[idx]
def __init__(self, idx, tkn):
self._id = idx
self._tkn = tkn
self._children = {}
TreeNode.id_treeNodes[i... |
from flask import Flask
from chatpy.api import API
from chatpy.auth import TokenAuthHandler
app = Flask(__name__)
app.config.from_object('config')
chatwork = API(auth_handler=TokenAuthHandler(app.config['CHATWORK_TOKEN']))
from app.endpoint import *
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by... |
# Copyright (c) 2021, CRS4
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribu... |
import billboard
import json
import urllib
from urllib.parse import quote
apikey = 'APIKEY'
# make the empty dictionary
songs = {}
# loop through the years we're interested in
for x in range(1960, 2016):
# another dictionary inside
songs[x] = {}
# get the chart for the last week of that year
chart = ... |
#! /usr/bin/env python
"""Perform massive transformations on a document tree created from the LaTeX
of the Python documentation, and dump the ESIS data for the transformed tree.
"""
import errno
import esistools
import re
import string
import sys
import xml.dom
import xml.dom.minidom
ELEMENT = xml.dom.Node.ELEMENT_... |
import importlib.util
import os
def vyLoadModuleFromFilePath(filePath, moduleName=None):
if moduleName == None:
replacements = [
('/', '.'),
('\\', '.'),
('-', '_'),
(' ', '_'),
]
filePathSansExt = os.path.splitext(filePath)[0]
for iss... |
from ._plugin import Workplane
from ._plugin import extend |
"""Testing File for roman_ssg_util"""
import os
import shutil
import roman_ssg_util
def setup_test():
"""Setup Tests for tests"""
os.chdir(os.getcwd())
if os.path.isdir("dist"):
shutil.rmtree("dist")
if os.path.isdir("testCustomDirectory"):
shutil.rmtree("testCustomDirectory")
def te... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# */AIPND/intropylab-classifying-images/check_images.py
#
# DONE: 0. Fill in your information in the programming header below
# PROGRAMMER: Aimee Ukasick
# DATE CREATED: 11 April 2018
# REVISED DATE: <=(Date Revised - if any)
# PURPOSE: Check images & report re... |
# -*- coding: utf-8 -*-
# Copyright (C) 2017 Intel Corporation. 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
#
# ... |
import os
import sys
import hashlib
def e(s):
if type(s) == str:
return s
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
def running_in_virtualenv():
return hasattr(sys, 'r... |
import unittest
import pprint
import os
from numpy import testing
import invest_natcap.fisheries.fisheries_hst as main
import invest_natcap.fisheries.fisheries_hst_io as io
pp = pprint.PrettyPrinter(indent=4)
workspace_dir = './invest-data/test/data/fisheries/'
data_dir = './invest-data/Fisheries'
inputs_dir = os.p... |
"""
Decorators
"""
import sys
from contextlib import contextmanager
import mock
from maya_mock.cmds import MockedCmdsSession
from maya_mock.pymel import MockedPymelSession, MockedPymelNode, MockedPymelPort
@contextmanager
def _patched_sys_modules(data):
"""
Temporary override sys.modules with provided data.... |
# -*- coding: utf-8 -*-
from .torsimany import main
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.