content
stringlengths
5
1.05M
from bullet import Bullet from vector import Vector import math import random class Entity: def __init__(self, start_position: Vector, health: int, color): self.color = color self.position = start_position self.health = health class Player(Entity): def __init__(self, start_position: Vector, power:int = 10...
#!/usr/bin/env python #----------------------------------------------------------------------------- # Copyright (c) 2013--, biocore development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #-------------------------...
''' Find the sum of the digits in the number 100! ''' def fact(n): return 1 if n <= 1 else n*fact(n-1) print(sum(map(int, [x for x in str(fact(100))])))
from java import util class MyList(util.ArrayList): def calc_size(self): return self.si<ref>ze()
# Font generation script from Ionicons # https://github.com/driftyco/ionicons/ # http://ionicons.com/ from subprocess import call import os BUILDER_PATH = os.path.dirname(os.path.abspath(__file__)) def main(): generate_font_files() def generate_font_files(): print "Generate Fonts" cmd = "fontforge -script %s/...
import numpy as np align_to_nbytes = 512 max_raidfile_entries = 64 # 8B MrParcRaidFileHeader = [("hdSize_", "<u4"), # ID??? ("count_", "<u4")] # # of meas # 152B MrParcRaidFileEntry = [("measId_", "<u4"), # MeasID ("fileId_", "<u4"), # FileID ...
from schema import Optional as SchemaOptional, SchemaError from schema import Regex, Schema from corehq.motech.dhis2.const import DHIS2_API_VERSION from corehq.motech.exceptions import ConfigurationError from corehq.motech.value_source import ( CaseTriggerInfo, get_form_question_values, get_value, ) def ...
from typing import Any, Optional, Dict from dataclasses import dataclass import json from numpy import ndarray from optmlstat.formatting import convert_data_for_json @dataclass(frozen=True) class OptimizationProblemEvaluation: opt_prob: Any x_array_2d: ndarray obj_fcn_array_2d: Optional[ndarray] = None ...
# display scalar images in volume class show3D : def __init__(self, input=None, MinOpacity=0.0, MaxOpacity=0.1) : import qt import vtk from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor self.__MinOpacity__ = MinOpacity self.__MaxOpacity__ = MaxOpacity # every QT app need...
from .client import AlchemyClient, AlchemyDialect from .database import AlchemyDatabase, AlchemyDatabaseSchema, AlchemyTable from .datatypes import schema_from_table, table_from_schema, to_sqla_type from .query_builder import AlchemyQueryBuilder, build_ast, to_sqlalchemy from .registry import ( fixed_arity, get...
import logging import os import random import re from logrec.dataprep.split.samecase.splitter import load_english_dict logger = logging.getLogger(__name__) class LanguageChecker(object): DEFAULT_MIN_CHARS_TO_BE_NON_ENG = 4 def __init__(self, path_to_general_english_dict, path_to_non_eng_dicts): log...
# Generated by Django 3.1.6 on 2021-02-19 12:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0006_auto_20210219_1215'), ] operations = [ migrations.CreateModel( name='OurTeam', fields=[ ...
def regras(x): if x < 100: if x % 2 == 0: return x else: return (x + x) lista = [100, 200, 1000, 3000, 2, 3, 4, 5, 6, 7, 8] print(list(filter(regras,lista))) #https://pt.stackoverflow.com/q/321682/101
import re # import time import datetime def to_list(file): f = open(file, 'rt', encoding = 'UTF-8') lines = f.readlines() return lines w_punct = to_list('broadcast_w_punct_u_double.txt') backup = w_punct f = open('SubtTV_2017_01_03_pcm.list.trn', 'rt', encoding = 'UTF-8') new_f = open('SubtTV_2017...
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.addHandler(logging.NullHandler()) from . import exceptions from .agent import Agent from .constants import ValueType from .mib import MIBMeta, MIBUpdater, MIBEntry, ContextualMIBEntr...
from Operators.ExampleTextRecognizeOperator.TextRecognizeOperator import GeneralCRNN
import math import sys import itertools as it import warnings import re from collections import OrderedDict import data_IO def readCases(paramsFile, namesdelimiter=";", valsdelimiter="_", paramsdelimiter = "\n", withParamType = True): with open(paramsFile) as f: content = f.read().split(...
'Computer vision as a Service - Python Client' from setuptools import setup setup( name='cvas', version='1.1.28', description='Computer Vision as a Service Python Client', long_description='Computer Vision as a Service Python Client.', license='MIT', author='Adam Jez', author_email='adamje...
# BOJ 11559 import sys from collections import deque si = sys.stdin.readline dx = [-1, 1, 0, 0] dy = [0, 0, -1, 1] def bfs(init_y: int, init_x: int, c: int) -> list: que = deque() vector = [] que.append((init_y, init_x)) visited[init_y][init_x] = True vector.append((init_y, init_x)) while qu...
import pygame class Tile(pygame.sprite.Sprite): def __init__(self,pos,size): super().__init__() self.image = pygame.Surface((size,size)) self.image.fill('grey') self.rect = self.image.get_rect(topleft = pos) def update(self,x_shift): self.rect.x += x_shift
from qgis.core import * from qgis.gui import * from PyQt4.QtGui import * from PyQt4.QtCore import * class CrossSymbolLayer(QgsMarkerSymbolLayerV2): def __init__(self, length=10.0, width=2.0): QgsMarkerSymbolLayerV2.__init__(self) self.length = length self.width = width def layerType(s...
import numpy as np import pandas as pd from sklearn.preprocessing import StandardScaler df=pd.read_csv("039.csv") # print(df) scalar=StandardScaler() scalar.fit(df) df_scaled=scalar.transform(df) print(df_scaled)
# Copyright 2019 ETH Zurich, Lukas Cavigelli and Georg Rutishauser # Copyright and related rights are licensed under the Solderpad Hardware # License, Version 0.51 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://solderpad.org/licenses...
#coding=UTF-8 ''' Created on 2011-7-6 @author: Administrator ''' from urlparse import urlparse import cookielib from pyquery.pyquery import PyQuery #@UnresolvedImport import re import datetime #@UnusedImport import urllib2 from lxml import etree #@UnresolvedImport from lxml.cssselect import CSSSelector #@Unresolv...
from typing import Dict, Iterator, Union from grpc import RpcContext from optionalgrpc.service import Service from my_foo_project.client import foo_pb2_grpc, foo_pb2 @Service(rpc_servicer = foo_pb2_grpc.add_FooServicer_to_server, stub = foo_pb2_grpc.FooStub, port = 1000) class Foo(foo_pb2_grpc.FooS...
import os.path import shutil from collections import OrderedDict from .base import Generator, run_process from ..base import get_logger import json logger = get_logger(__file__) class JSONGenerator(Generator): def generate(self, base="."): out_dir = os.path.abspath(base) os.makedirs(out_dir, ex...
import argparse import os from src.h_CPP.Environment import H_CPPEnvironmentParams, H_CPPEnvironment from src.CPP.Environment import CPPEnvironment, CPPEnvironmentParams from src.DH.Environment import DHEnvironmentParams, DHEnvironment from src.DHMulti.Environment import DHMultiEnvironment from utils import * def m...
class BarryFileException(Exception): """Raise exception when dealing with input files.""" class BarryConversionException(Exception): """Raise exception when converting file to dataframe.""" class BarryExportException(Exception): """Raise exception when writing dataframe to a file.""" class BarryDFExcep...
# Funktion zum Konvertieren eines JSON-Strings in ein # Python-Array. Die Funktion erhält den JSON-String in der # Übergabe und liefert das Ergebnis-Array zurück. def toStringArray(jsonArray): stringArray = [] # Alle Leerzeichen entfernen jsonArray = jsonArray.replace(" ", "") # Sind wir gerade mitten...
from .MidiInfo import *
from __future__ import annotations from datetime import datetime from typing import TYPE_CHECKING from sqlalchemy import Boolean, Column, DateTime, Integer, String, Text from grouper.constants import MAX_NAME_LENGTH from grouper.models.base.model_base import Model if TYPE_CHECKING: from grouper.models.base.sess...
from setuptools import setup, find_packages setup( name="tg_logger", version="3.1", description="A tool to bridge python logging and user files to telegram bot", long_description=open("README.md").read(), long_description_content_type="text/markdown", author="ChernV (otter18)", author_email...
import argparse from update_js import update_js from generate_display_tables import generate_display_tables from datetime import date, timedelta import subprocess def read_lexicon(lfile): conversion = {} with open(lfile) as inf: for entry in inf: spent = entry.strip().split(",") ...
# # Generated with StrouhalUserDefinedPropertyBlueprint from dmt.blueprint import Blueprint from dmt.dimension import Dimension from dmt.attribute import Attribute from dmt.enum_attribute import EnumAttribute from dmt.blueprint_attribute import BlueprintAttribute from .strouhalspecificationproperty import StrouhalSpec...
''' Python 2.7 implementation with some additional functionality: -systeminfo data is uploaded when the file is executed -all the data uploaded to FTP server is encrypted (keys_retriever.py is used to collect/decrypt the data) -ability to take screenshot with simple kl.UploadScreenShot() -auto-downloader so you ca...
from urllib import request import ssl # 全局去掉ssl验证 ssl._create_default_https_context = ssl._create_unverified_context if __name__ == "__main__": # get,默认请求方式 url = "www.ebiddingtest.cecep.cn/jyxx/001001/001001001/20200119/0cac7331-8385-48b7-b252-f836f329aa65.html" res = request.urlopen(url) print(res) ...
# -*- coding: utf-8 -*- from optimus.i18n.manager import I18NManager def po_interface(settings, init=False, update=False, compile_opt=False): """ Manage project translation catalogs for all registred languages. You may enable all available modes. Modes are always processed in the same order: "init" t...
from handy import * lines = read(20) #lines = read_test(20) alg = lines[0] img = lines[2:] img_h = len(img) img_w = len(img[0]) def expand_img(char="."): global img global img_h, img_w img = [char+x+char for x in img] img_w += 2 img = [char*img_w]+img+[char*img_w] img_h += 2 def pmap(img, r...
# https://www.hackerrank.com/challenges/minimum-operations/problem def min_operations(red, green, blue): dp = [[(1<<30) for x in range(8)] for y in range(len(red)+1)] n = len(red) dp[0][0] = 0 for i in range(0, n): for j in range(0, 8): dp[i + 1][j | 1] = min(dp[i + 1][j | 1], dp[i]...
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/pls/ydlidar_ws/src/ros/common_msgs/geometry_msgs/msg/Accel.msg;/home/pls/ydlidar_ws/src/ros/common_msgs/geometry_msgs/msg/AccelStamped.msg;/home/pls/ydlidar_ws/src/ros/common_msgs/geometry_msgs/msg/AccelWithCovariance.msg;/home/pls/ydlidar_ws/sr...
from game.models.base_game_model import BaseGameModel from tf_models.ddqn_model import DDQNModel from game.helpers.constants import Constants from game.environment.action import Action import random import shutil import numpy as np import os from statistics import mean GAMMA = 0.99 MEMORY_SIZE = 10000 BATCH_SIZE = 32 ...
## # @file Placer.py # @author Yibo Lin # @date Apr 2018 # @brief Main file to run the entire placement flow. # import matplotlib matplotlib.use('Agg') import os import sys import time import numpy as np import Params import PlaceDB import NonLinearPlace import pdb def place(params): """ @brief T...
from __future__ import print_function import cv2 import matplotlib.pyplot as plt from skimage.color import rgb2gray from skimage.color import gray2rgb from pydensecrf.utils import unary_from_labels, create_pairwise_bilateral, create_pairwise_gaussian, unary_from_softmax from skimage.io import imread, imsave from six.mo...
# This sample tests various forms of subscript expressions for # syntax and semantic (type) errors. from typing import List, TypeVar _T = TypeVar("_T", list, tuple) def func1(p1: List[int], p2: _T): a1 = p1[0] reveal_type(a1, expected_text="int") a2 = p1[:] reveal_type(a2, expected_text="list[int]"...
from unittest import TestCase from mock import Mock, MagicMock, patch, call from samtranslator.plugins import BasePlugin from samtranslator.model.function_policies import PolicyTypes, PolicyEntry from samtranslator.model.exceptions import InvalidResourceException from samtranslator.plugins.policies.policy_templates_pl...
"""This is just a simple example for testing cprofilev. To see cprofilev in action, run python -m cprofilev example_for_profiling.py """ import random import time def product(x, y): return x * y def main(): x = 1. while True: x = product(x, 0.5 + random.random()) time.sleep(0.1) if _...
import torch import torch.nn as nn from einops import rearrange from utils.vit import ViT class EncoderBottleneck(nn.Module): def __init__(self, in_channels, out_channels, stride=1, base_width=64): super().__init__() self.downsample = nn.Sequential( nn.Conv2d(in_channels, out_channel...
from math import pi def circle_area(radius): if type(radius) not in [int, float]: raise TypeError("The radius is not number") if radius < 0: raise ValueError("The radius is less than zero.") return pi*(radius**2) """" radii = [2, 0, -3, 2 + 5j, True] message = "Area of circles with r = {ra...
import datetime today = datetime.date.today() # global variable to permanantly store the date of day of program execution class BankAccount(object): """ A class to represent a Bank Account ** This class acts as a superclass for classes; SavingsAccount and CheckAccount Constructor Args: -...
# Copyright (c) 2019-2021 Manfred Moitzi # License: MIT License from typing import TYPE_CHECKING, Optional, Tuple, Iterable, Dict, Any from ezdxf.entities import factory from ezdxf import options from ezdxf.lldxf import validator from ezdxf.lldxf.attributes import ( DXFAttr, DXFAttributes, DefSubclass, ...
""" MIT License Copyright (c) 2020 Camilo A. Cáceres 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, publis...
from zephyrus_sc2_parser.events.base_event import BaseEvent from zephyrus_sc2_parser.game.perception_action_cycle import PerceptionActionCycle class CameraUpdateEvent(BaseEvent): def __init__(self, *args): super().__init__(*args) def parse_event(self): if self.event['m_target']: p...
import pandas as pd def clean_dict_cols(df, cols, key='$'): df = df.copy() for c in cols: df[c] = df[c].apply(lambda x: x.get(key) if isinstance(x, dict) else x) return df
from setuptools import setup from rak_net import __version__ requirements = [ 'binary-utils', ] extras_require = { 'docs': [ 'sphinx', 'sphinx-rtd-theme', ], } packages = [ 'rak_net', ] with open('README.rst') as f: readme = f.read() setup( name='aio-rak-net', author='...
#Write your code below this line 👇 print(len(input()))
import re import unittest def assertIn(self, member, container, msg=None): """Just like self.assertTrue(a in b), but with a nicer default message.""" if member not in container: if not msg: msg = '%r not found in %r' % (member, container) self.fail(msg) unittest.TestCase.assertIn =...
# coding: utf-8 import numpy as np import matplotlib.pyplot as plt class Modem: def __init__(self, M, gray_map=True, bin_input=True, soft_decision=True, bin_output=True): N = np.log2(M) # bits per symbol if N != np.round(N): raise ValueError("M should be 2**n, with n=1, 2, 3...") ...
from io import BytesIO import requests from duty.objects import dp, MySignalEvent # Прошу прощения за говнокод. Лень было функцию для загрузки делать :) @dp.longpoll_event_register('неко') @dp.my_signal_event_register('неко') def neko(event: MySignalEvent) -> str: event.msg_op(2, "⏱️Секунду...") img...
"""Test oscillator response calculation.""" import numpy as np import pytest import pyrotd from .test_spectra import load_at2 osc_freq = 10 def calc_oscillator_resp(motion, osc_damping, resp): return pyrotd.calc_oscillator_resp( motion["freqs"], motion["fourier_amps"], osc_damping, ...
import base64, subprocess, json from urllib.request import urlopen, Request def _base64(text): """Encodes string as base64 as specified in the ACME RFC.""" return base64.urlsafe_b64encode(text).decode("utf8").rstrip("=") def _openssl(command, options, communicate=None): """Run openssl command line and rai...
import pytest from ebl.dictionary.domain.word import WordId from ebl.transliteration.domain import atf from ebl.transliteration.domain.dollar_line import RulingDollarLine from ebl.transliteration.domain.enclosure_tokens import BrokenAway from ebl.transliteration.domain.language import Language from ebl.transliteration...
from ktech_python.api import API from ktech_python.middleware import Middleware app = API() def custom_exception_handler(request, response, exception_cls): response.text = str(exception_cls) app.add_exception_handler(custom_exception_handler) @app.route("/home") def home(request, response): response.text ...
/home/runner/.cache/pip/pool/80/e1/5d/d331d8971e24aeb2c49fdf367ac3ad9b3ddd8e21b40454838608e5bdc2
"""TTT4275 Project in Classification""" import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.pyplot import figure from matplotlib import style import matplotlib.animation as animation from sklearn.metrics import ConfusionMatrixDisplay style.use('seaborn-paper') legends = ["Setosa", ...
# -*- coding: utf-8 -*- from django import template from .datetime_filter import format_time register = template.Library() @register.filter(name='find_special_time_by_event') def find_special_time_by_event(special_results, event): for result in special_results: if result.event == event: ...
import glob, unittest from inspect import getmembers, isclass loader = unittest.TestLoader() for modname in (n[:-3] for n in glob.glob('test_*.py')): for suite in loader.loadTestsFromName(modname): if suite.countTestCases(): cls = list(suite)[0].__class__ tests = loader.getTestCase...
from .measurement_parameters import Parameter from .measurement_procedure import Procedure from .publisher import Publisher
from typing import Union, Callable from pydantic.types import constr from .stateful_mechanism import StatefulMechanism from ..utils.pydantic_base_model import CamelBaseModel class Suppression(StatefulMechanism): """ The suppression mechanisms anonymizes input by replacing it with a fixed string of the same ...
import os import sys import json import faiss import numpy as np from tornado import web from tornado import ioloop import rocketqa class FaissTool(): """ Faiss index tools """ def __init__(self, text_filename, index_filename): self.engine = faiss.read_index(index_filename) self.id2text...
import struct import csv import os import numpy as np import math class BinaryReaderEOFException(Exception): def __init__(self): pass def __str__(self): return 'Not enough bytes in file to satisfy read request' class BinaryReader(object): def __init__(self, filename): self.file =...
""" Example Script for writing a timeseries CSV and launching an external R script via a system call. Could be adapted to many other models. """ import os import json from csv import DictWriter from hec.script import Constants from hec.heclib.util import HecTime from hec.hecmath import TimeSeriesMath def callR(scrip...
#! /usr/bin/env python3 from common import * test_vector_a = [randImmI() for x in range(2**4)] test_vector_b = [ randShamt() if x in [AluTypes.SLL.value,AluTypes.SRL.value,AluTypes.SRA.value] else 4 if x in [AluTypes.ADD4A.value] else randImmI() for x in range(2**4) ] test_vecto...
import inspect from typing import Callable, List, Text __all__ = ["infer_variable_names", "infer_separability"] def infer_variable_names(rhs: Callable) -> List[Text]: """ Infer the variable names from the right-hand side function of an ODE model. Args: rhs: Right-hand side to infer variable name...
#It is found that adding two subsequent odd numbers give square of a number. # 1+3=4 which is square of 2 #4+5=9 and so on. # writing a program to compute a entered number square root using this method #if we have to find square root of 6 we will add first six odds->1+3+5+7+9+11 from __future__ import print_function ...
# -*- coding: utf-8 -*- import string from collections import defaultdict from commons import hamming_bin, chunked, sxor ASCII_PRINTABLE_FREQS = { '\n': 0.02908045733331944, '!': 0.0007948248708319754, ' ': 0.20026065368955764, '#': 8.983102066365002e-08, '"': 0.0007286194086028653, '%': 8.983102066365002e-0...
#! /usr/bin/python # -*- coding: UTF-8 -*- # Copyright 2013-2018 Luiko Czub, TestLink-API-Python-client developers # # 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...
from django.urls import path, include from . import views urlpatterns = [ path('', views.index, name='index'), path('books', views.books, name='books'), path('update/<int:id>', views.update, name='update'), path('delete/<int:id>', views.delete, name='delete'), ]
import os import re import subprocess from typing import * import pexpect from PyQt5 import QtWidgets from PyQt5.QtCore import QThread, QMutex def get_temp_file(lang: str): if lang == "rust": return os.path.join(os.path.dirname(__file__), "temp.rs") if lang == "python3": return os.path.join(o...
"""Tests for Python requests implementation generators.""" import os import pytest from http_request_codegen import generate_http_request_code from tests.combinations import ( combination_arguments_to_kwargs, get_argument_combinations, ) CASES_DIRS = { method: os.path.abspath(os.path.join(os.path.dirn...
""" The Web Map Service (WMS) provides a simple HTTP interface for requesting geo-registered map images from one or more distributed geospatial databases. (source : https://www.ogc.org/standards/wms#schemas) The three operations defined for a WMS are : * GetCapabilities (to obtain service metadata) [MANDATORY], * GetM...
from tkinter import ttk, Text, Label, Entry, StringVar import tkinter as tk from tkinter.constants import BOTTOM, TOP from .db import database # Import Database class import re import inspect databaseConnector = database() # Database object def monthView(root): monthWindow = tk.Toplevel(root, width=900, height=5...
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class EventItem(scrapy.Item): # Structure id = scrapy.Field() # What name = scrapy.Field() url = scrapy.Field() imgList = scrapy.Field() imgDe...
import numpy as np import torch import torch.nn.functional as F def f_div_loss(div: str, IS: bool, samples, rho_expert, agent_density, reward_func, device): # please add eps to expert density, not here assert div in ['fkl', 'rkl', 'js'] s, _, log_a = samples N, T, d = s.shape s_vec = s.reshape(-1,...
import argparse import Functions_Features.functionsToDetermineMotifStrength as fdm import pandas as pd parser = argparse.ArgumentParser() parser.add_argument("-w","--tmpfolder",type=str,help="Input the upperlevel folder containing folder to Write to") parser.add_argument("-t","--foldertitle",type=str,help="Input the t...
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By chromedriver = "/home/yongjer/下載/chromedriver" option = webdriver.ChromeOptions() option.binary_location = '/opt/brave.com/brave/brave' s = Service(chromedriver) driver = webdriver.Chro...
import torch import torch.nn as nn import torch.nn.functional as F from einops.layers.torch import Rearrange class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_channels, out_channels, stride = 1): super(BasicBlock, self).__init__() resblock_out_channels = out_channels * BasicBl...
from django.db import models # Create your models here. class Menu(models.Model): title = models.CharField(max_length=32) weight = models.IntegerField(default=1) icon = models.CharField(max_length=64) def __str__(self): return self.title class Permission(models.Model): url = models.CharF...
from fluiddb.cache.permission import CachingPermissionAPI from fluiddb.cache.test.test_namespace import CachingNamespaceAPITestMixin from fluiddb.data.permission import Operation, Policy from fluiddb.data.system import createSystemData from fluiddb.model.exceptions import UnknownPathError from fluiddb.model.test.test_n...
""" Description of frames from Table S2 in "Supplimentary Information for Dominant Frames in Legacy and Social Media Coverage of the IPCC Fifth Assessment Report" Some description has been left out like mentions of other frames, punctuation removed, everything lowercased, entities joined by _ ss Settled Scie...
"""Add a size table Revision ID: 8e8e52357e77 Revises: 0d1c3d81d948 Create Date: 2021-09-21 09:06:01.221871 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '8e8e52357e77' down_revision = '0d1c3d81d948' branch_labels = None depends_on = None def upgrade(): ...
#! /usr/bin/python ### Convert Audio for iPhone Project import os.path import subprocess import shutil def main(): dir = '/Users/Liz/Dropbox/Projects/BoardGame/Sound' files = os.listdir(dir) os.chdir(dir) for file in files: if file.endswith('m4a'): newfile = file.replace('m4a','caf') print(newfile) co...
# SPDX-License-Identifier: BSD-3-Clause # Copyright Contributors to the OpenColorIO Project. import unittest, os, sys build_location = sys.argv[1] opencolorio_sse = sys.argv[2].lower() == 'true' opencolorio_dir = os.path.join(build_location, "src", "OpenColorIO") pyopencolorio_dir = os.path.join(build_location, "sr...
#!/usr/bin/env python3 import argparse import re import subprocess import sys import ruamel.yaml from prompt_toolkit import prompt yaml = ruamel.yaml.YAML() yaml.preserve_quotes = True def merge_values(v1, v2): for k, v in v2.items(): if isinstance(v, dict): node = v1.setdefault(k, {}) ...
def triples_sum_to_zero(l: list): """ triples_sum_to_zero takes a list of integers as an input. it returns True if there are three distinct elements in the list that sum to zero, and False otherwise. >>> triples_sum_to_zero([1, 3, 5, 0]) True >>> triples_sum_to_zero([1, 3, -2, 1]) True ...
""" Install and Uninstall Mongo Connector as a Linux system daemon """ import platform import os import shutil import pathlib import autocommand import importlib_resources as res def check_env(): if platform.system() != "Linux": print("Must be running Linux") raise SystemExit(1) if os.geteui...
from psycopg2.pool import ThreadedConnectionPool import psycopg2.extras import psycopg2.sql as sql from contextlib import contextmanager from threading import Semaphore from ..db.exceptions import DatabaseException from ..utils.logs import Log from ..constants import MIN_CONN, MAX_CONN, TIMEOUT_CONN, DEFAULT_OFFSET_LI...
"""Add ModuleBuid.ref_build_context. Revision ID: caeae7a4f537 Revises: 9ca1c166f426 Create Date: 2018-04-18 13:37:40.365129 """ # revision identifiers, used by Alembic. revision = 'caeae7a4f537' down_revision = '9ca1c166f426' from alembic import op import sqlalchemy as sa # Data migration imports from module_buil...
import json import time import sender while True : time.sleep(1) try : import receiver break except OSError : print("Connect Failed") continue except KeyboardInterrupt : break import threading import distributer sem = threading.Semaphore(5) c...
import numpy as np class Tree: def __init__(self,filename): self.file = open("{}".format(filename)) self.node_dict = {} for node in self.file.readlines(): parameter = node.strip().split(",") if len(parameter) == 4: self.node_dict[int(parameter[0])] = ...
import os import time import Adafruit_DHT timestamp = time.strftime("%x") + " " + time.strftime("%X") # Sensor settings pin = os.environ['DHT_PIN'] sensor_type = { 'DHT11': Adafruit_DHT.DHT11, 'DHT22': Adafruit_DHT.DHT22, 'AM2302': Adafruit_DHT.AM2302 } sensor = sensor_type[os.environ[...