text
stringlengths
1
927k
import os def configuration(f): import click from functools import update_wrapper @click.pass_context def inner(ctx, *args, **kwargs): # HACK: We can't call `configure()` from within tests # since we don't load config files from disk, so we # need a way to bypass this initiali...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 Nicira Networks, 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.apach...
from dataclasses import dataclass, field from typing import Optional @dataclass class DataTrainingArguments: """ Arguments pertaining to what data we are going to input our model for training and eval. Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify them o...
from office365.runtime.client_result import ClientResult from office365.runtime.queries.create_entity_query import CreateEntityQuery from office365.runtime.queries.service_operation_query import ServiceOperationQuery from office365.runtime.queries.update_entity_query import UpdateEntityQuery from office365.runtime.reso...
import logging import copy import torch from crowd_sim.envs.utils.info import * class Explorer(object): def __init__(self, env, robot, device, memory=None, gamma=None, target_policy=None): self.env = env self.robot = robot self.device = device self.memory = memory self.gamm...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-02-04 21:33 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('books', '0001_initial'), ] operations = [ migrations.RenameField( model_n...
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: v1.10.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import si...
"""Fixtures for the Switch as X integration tests.""" from __future__ import annotations from collections.abc import Generator from unittest.mock import AsyncMock, patch import pytest @pytest.fixture def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock setting up a config entry.""" with patch...
import visa import numpy as np import logging from datetime import datetime resource_manager = visa.ResourceManager() class Aglient33250A(object): def __init__(self): self.instr = self.open_instrument() def open_instrument(self): resource_list = resource_manager.list_resources() gpi...
import json from django.db.models import FieldDoesNotExist class BaseCache(object): def get(self, version): raise NotImplementedError def set(self, version, data): raise NotImplementedError def delete(self, version): raise NotImplementedError class ModelCache(object): updat...
""" Functions to read resource files (.yml, .xls/.xlsx and images) """ # -*- coding: utf-8 -*- from os import path import pandas as pd import matplotlib.image as mpimg import numpy as np import yaml import pyshield as ps def load_item(item): """ Load yaml, image or excel or return value as is. """ if is...
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains th...
from dataclasses import dataclass from blspy import G1Element from profit.types.blockchain_format.sized_bytes import bytes32 from profit.util.ints import uint32 from profit.wallet.util.wallet_types import WalletType @dataclass(frozen=True) class DerivationRecord: """ These are records representing a puzzle ...
import logging import os import time from parsl.channels import LocalChannel from parsl.launchers import SimpleLauncher from parsl.providers.provider_base import ExecutionProvider, JobStatus, JobState from parsl.providers.error import ScriptPathError from parsl.utils import RepresentationMixin logger = logging.getLog...
# Copyright 2019 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
from __future__ import unicode_literals from django.db import models import re import json # import nlp try: import Queue as Q #python version < 3.0 except ImportError: import queue as Q #python3.* class wordBlock(): def __init__(self, start, end, kind): self.start = start; self.end = en...
import pickle def write_params_file(params_file,type_file,lower_file,upper_file,obj_file,max_f_eval): """ assembles known problem info and settings for NOMAD into a plain text file ---Inputs--- ---Outputs--- """ #get data from pickles type_list = pickle.load(open(type_file,'rb')) ...
#!/usr/bin/env python """ distutils/setuptools install script. """ import os import re from setuptools import find_packages, setup ROOT = os.path.dirname(__file__) VERSION_RE = re.compile(r'''__version__ = ['"]([0-9.]+)['"]''') requires = [ 'botocore>=1.24.29,<1.25.0', 'jmespath>=0.7.1,<2.0.0', 's3tran...
from django.shortcuts import render from postgresqleu.util.backendviews import backend_list_editor from postgresqleu.util.auth import authenticate_backend_group from postgresqleu.util.db import exec_to_dict from postgresqleu.accounting.backendforms import BackendAccountClassForm from postgresqleu.accounting.backendfo...
from __future__ import print_function import cv2 import os import shutil import pickle as pkl import time import numpy as np import hashlib from IPython import embed class Logger(object): def __init__(self): self._logger = None def init(self, logdir, name='log'): if self._logger is None: ...
"""Binary class.""" import os from subprocess import CalledProcessError from subprocess import check_output from subprocess import STDOUT class Binary(object): # pylint: disable=too-few-public-methods """Represent Binary structure.""" def __init__(self, path): # type: (str) -> None """Binary...
"""NFSP agents trained on simplified risk.""" from absl import app from absl import flags from absl import logging import tensorflow.compat.v1 as tf import numpy as np import igraph as ig import cairocffi import random import pyspiel from open_spiel.python import policy from open_spiel.python import rl_environment fr...
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Dict import textwrap from fastclasses_json.api import dataclass_json from fastclasses_json import core def test_to_dict_source(): @dataclass class A: x: int assert core._to_dict_source(A) == textwrap.dede...
#!/usr/bin/env python """Train the Text2Mel network. See: https://arxiv.org/abs/1710.08969""" __author__ = 'Erdene-Ochir Tuguldur' import sys import time import argparse from tqdm import * import numpy as np import torch import torch.nn.functional as F # project imports from models import Text2Mel from hyperparams ...
from sqlalchemy import Column, Integer, Float, DateTime SE_CREDENTIALS = {"apiKey": "XXXXXXXXX", "siteID": "12345"} SQL_CREDENTIALS = {"user": "user", "password": "password", "host": "ip:port" } SQL_SSL = {"CA": "/path/to/ca.pem", "C...
#!/usr/bin/env python # (c) Copyright 2017 Jonathan Simmonds # # Licensed under the MIT License # # 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 limita...
from django.core.management import BaseCommand import urllib2, json, urllib, base64 from main.models import * try: from biojs.settings import GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET except: print('ERROR: Could not load config!') GITHUB_CLIENT_ID = '' GITHUB_CLIENT_SECRET = '' from datetime import datetim...
""" response_hanlders.py """ from __future__ import print_function import sys def handle_bad_response_status_code(r): """ Handle a response with a bad status code """ ...
# Copyright 2015-2016 Google 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 applicable law...
# -*- coding: utf-8 -*- # @Time : 2020/7/2 15:16 # @Author : lightsmile # @Software: PyCharm from lighttext import KeywordProcessor if __name__ == '__main__': kp = KeywordProcessor() kp.add_keyword("曹操") kp.add_keyword("曹丕") kp.add_keyword("司马懿") kp.add_keyword("司马") stn = "曹操、曹丕和司马懿一起去吃大...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('markers', '__first__'), ('polls', '__first__'), ('neighborhood'...
from airflow.plugins_manager import AirflowPlugin from facebook_ads_plugin.hooks.facebook_ads_hook import FacebookAdsHook from facebook_ads_plugin.operators.facebook_ads_to_s3_operator import ( FacebookAdsInsightsToS3Operator, FacebookAdsToS3Operator, ) class FacebookAdsPlugin(AirflowPlugin): name = "face...
#!/usr/bin/env python # # Written by JM Lopez # GitHub: https://github.com/jm66 # Email: jm@jmll.me # Website: http://jose-manuel.me # # Note: Example code For testing purposes only # # This code has been released under the terms of the Apache-2.0 license # http://opensource.org/licenses/Apache-2.0 # import atexit imp...
'''Extension for Nemo's context menu to easily convert images to PNG and optimize their filesize with pngcrush.''' from __future__ import annotations import os import subprocess from urllib.parse import unquote_plus, urlparse from PIL import Image, UnidentifiedImageError import PySimpleGUI as sg import gi gi.require...
# Copyright 2015 The TensorFlow 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 applica...
# coding: utf-8 """ Portainer API OpenAPI spec version: 1.24.1 Contact: info@portainer.io Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class DockerHubSubset(object): """NOTE: This class is auto generated by the swagger ...
from Exercise_115.Interface import * from Exercise_115.Functions import * data_base = 'registers.txt' while True: screen() options = menu('Type a value: ') print(line()) if options == 1: if validation_file(data_base) == True: name = str(input('Type the name: ')) age =...
import subprocess def cli_returncode(argument_string): p = subprocess.Popen(argument_string,shell=True,stdout=subprocess.PIPE) print str(p.communicate()[0]) p.wait() rc = p.returncode return rc def cli_output(argument_string): p = subprocess.Popen(argument_string,shell=True,stdout=subprocess...
# 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, software # distributed u...
import threading import numpy as np import torch import os.path as osp from rl.utils import mpi_utils #Replay buffer!!! def sample_her_transitions(buffer, reward_func, batch_size, future_step, future_p=1.0): assert all(k in buffer for k in ['ob', 'ag', 'bg', 'a']) buffer['o2'] = buffer['ob'][:, 1:, :] bu...
from django.conf import settings from django.contrib import admin from django.db import IntegrityError from django.db.models import Exists, OuterRef, Q from django.utils.translation import gettext as _ from import_export import resources from import_export.admin import ImportExportMixin, ImportExportModelAdmin from de...
# Auto-generated at 2021-09-27T17:12:38.701190+08:00 # from: Justice Basic Service (1.17.0) # Copyright (c) 2018 - 2021 AccelByte Inc. All Rights Reserved. # This is licensed software from AccelByte Inc, for limitations # and restrictions contact your company contract manager. # pylint: disable=duplicate-code # pylin...
from datetime import datetime from http.client import responses as STATUS_MESSAGES from http.cookies import SimpleCookie import mimetypes import os from .case_insensitive_dict import CaseInsensitiveDict class Response(BaseException): def __init__(self): self.status = 404 self.headers = CaseInsen...
from onelang_core import * import OneLang.One.Ast.Expressions as exprs import OneLang.One.Ast.Statements as stats import OneLang.One.Ast.Types as types import OneLang.One.Ast.AstTypes as astTypes import OneLang.One.Ast.References as refs import OneLang.One.Ast.Interfaces as ints import onelang_core as one import json i...
###################################################################### # Copyright (c) # All rights reserved. # # This software is licensed as described in the file LICENSE.txt, which # you should have received as part of this distribution. # ###################################################################### """ In...
from collections import namedtuple from guillotina import configure from guillotina import schema from guillotina.component import get_adapter from guillotina.exceptions import ComponentLookupError from guillotina.exceptions import ValueDeserializationError from guillotina.fields.interfaces import IDynamicField from gu...
n = int(input()) if n == 7 or n == 5 or n== 3: print("YES") else: print("NO")
# -*- coding: utf-8 -*- import imaplib import email from email.header import decode_header import time import re import mimetypes import chardet try: unicode('') except NameError: # for python3 compatibility. unicode = str class MailObj(object): def __init__(self, message, uid=-1, raw=''): ...
# Generated by Django 2.0.6 on 2019-10-03 21:22 from django.db import migrations, models import django.db.models.expressions class Migration(migrations.Migration): dependencies = [ ('estoque', '0001_initial'), ] operations = [ migrations.CreateModel( name='Telefone_Fornecedo...
from sqlalchemy import Column, Integer, String from server.db.database import Base class Book(Base): """ Books in a library """ __tablename__ = 'books' id = Column(Integer, primary_key=True) name = Column(String(50), unique=True) def __init__(self, name=None, email=None): self.name = name...
# Copyright 2017, 2018 Amazon.com, Inc. or its affiliates. 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. A copy of the License # is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" fi...
#!/usr/bin/python3 """Recipe for training a speaker verification system based on PLDA using the voxceleb dataset. The system employs a pre-trained model followed by a PLDA transformation. The pre-trained model is automatically downloaded from the web if not specified. To run this recipe, run the following command: ...
import itertools import numpy as np def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = itertools.tee(iterable) next(b, None) return zip(a, b) def struct_to_ndarray(array): """Turns returns a view of a structured array as a regular ndarray.""" return array.view(array.dtype[0...
#!/usr/bin/python3 from urllib.parse import urlparse from crawler.error.urlerror import DomainUrlError from crawler.utils.strtool import find_last_index def start_with(str, prefix): if str[0: len(prefix)] == prefix: return True else: return False def get_domain_url(url): url_parse = urlpa...
from pathlib import Path from tempfile import NamedTemporaryFile, SpooledTemporaryFile from unittest import TestCase from click.testing import CliRunner from duplicity_backup_s3.config import check_config_file class TestConfig(TestCase): def test_default_config_provided_by_package(self): from duplicity_...
__all__ = ["get_fl", "disp", "select"]
from libai.config import LazyCall, get_config from .models.palm_small import model from libai.evaluation import PPLEvaluator graph = get_config("common/models/graph.py").graph train = get_config("common/train.py").train optim = get_config("common/optim.py").optim data = get_config("common/data/gpt_dataset.py") datalo...
""" kbible.py - base bible object and commands """ import pandas as pd import yaml import os import subprocess __author__ = "Sungcheol Kim <sungcheol.kim78@gmail.com>" __docformat__ = "restructuredtext en" class KBible(object): """ Bible text object """ def __init__(self, version="개역한글판성경", debug=False, **k...
#!/usr/bin/env python # # __COPYRIGHT__ # # 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, ...
def main(important_parameter, ignored_parameter): """ :return: The answer to everything """ important_field = important_parameter # this way the parameter was actually used, hence making it important. def realmain(): def actualrealrealmain(): def nownoteve...
""" snake/food_obj.py author: Stephen Radley date: 2018/07/05 package: snake version: 0.0.1 """ from random import randint from snake.location_obj import Location from snake.functions import find_valid_locs """ Food ... """ class Food: """ __init__ ... """ def __ini...
from time import sleep import matplotlib.pyplot as plt import numpy as np from sot_talos_balance.utils.run_test_utils import evalCommandClient, run_ft_calibration, run_test, runCommandClient try: # Python 2 input = raw_input # noqa except NameError: pass run_test('appli_zmpEstimator.py') run_ft_calibr...
import pybullet as p import math import pybullet_data import time import random import numpy as np import serial def radToPwm(angle): return ((2000 * angle) / math.pi) + 1500 # t in ms; the closer t is to 0, more accuracy but less smooth motion def updateRealServos(ser, t): # right legs ser.write( ...
from web import app from gevent.pywsgi import WSGIServer if __name__ == '__main__': http_server = WSGIServer(('', 5000), app) http_server.start() http_server.serve_forever()
import math import torch from pixelflow.distributions import Distribution from pixelflow.utils import sum_except_batch from torch.distributions import Normal class StandardNormal(Distribution): """A multivariate Normal with zero mean and unit covariance.""" def __init__(self, shape): super(StandardNo...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
import argparse import json import os import pickle import sys import sagemaker_containers import pandas as pd import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.utils.data from model import LSTMClassifier from utils import review_to_words, convert_and_pad def model_fn(mod...
from .scraping import evaluate_comment_reply_pair __all__ = [ "evaluate_comment_reply_pair", ]
# Copyright 2021 NEC 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...
# Copyright (c) 2014 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Helpful routines for regression testing # # Add python-bitcoinrpc to module search path: import os import sys from decimal impor...
number = int(input("Enter an integer number: ")) for i in range(number, 0, -1): print(i)
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( smuggle_url, ExtractorError, ) class SBSIE(InfoExtractor): IE_DESC = 'sbs.com.au' _VALID_URL = r'https?://(?:www\.)?sbs\.com\.au/(?:ondemand(?:/video/(?:single/)?|.*?\bplay=)|news/(?:embeds...
import pandas as pd import itertools from functools import partial from fastai.callbacks import CSVLogger def get_config_df(config): df = pd.DataFrame(list(itertools.product(*config.values())), columns=config.keys()) df.index = [f'model_{i+1}' for i in range(len(df))] return df def create_experiment(nm, ...
import supriya def _build_synthdef(): with supriya.SynthDefBuilder(amplitude=0, bus=0, frequency=440) as builder: supriya.ugens.Out.ar( bus=builder["bus"], source=supriya.ugens.SinOsc.ar(frequency=builder["frequency"]) * builder["amplitude"], ) return builde...
#!/usr/bin/env python from flask import Flask, request app = Flask(__name__) # Shared storage for our list of tasks tasks = ["GenCS 1"] form = ("<form action='/' method='POST'>" "<input autofocus type='text' name='task' />" "<input type='submit' />" "</form>") def delete_form(idx): retur...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayOpenPublicPartnerMenuOperateModel(object): def __init__(self): self._action_param = None self._action_type = None self._agreement_id = None self._public_id =...
"""Dummy backend for testing basic interaction of projects and backends""" from annif.suggestion import SubjectSuggestion, ListSuggestionResult from . import backend class DummyBackend(backend.AnnifLearningBackend): name = "dummy" initialized = False uri = 'http://example.org/dummy' label = 'dummy' ...
from nose.tools import eq_ import inflect def test_ancient_1(): p = inflect.engine() # DEFAULT... eq_(p.plural_noun("Sally"), "Sallys", msg="classical 'names' active") eq_(p.plural_noun("Jones", 0), "Joneses", msg="classical 'names' active") # "person" PLURALS ACTIVATED... p.classical(nam...
import math import time from .locators import BasePageLocators from selenium.common.exceptions import NoSuchElementException, NoAlertPresentException, TimeoutException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class BasePage(): def __i...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
"""todoList URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-base...
class Student(object): def __init__(self, name): self.name = name def __repr__(self): print "8"*20 return 'Student object (name: %s)' % self.name def __str__(self): print "*"*20 return 'Student object str (name: %s)' % self.name def __call__(self): print ...
""" Main program for 2to3. """ from __future__ import with_statement, print_function import sys import os import difflib import logging import shutil import operator import optparse from . import refactor def diff_texts(a, b, filename): """Return a unified diff of two strings.""" a = a.splitlines() b =...
"""A mock type that returns features data.""" import pandas as pd import woodwork as ww from facilyst.mocks import MockBase from facilyst.mocks.mock_types.utils import mock_features_dtypes class Features(MockBase): """Class to manage mock data creation of features. :param num_rows: The number of observation...
# coding=utf-8 """ spellcheck.py - Sopel spell check Module Copyright © 2012, Elad Alfassa, <elad@fedoraproject.org> Copyright © 2012, Lior Ramati Licensed under the Eiffel Forum License 2. http://sopel.chat This module relies on pyenchant, on Fedora and Red Hat based system, it can be found in the package python-enc...
#!/bin/env python """ ThorLabs TDC001 and KDC001 cubes Low Level code. This code specifies communication protocola for T snd K cubes. Valentyn Stadnytskyi valentyn.stadnytskyi@nih.gov The communication protocols: https://www.thorlabs.com/Software/Motion%20Control/APT_Communications_Protocol.pdf issue 20 """ from t...
import sys from ocumol.leapConfig import leapPath if leapPath not in sys.path: sys.path.append(leapPath) #from ocumol.src.hands.leap_only import PymolListener # from ocumol.src.pymol.pymolHmd import PymolHmd, pymolHmdScript
import email import StringIO from nose.tools import assert_raises from lxml import etree from webob import Request import nose import cc.license from cc.engine import util util._activate_testing() class FakeAcceptLanguage(object): def __init__(self, best_matches): self._best_matches = best_matches ...
"""Performs attention intervention on Winobias samples and saves results to JSON file.""" import json import fire from pandas import DataFrame from transformers import ( GPT2Tokenizer, TransfoXLTokenizer, XLNetTokenizer, BertTokenizer, DistilBertTokenizer, RobertaTokenizer ) import winobias from attention_ut...
""" Prime Developer Trial No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v1 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from fds.sdk.S...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
#!/usr/bin/env python3 # Install pip3 (if not there) # sudo apt-get install python3-pip # Install zmq with # pip3 install pyzmq # Install bitcoinrpc with # pip3 install python-bitcoinrpc # Install ipfsapi with # pip3 install ipfsapi import sys import argparse import zmq import struct import binascii imp...
def set_message(message): content = { "message": message } return content
import os import serial from time import sleep ser = serial.Serial('/dev/ttyACM0',9600) #counter = 32 flame = False newflame = False while True: #counter +=1 value = ser.readline() print(value) try: if int(value) > 400: newflame = True else: newflame = False ...
from math import ceil def chunk(lst, size): return list( map(lambda x: lst[x * size:x * size + size], list(range(0, ceil(len(lst) / size))))) def find_str_index(str1, str2): if not str2: return "str2 not none" for x in str2: if x in str1: return str1.index...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ Topic: 下降解析器 Desc : """ import re import collections # Token specification NUM = r'(?P<NUM>\d+)' PLUS = r'(?P<PLUS>\+)' MINUS = r'(?P<MINUS>-)' TIMES = r'(?P<TIMES>\*)' DIVIDE = r'(?P<DIVIDE>/)' LPAREN = r'(?P<LPAREN>\()' RPAREN = r'(?P<RPAREN>\))' WS = r'(?P<WS>\s+...
import re import sys shape_file = sys.argv[1] pattern = re.compile("^>.*$") toWrite = "" count_for_id = 1 seq_counter = 0 new_id = "" seq_id = [] seq_string = [] orig_id = [] name_file = "FASTA/data.names" array_all_chunks = [] with open(name_file, "r") as f: for line in f: if len(line.strip()) == 0: ...
from __future__ import division import os, glob import pandas as pd import math import numpy as np from scipy.spatial import ConvexHull import scipy from configparser import ConfigParser, NoOptionError, NoSectionError from numba import jit from simba.rw_dfs import * import re def extract_features_wotarget_16(inifile)...
import rospy from pid import PID from lowpass import LowPassFilter from yaw_controller import YawController """ This file contains a stub of the Controller class. You can use this class to implement vehicle control. For example, the control method can take twist data as input and return throttle, brake, and steering ...
# Thomas (Desnord) # O objetivo desta tarefa é fazer um programa # que use recursividade e que, dada a matriz # que descreve a hierarquia de uma empresa, # encontre a cadeia hierárquica relativa a # um determinado funcionário. #entrada: # A primeira linha contém dois inteiros: n, # o número de funcionários entre 3 ...