content
stringlengths
5
1.05M
import datetime import enum RFC3339Nano = "%Y-%m-%dT%H:%M:%SZ" USER_AGENT = "rmcl <https://github.com/rschroll/rmcl>" DEVICE_TOKEN_URL = "https://webapp-production-dot-remarkable-production.appspot.com/token/json/2/device/new" USER_TOKEN_URL = "https://webapp-production-dot-remarkable-production.appspot.com/token/json...
# Ivan Carvalho # Solution to https://www.urionlinejudge.com.br/judge/problems/view/1799 #!/usr/bin/env python2.7 # encoding : utf-8 from heapq import heappush,heappop def dijkstra(graph,start): a = {x:None for x in graph.keys()} queue = [(0,start)] while queue: distance,v = heappop(queue) if a[v] is None : a...
__author__ = 'Juxi Leitner, [email protected]' from pybrain.rl.environments import EpisodicTask from docking import DockingEnvironment from math import fabs class DockingTask(EpisodicTask): __name__ = "Docking Task" logBuffer = None logging = False logfileName = None timeNeuron_Threshold = 0.9...
# game.py #IMPORTS import random #INTRODUCTION print("Rock, Paper, Scissors, Shoot!") print(" ") # CAPTURE INPUTS user_choice = input("Please choose one of the following options: 'rock', 'paper' or 'scissors' (without the quotes) ") print("------------------") print("You chose:", user_choice) print(" ") # VA...
''' distance2clusters.py - RNAseq timeseries analysis ==================================================== :Author: :Release: $Id$ :Date: |today| :Tags: Python Purpose ------- Script for clustering analysis of distance matrices. Script functions are: * combine multiple clusterings by averaging distance matrix or con...
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. 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 requir...
class BSTNode: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right class BST: def __init__(self, data=None): if data is None: self.root = None else: self.root = BSTNode(data) def insert(self,...
#!usr/local/bin/python3 import scipy.io as scio import numpy as np import matplotlib.pyplot as plt import random as random import copy from math import sqrt ## Node class Node(object): def __init__(self): self.id_ = -1 self.position_ = np.array([-1.0, -1.0], dtype = int) self.parent_ = -1...
# Copyright (c) 2017-2019 Neogeo-Technologies. # 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...
# http.response import datetime import os from .settings import HTML_ROOT # status codes # informational CONTINUE = 100 SWITCHING_PROTOCOLS = 101 PROCESSING = 102 # successful OK = 200 CREATED = 201 ACCEPTED = 202 NON_AUTHORITATIVE_INFORMATION = 203 NO_CONTENT = 204 RESET_CONTENT = 205 PARTIAL_CONTENT = 206 MULTI_S...
# -*- coding: utf-8 -*- # © 2017-2019, ETH Zurich, Institut für Theoretische Physik # Author: Dominik Gresch <[email protected]> """ Defines a calculation to run the ``bands-inspect align`` command. """ import six from aiida.engine import CalcJob from aiida.common import CalcInfo, CodeInfo from aiida.plugins import Dat...
from trabalho_final.caches import cache from numpy import inf import json class Config: def __init__( self, file_path='default_config.json', client2CacheRate = None, client2CacheP = None, timeoutRate = None, cache2Server2CacheRate = None, alternativeServerRa...
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import import sys from pex.tools.main import main as tools sys.exit(tools())
def statusname(sid): from app import app return app.config["STATUSES"][sid]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Euler discovered the remarkable quadratic formula: n² + n + 41 It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 41² + 41 +...
import time from google.protobuf.message import Message from k8s.io.apimachinery.pkg.apis.meta.v1.generated_pb2 import ObjectMeta from modela.common import ObjectReference from modela.ModelaException import ResourceNotFoundException, ResourceExistsException, GrpcErrorException class Resource: """ Base class...
""" A library of pre-defined blocks. - - - - - - Docs: https://edzed.readthedocs.io/en/latest/ Home: https://github.com/xitop/edzed/ """
import pandas as pd import numpy as np import re import os from collections import Counter import pickle import codecs import pickle from sklearn.preprocessing import LabelEncoder import spacy ids = [] sentences = [] titles = [] link = [] with open("Datasets/wikipedia-biography-dataset/train/train.id") ...
""" This piece of source code is part of FADCIL project from Visibilia More details about this project at: http://visibilia.net.br/fadcil Last updated: 11/17/2020 """ from tensorflow.keras import Model from tensorflow.keras.layers import Input, BatchNormalization, Conv3D, Concatenate, Cropping3...
## # This software was developed and / or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted data whose # export/transfer/disclosure is restricted by U.S. law. Dissemination # to ...
import numpy as np from ConfigSpace.configuration_space import ConfigurationSpace from ConfigSpace.hyperparameters import UniformFloatHyperparameter, \ CategoricalHyperparameter from autosklearn.pipeline.components.base import AutoSklearnClassificationAlgorithm from autosklearn.pipeline.constants import * class...
#!/usr/bin/env python # coding: utf-8 # In[1]: import os, sys, time, random from pathlib import Path ############################################################################################################## ##DO NOT change this part. ##../setup.py will update this variable HTC_package_path = "C:/Users/tyang/Do...
"""Internal module that contains functions to handle datetime related operations.""" # =============================================================== # Imports # =============================================================== # Standard Library import logging from typing import Optional # Third Party import pandas ...
import os import time import argparse import importlib.util from scipy.integrate import ode from cellsolver.codesamples import hodgkin_huxley_squid_axon_model_1952 as hh from cellsolver.plot import plot_solution KNOWN_SOLVERS = ['euler', 'dop853', 'vode'] class TimeExecution(object): number = 10 run_tim...
def atbash(string): s2='' for char in string: if char.islower()==True: s2+=chr(122-(ord(char)-97)) elif char.isupper()==True: s2+=chr(90-(ord(char)-65)) else: s2+=char string=s2 return string
"""Test for parser.omega""" import pytest import fromconfig @pytest.mark.parametrize( "config, expected", [ pytest.param(None, None, id="none"), pytest.param({"foo": "bar"}, {"foo": "bar"}, id="none"), pytest.param({"foo": "bar", "baz": "${foo}"}, {"foo": "bar", "baz": "bar"}, id="va...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Script to interpolate atmospheric data from UERRA: increase temporal resolution, and save into speed, cosine of angle and sine of angle, pressure and pressure gradient Created on Mon Apr 11 15:01:26 2022 @author: Matias Duran-Matute ([email protected]) """ #%...
"""Scrape GADM website for geospatial package link.""" from bs4 import BeautifulSoup from datetime import datetime as dt from selenium import webdriver from selenium.webdriver.support.ui import Select import requests import time import pandas url = 'https://gadm.org/download_country_v3.html' base_url = 'https://biog...
from easycore.common.network import download_file import os def test_download_file(): url = "https://github.com/YuxinZhaozyx/easycore/archive/v0.3.4.zip" dir = os.path.dirname(__file__) file_path = download_file(url, dir) os.remove(file_path) if __name__ == '__main__': import logging log...
# coding: utf-8 import glob import os def matched_exclude(fn, patterns): for pat in patterns.split(','): if glob.fnmatch.fnmatch(fn, pat.strip()): return True return False def count_lines(directory, ext=None, exclude_patterns=None, exfuncs=None, detail=False): '''Cou...
from django import forms from .models import Article class ArticleForm(forms.ModelForm): class Meta: model = Article fields = [ 'title', 'date', 'abstract', 'body' ] def clean_title(self): title = self.cleaned_data.geta('title') ...
r"""Observables in $D$ meson decays.""" from . import dlnu
# -*- coding: utf-8 -*- """ @File : config.py @Time : 2020/7/7 下午3:08 @Author : yizuotian @Description : 配置类 """ class Config(object): def __init__(self, **kwargs): super(Config, self).__init__(**kwargs) self.alpha = ' abel一丁七万丈三上下不与丐丑专且世丘丙业丛东丝丢两严丧个中丰串临丸丹为主丽举乃久么义之乌乍乎乏乐乒乓乔乖乘乙九乞也习乡书买乱乳...
""" Making use of the REST API (NeuroMorpho.org v7) to query the database """ """ Ahmad made two changes 1- added html = html.decode('ISO-8859-1') on line 99 2- changed open(fileName, 'w').write(response.read()) to open(fileName, 'wb').write(response.read()) """ # python v2 or v3 try: from urllib2 import urlopen, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from yosaipy2.web.registry.abcs import WebRegistry from flask import request, g from typing import Callable, Dict, Any from werkzeug.exceptions import Forbidden, Unauthorized import json class FlaskWebRegistry(WebRegistry): def __init__(self): # type: (Callabl...
import json import click import requests import os from fandogh_cli.config import get_user_config, get_cluster_config, get_user_token, get_cluster_namespace from fandogh_cli.utils import convert_datetime, parse_key_values, TextStyle, format_text cluster_url = [key['url'] for key in get_cluster_config() if key['active...
import numpy as np import fire from utilities import parse_matrix def tdma_solve(matrix: np.ndarray, rhs: np.ndarray) -> np.ndarray: """Решение СЛАУ с трёхдиагональной матрицей методом прогонки :param matrix: матрица коэффициентов :param rhs: вектор правых частей :return: решение СЛАУ """ b ...
from some_bandits.bandits.egreedy import egreedy from some_bandits.bandits.EXP3 import EXP3 from some_bandits.bandits.EXP4 import EXP4 from some_bandits.bandits.UCB import UCB from some_bandits.bandits.UCBImproved import UCBImproved from some_bandits.bandits.UCBNorm import UCBNorm from some_bandits.bandits.SWUCB ...
import torch import random import numpy as np import tensorrt as trt from torchvision import datasets, transforms, models from torch import nn, optim import onnx import torch.nn.functional as F import pycuda.driver as cuda import pycuda.autoinit from PIL import Image import argparse from utils import preprocess_image, ...
import logging.config import os from jans.pycloudlib import get_manager from jans.pycloudlib import wait_for from jans.pycloudlib import wait_for_persistence from jans.pycloudlib.validators import validate_persistence_type from jans.pycloudlib.validators import validate_persistence_hybrid_mapping from jans.pycloudlib....
""" The conmon package for container monitoring. """ __all__ = []
class Student: def __init__(self, name, score): self.name = name self.score = score # for python2 use __cmp__ def __lt__(self, other): return self.score < other.score def __str__(self): return "{}: {}".format(self.name, self.score) class PriorityQueue: def __init_...
from distutils.core import setup setup( name='htmlparser', packages=['htmlparser'], version='1.0.0', description='Parse html to extract required content', author='Akhil Ramachandran', author_email='[email protected]', url='https://github.com/akhilram/htmlparser', classifiers=[ 'D...
# -*- coding: utf-8 -*- UNIVERSITY_DOMAINS = { 'um.edu.ar': [u'Universidad de Mendoza'], 'unsa.edu.ar': [u'Universidad Nacional de Salta'], 'uces.edu.ar': [u'Universidad de Ciencias Empresariales y Sociales'], 'unq.edu.ar': [u'Universidad Nacional de Quilmes'], 'ucel.edu.ar': [u'Universidad del Cen...
#!/usr/bin/env python # -*- coding: UTF-8 -*- import rospy import dynamic_reconfigure.client import serial from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QWidget, QLabel, QMessageBox import sys class Q_Window(QWidget): def __init__(self): sup...
# -*- coding: utf-8 -*- from south.db import db from south.v2 import SchemaMigration from ..compat import get_user_model User = get_user_model() user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name) user_model_label = '%s.%s' % (User._meta.app_label, User._meta.module_name) class Migration(Sche...
#! -*- coding: utf-8 -*- import jieba import numpy as np import tensorflow as tf import datetime from bert4keras.models import build_transformer_model from bert4keras.snippets import AutoRegressiveDecoder from bert4keras.tokenizers import Tokenizer config_path = './chinese_t5_pegasus_base/config.json' checkpoint_path ...
import sys import os import math from dataclasses import dataclass from typing import overload import time from tkinter import Tk from tkinter.filedialog import askopenfile from editor_utils.font import font from editor_utils.atlas import atlas _stdout = sys.stdout sys.stdout = open(os.devnull,'w') ...
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\carry\put_down_strategy.py # Compiled at: 2019-01-17 03:59:06 # Size of source mod 2**32: 5644 bytes...
from __future__ import absolute_import import hashlib import hmac import logging import six from django.http import HttpResponse from django.utils.crypto import constant_time_compare from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from simplejson import JSONDe...
# Enter your code here. Read input from STDIN. Print output to STDOUT x,k=map(int,input().split()) p=input() if eval(p)==k: print(True) else: print(False)
# -*- coding: utf-8 -*- """ 1385. Find the Distance Value Between Two Arrays Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays. The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <...
import pandas as pd import numpy as np import argparse parser = argparse.ArgumentParser() parser.add_argument("--model_prefix", default=None, type=str, required=True) parser.add_argument("--out_path", default=None, type=str, required=True) args = parser.parse_args() df = pd.read_csv('data/test.csv', sep=',') temp = pd...
import sys import argparse import os import Utils import SeriesModel import Results import pickle def CmdLine( args ): seriesFileName = None if args.series: seriesFileName = args.series try: with open(seriesFileName, 'rb') as fp: SeriesModel.model = pickle.load( fp, encoding='latin1', errors='replace' ) ...
import datetime from django.db import models # Create your models here. class Doctor(models.Model): name = models.CharField(max_length = 100) specialization = models.CharField(max_length = 40) def __str__(self): return 'Врач {0}, {1}'.format(self.name, self.specialization) def appointme...
from threading import Thread import cv2 from Constants import Constants class ImageThread(Thread): def __init__(self, mat): super(ImageThread, self).__init__() self.mat = mat def run(self): print("Starting Proccessing\n") hsv = cv2.cvtColor(self.mat, cv2.COLOR_BGR2HSV) ...
# Copyright 2019 Xilinx 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, ...
from textwrap import dedent import unittest.mock as mock from pathlib import Path from typing import Annotated import pytest from .exceptions import * from .parser import * from .transformers import * def assert_type_value(value, assert_type: type, assert_value): __tracebackhide__ = True assert isinstance(v...
# -*- coding: utf-8 -*- """Utilities for getting and initializing KGE models.""" import logging import random import timeit from typing import Any, Iterable, List, Mapping, Optional, Union import numpy as np import pykeen.constants as pkc import rdflib import torch import torch.optim as optim from pykeen.constants i...
categories = [ "floating_point", "integer", ] microcode = ''' # AVX512 instructions ''' for category in categories: exec("from . import {s} as cat".format(s=category)) microcode += cat.microcode
import numpy as np def solve_matrix(augmented_matrix: np.ndarray) -> (np.ndarray, np.ndarray): augmented_matrix = np.array(augmented_matrix.copy()) # Split matrix to matrix and results_vector results_vector: np.ndarray = augmented_matrix[:, -1] matrix: np.ndarray = np.delete(augmented_matrix, -1, axi...
# Copyright 2018/2019 The RLgraph 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...
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import configure_mappers, create_session from literature.database.main import Base from literature.models.author_model import AuthorModel from literature.models.cross_reference_model import CrossReferenceModel from literature.models.editor_mod...
""" Tests for the custom jupyter contents manager """ import sys import os from pathlib import Path from unittest.mock import Mock import yaml from ipython_genutils.tempdir import TemporaryDirectory from notebook.services.contents.tests.test_manager import TestContentsManager from notebook.notebookapp import NotebookA...
from .augmentations import augment from .types import Data, Batch, AugmentationColumns, AugmentationProbability, BatchSize def next(data: Data, augmentation_columns: AugmentationColumns, augmentation_probability: AugmentationProbability, batch_size: BatchSize) -> Batch: '''This function implements the batch genera...
################################ # @Time : 5/7/2021 # @Author : Yenchia Yu # @Mail : [email protected] # @Github : https://github.com/Rexyyj # @Note : None ################################
n=int(input("ENTER A DAY NUMBER IN RANGE 2 TO 365 ")) fdy=input("ENTER THE FIRST DAY OF YEAR ") w=['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] ws=[] while len(ws)!=7: for a in w: if a==fdy and a not in ws: ws.append(a) if a not in ws: if a==f...
s = set({11, 22, 33, 44, 55, 66, 77, 66, 55, 44, 33, 22, 11}) # print(s) # for val in s: # print('Set Values: ', val) # Add method in Set s.add(5) # print(s) # Remove method in Set s.remove(5) # clear s.clear() python_class = {'Taher', 'Fatima', 'Mustafa', 'Mameet'} web_class = {'Zainab', 'Qaidjohar', 'Taher...
from django.test import TestCase from casexml.apps.case.dbaccessors import get_open_case_docs_in_domain, \ get_open_case_ids_in_domain from casexml.apps.case.models import CommCareCase from casexml.apps.case.util import create_real_cases_from_dummy_cases from corehq.apps.hqcase.dbaccessors import get_number_of_case...
#!/usr/bin/python import subprocess def main(): layout_map = {"us":"EN", "il":"HE", "ru":"RU"} layout = subprocess.Popen("/home/lxgreen/scripts/wm" "/language_bar/xkb-switch", stdout=subprocess.PIPE).stdout.read() print layout_map[layout[:2]] if __name__ == '__main__': main()
#setting the domain size for the problem to be solved domain_size = 3 ################################################################## ################################################################## ## ATTENTION: here the order is important #including kratos path kratos_libs_path = '../../../../libs/' ##kratos_r...
# -*- coding: utf-8 -*- import random from collections import deque, namedtuple Transition = namedtuple('Transition', ('state', 'action', 'reward', 'policy')) class EpisodicReplayMemory(): def __init__(self, capacity, max_episode_length): # Max number of transitions possible will be the memory capacity, could ...
""" This notebook plots the Magpie feature space for the Gaultois database with several dimensional reduction algorithms (t-SNE, UMAP, PCA) to check for clustering. """ # %% import matplotlib.pyplot as plt import pandas as pd from plotly import express as px from sklearn.decomposition import PCA from sklearn.manifold...
def counter_effect(hit_count): return [range(int(i)+1) for i in hit_count]
import json import unittest from django.core.mail.message import EmailMessage import django_gearman_proxy.settings django_gearman_proxy.settings.GEARMAN_EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' django_gearman_proxy.settings.GEARMAN_EMAIL_SERIALIZER = 'django_gearman_proxy.serializers.mail.json.se...
import data_importer from models.model_base import ModelBase LM_POSITIVE_WORDS, LM_NEGATIVE_WORDS = data_importer.import_lm_dictionary() NEGATE = { "aint", "arent", "cannot", "cant", "couldnt", "darent", "didnt", "doesnt", "ain't", "aren't...
import sys verbose = False def newLine(): info("") def critical(msg): """ Print critical message to stderr """ sys.stderr.write(msg) sys.stderr.write('\n') def info(msg): infoWithoutNewLine(msg + '\n') def infoWithoutNewLine(msg): if verbose: sys.stdout.write(msg)
from threading import Thread import requests from constants import BATCH_SIZE, NUMBER_REQUESTS, URL_FASTER def crawler(url): response = requests.get(url) if response.status_code != 200: print('error') return response.status_code if __name__ == '__main__': size = int(NUMBER_REQUESTS/BATCH_S...
# -*- coding: utf-8 -*- # # Copyright (c) 2016 - 2022 -- Lars Heuer # All rights reserved. # # License: BSD License # """\ SVG related tests for multicolor support. """ from __future__ import absolute_import, unicode_literals import io import xml.etree.ElementTree as etree import pytest import segno from segno import w...
import hashlib import envi import envi.archs.amd64 as e_amd64 from vivisect.symboliks.common import * import vivisect.symboliks.archs.i386 as vsym_i386 import vivisect.symboliks.analysis as vsym_analysis import vivisect.symboliks.callconv as vsym_callconv from envi.archs.amd64.vmcslookup import VMCS_NAMES class VMCS...
import click from myfi.cli import pass_context @click.command('loadofx', short_help='Import OFX files.') @click.argument('ofxfile', nargs=-1) @pass_context def cli(ctx, ofxfile): """Import OFX files.""" from myfi.loadofx import loadofx loadofx(ctx.session, ofxfile)
from ..data.data import WORD_VOCAB_FILE, PUNCTUATION_VOCABULARY, CHAR_VOCAB_FILE from ..data.data import read_vocabulary, iterable_to_dict from ..utils.data_utils import load_embeddings import os class Config: def __init__(self): if not os.path.exists(self.ckpt_path): os.makedirs(self.ckpt_pat...
#!/bin/env python # -*- coding: utf-8 -*- import os import sys import codecs import re import configparser # Type of printing. OK = 'ok' # [*] NOTE = 'note' # [+] FAIL = 'fail' # [-] WARNING = 'warn' # [!] NONE = 'none' # No label. class ErrorChecker: def __init__(self, util...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2019-07-09 23:22 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone def create_default_book(apps, schema_editor): Book = apps.get_mode...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # michael a.g. aïvázis # orthologue # (c) 1998-2021 all rights reserved # """ Verify searching through folders for named nodes """ def test(): # support import pyre.primitives # my package import pyre.filesystem # build a folder root = pyre.f...
developer_nrel_gov_key = "" def set_developer_nrel_gov_key(key: str): global developer_nrel_gov_key developer_nrel_gov_key = key def get_developer_nrel_gov_key(): global developer_nrel_gov_key if len(developer_nrel_gov_key) != 40: raise ValueError("Please provide NREL Developer key using `se...
from __future__ import annotations from setuptools import setup setup()
import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Categorical from collections import OrderedDict from maml_rl.policies.policy import ConvLSTM, ConvGRU import numpy as np class ConvCLSTMPolicy(nn.Module): """ Baseline DQN Architecture """ def __init__(s...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # C++ version Copyright (c) 2006-2007 Erin Catto http://www.box2d.org # Python version by Ken Lauer / sirkne at gmail dot com # # This software is provided 'as-is', without any express or implied # warranty. In no event will the authors be held liable for any dam...
def quicksort(array) : if len(array) < 2 : return array else : pivot = array[0] less = [i for i in array[1:] if i <= pivot] greate = [i for i in array[1:] if i > pivot] return quicksort(less) + [pivot] + quicksort(greate) array = [1,5,2,3,7,6] print(quicksort(array))
# Complete the check_log_history function below. def check_log_history(events): stack = [] row = 0 for event in events: row += 1 if event.startswith('A'): lockNum = event.split(' ')[1] # 重复输入 if lockNum in stack: return row stac...
import _init_paths from fast_rcnn.config import cfg import argparse from utils.timer import Timer import numpy as np import cv2 from utils.cython_nms import nms from utils.transform import lidar_3d_to_corners, corners_to_bv, lidar_cnr_to_img_single, lidar_cnr_to_img from utils.draw import show_lidar_corners, show_image...
# Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs") # and others. 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://w...
import autoencoder as ae import manifold as mf import process as pc import matplotlib.pyplot as plt import datetime if __name__ == '__main__': path = 'data/interpolate_gos/' signals, filenames = ae.load_data(path) gos_map = pc.gos_loader() total_image = [] total_signal = [] file_len_map = {} bef_cnt = ...
#!/usr/bin/env python2 import re import sys import IPython import ipdb # noqa import requests # noqa try: import scrapy # noqa except ImportError, e: print 'warning: scrapy import: %s' % e def start_ipython(fix_argv=True, *args, **kwargs): if fix_argv: sys.argv[0] = re.sub(r'(-script\.pyw|\.ex...
from ansiblemetrics.ansible_metric import AnsibleMetric class NTS(AnsibleMetric): """ This class implements the metric 'Number Of Tasks' in an Ansible script. """ def count(self): """ Return the number of tasks in a playbook. """ return len(self.yml)
import logging import unittest import sys from multiprocessing.queues import Queue as MQueue is_py2 = sys.version[0] == '2' if is_py2: import mock from Queue import Queue else: from unittest import mock from queue import Queue from splunk_handler import SplunkHandler # These are intentionally differ...
__author__ = 'golfape' from pynearest.containers import _SortedRealDict import numpy as np def deterministic_srd(): srd = _SortedRealDict() vals = [(9.1,'nine'),(10.0,'ten'),(11.1,'eleven'),(12.2,'twelve'),(13.5,'thirteen'),(14.1,'forteen')] for v in vals: srd[v[0]]=v[1] return srd def rnd...
from ._entropy_functions import ApproximateEntropry, SampleEntropy from ._modelling_frameworks import ro_framework from ._residual_diagnostics import residual_diagnostic from ._statistical_tests import get_ts_strength, adf_test, kpss_test
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import spacy import networkx as nx from anntools import Sentence, Keyphrase, Collection from utils import find_match, detect_language, nlp_es, nlp_en from itertools import chain, zip_longest import numpy as np import re tag_re = re.compile(r'([BILUOV])-(\w+)') sufix...