content
stringlengths
5
1.05M
import numpy as np import matplotlib.pyplot as plt from . import SBM, LBM from .utils import ( lbm_merge_group, sbm_merge_group, lbm_split_group, sbm_split_group, ) from typing import Any, Tuple, Union, Optional from scipy.sparse import spmatrix import scipy.sparse as sp import logging logger = logging...
from enum import Enum # Clockwise class Direction(Enum): NORTH = 1 EAST = 2 SOUTH = 3 WEST = 4
# coding: utf-8 from sqlalchemy import BigInteger, Column, Date, ForeignKey, Index, Integer, String from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() metadata = Base.metadata class Meetingdate(Base): __tablename__ = 'MeetingDate' __tabl...
""" PGD attacks """ import torch import torch.nn.functional as F from torch.autograd import Variable # ------------------------------------------------------------------------------ # PGD attack and its variants in the TripleWins paper # ---------------------------------------------------------------------------...
n = input('numero: ') print('unidade: ',n[3]) print('dezena: ',n[2]) print('centena: ',n[1]) print('milhar: ',n[0])
def max_subarray_cross(array,left,mid,right): # For left of mid inter_sum = 0 left_sum = 0 for i in range(mid-1,left-1,-1): inter_sum += array[i] if (inter_sum > left_sum): left_sum = inter_sum # For right of mid inter_sum = 0 right_sum = 0 for i in range(mid,right+1,1): inter_sum += ...
#!/usr/bin/env python from distutils.core import setup from setuptools.command.test import test as TestCommand import sys class Tox(TestCommand): def finalize_options(self): super(Tox, self).finalize_options(self) self.test_args = [] self.test_suite = True def run_test(self): ...
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. # This is an auto-generated file. Do not edit it. """ Provides Twisted version information. """ from twisted.python import versions version = versions.Version('twisted.words', 15, 0, 0)
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import os.path import sys from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand from ab2cb import __version__ class Tox(TestCommand): user_options = [('tox-args=', 'a', "Arguments to pass to tox")] def ini...
""" Copyright (c) 2020, Tidepool Project All rights reserved. """ import logging from .issue import JiraIssue logger = logging.getLogger(__name__) class JiraFuncRequirement(JiraIssue): @property def id(self): return self.fields[self.jira.fields['reference_id']] or '' @property def risks(self...
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute 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...
from rest_framework import serializers from openpersonen.api.enum import GeslachtsaanduidingChoices, OuderAanduiding from .datum import DatumSerializer from .in_onderzoek import OuderInOnderzoekSerializer from .persoon import PersoonSerializer class OuderSerializer(PersoonSerializer): geslachtsaanduiding = seri...
expected_output = { "processor_pool": {"total": 10147887840, "used": 487331816, "free": 9660556024}, "reserve_p_pool": {"total": 102404, "used": 88, "free": 102316}, "lsmi_io_pool": {"total": 6295128, "used": 6294296, "free": 832}, }
#Juan Camilo Betancourt Giraldo #Ingenieria de Sistemas #Primer Semestre def aportes (totalsalario, smm): ingreso = totalsalario / smm if ingreso <= 2: totalaporte = totalsalario * 0.01 return totalaporte if ingreso > 2 and ingreso <= 6: totalaporte = totalsalario * 0.02 re...
import pafy from core import internals from core import const import os import pprint log = const.log # Please respect this YouTube token :) pafy.set_api_key('AIzaSyAnItl3udec-Q1d5bkjKJGL-RgrKO_vU90') def go_pafy(raw_song, meta_tags=None): """ Parse track from YouTube. """ if internals.is_youtube(raw_song)...
#!/usr/bin/env python # coding: utf-8 """ Tool for automagically updating the paths in visual studio project files. Is part of the git commit hook, or can be just ran manually. Takes no arguments, the paths are hardcoded here. Tested to work with both python 2.7.9 and 3.4.3 (Python's default XML libraries are so horr...
# Copyright (c) 2019 NTT DATA # # 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, ...
# -*- coding: utf-8 -*- from xutils.custom_logger import (LogFormatter, CustomLogger) from xutils.string_utils import (to_unicode, combinations) from xutils.test_runner import (add_parent_path, TestRunner) from xutils.d...
"""Dynamically generate Buildkite pipeline artifact based on git changes.""" import re import os import sys import json import fnmatch import pathlib import datetime import functools import subprocess import collections from typing import Dict, List, Tuple, Set, Generator, Callable, NoReturn, Union import box import p...
# By design, pylint: disable=C0302 import threading from typing import Any, Callable, Optional, Union, TypeVar, cast, overload from rx.disposable import Disposable from rx.concurrency import current_thread_scheduler from ..observer import AutoDetachObserver from .. import typing, abc A = TypeVar('A') B = TypeVar('B'...
# Generated by Django 2.1.2 on 2018-10-11 19:00 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("pyazo_core", "0010_auto_20181011_1854"), ] operations = [ migrations.AlterField( model_name="up...
import random ordleatters=[ord(a),ord(b),ord(c),ord(d),ord(e),ord(f),ord(g),ord(h),ord(i),ord(j),ord(k),ord(l),ord(m),ord(n),ord(o),ord(p),ord(q),ord(r),ord(s),ord(t),ord(u),ord(v),ord(w),ord(x),ord(y),ord(z)] leatters=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x',...
from config import * from spotipy.oauth2 import SpotifyClientCredentials import spotipy import re ccm = SpotifyClientCredentials(client_id=spotify_client_id, client_secret=spotify_client_secret) sp = spotipy.Spotify(client_credentials_manager=ccm) def manager(): temp = get_start_data() spotify_link,...
class Calculator: def __init__(self, num1, num2): self.num1 = num1 self.num2 = num2 def add(self): return(self.num1 + self.num2) def subtract(self): return(self.num2 - self.num1) def multiply(self): return(self.num1 * self.num2) def divide(self): r...
import asab import time import logging ### L = logging.getLogger(__name__) ### class SystemManagerService(asab.Service): """ This class manages system messages in within the application """ def __init__(self, app): super().__init__(app, "eaglestitch.SystemManagerService") self.is_running = True async d...
# Copyright 2014 Midokura SARL # # 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...
import os class ReleaseConstants: def __init__(self) -> None: self.build_dir = F"../build" self.release_dir = F"../build/releases" self.xxx_release_notes_path = os.path.join(self.build_dir, F'relnotes_x.y.z.md') self.release_notes_dir = os.path.join(self.build_dir, 'release_notes'...
import unittest import excalibur import datetime class TestTimeConversion(unittest.TestCase): def test_convert_timestamp_between_timezones(self): dt_obj = datetime.datetime(2019, 5, 1, 18, 20, 28) dt_obj_converted = excalibur.convert_timestamp_between_timezones( dt_obj, exc...
import argparse from fmridenoise.interfaces.denoising import Denoise from fmridenoise.interfaces.smoothing import Smooth from nipype import Node, Workflow from fmridenoise.interfaces.confounds import Confounds from fmridenoise.pipelines import is_IcaAROMA, get_pipeline_path, load_pipeline_from_json def run(output_dir...
# helper functions def format_show_info(show): empty_placeholder = "—" star_emoji = "★" empty_star_emoji = "☆" text = "_{name} ({start} - {end})_\ \nRating: {rating}\ \nGenres: _{genres}_\ \nRuntime: _{runtime}_\ \nStatus: _{status}_" name = getatt...
from wsbtrading.maths.maths import *
import pickle import os import numpy as np import json import argparse import os.path as op import csv def main(): random_seed = 0 np.random.seed(random_seed) args = get_args() text = dict() with open(args.text_file, newline='') as rf: reader = csv.reader(rf) for row in reader: text[row[0]] = row[1] id...
''' List Mode: Runtime: 40 ms, faster than 97.87% of Python3 online submissions for Two Sum. Memory Usage: 14.3 MB, less than 53.95% of Python3 online submissions for Two Sum. ''' ''' Tuple Mode: Runtime: 52 ms, faster than 53.96% of Python3 online submissions for Two Sum. Memory Usage: 14.3 MB, less than 51....
#!/usr/bin/env python import os import imp import sys import time import inspect import cProfile import argparse import threading import traceback import vivisect import vivisect.cli as viv_cli import envi.config as e_config import envi.threads as e_threads import vivisect.parsers as viv_parsers def main(): par...
from pbpstats.resources.enhanced_pbp import Rebound from pbpstats.resources.enhanced_pbp.live.enhanced_pbp_item import LiveEnhancedPbpItem class LiveRebound(Rebound, LiveEnhancedPbpItem): """ Class for rebound events """ action_type = "rebound" def __init__(self, *args): super().__init__...
CONF_MAINNET = { "fullnode": "https://api.trongrid.io", "event": "https://api.trongrid.io", } # The long running, maintained by the tron-us community CONF_SHASTA = { "fullnode": "https://api.shasta.trongrid.io", "event": "https://api.shasta.trongrid.io", "faucet": "https://www.trongrid.io/faucet", ...
from telethon import TelegramClient from telethon.hints import EntityLike class Wipers: @staticmethod async def wipe(client: TelegramClient, entity: EntityLike, own: bool = True): message_ids = [m.id async for m in client.iter_messages(entity, from_user='me' if own else None)] await client.del...
#!/usr/bin/env python """ Commands work with servers. (Hiss, boo.) """ import copy import logging from fabric.api import local, put, settings, require, run, sudo, task from fabric.state import env from jinja2 import Template import app_config logging.basicConfig(format=app_config.LOG_FORMAT) logger = logging.getLo...
# coding: utf-8 """ Deep Lynx The construction of megaprojects has consistently demonstrated challenges for project managers in regard to meeting cost, schedule, and performance requirements. Megaproject construction challenges are common place within megaprojects with many active projects in the United State...
print('This program will provide a list of cubes for you. ') minRange = int(input('What\'s the minimum for your range? ')) maxRange = int(input('What\'s the maximum for your range? ')) listOfCubes = [] for value in range(minRange, maxRange+1): number = value**3 listOfCubes.append(number) print('Your list of c...
# Copyright (c) 2020 vesoft inc. All rights reserved. # # This source code is licensed under Apache 2.0 License, # attached with Common Clause Condition 1.0, found in the LICENSES directory. # import os import sys import pytest from pytest_bdd import ( scenarios, given, when, then, parsers, ) fro...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 23 10:49:52 2018 @author: marcmueller-stoffels """ from bs4 import BeautifulSoup # open file and read into soup infile_child = open('../../OutputData/Set0/Setup/Igiugig0Set2Setup.xml', "r") # open contents_child = infile_child.read() infile_child...
# Copyright 2017, 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 or ...
import os import tkinter as tk from collections import Counter from tkinter.filedialog import askopenfilename os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" import cv2 as cv import numpy as np from PIL import Image, ImageTk from tensorflow.keras import models from utils import decoder IMAGE_FORMATS = [("JPEG", "*.jpg"), ...
import math dirac = [0 for i in range(1000)] dirac[100] = 1 # needs a Dirac impulse to start swinging amp = 0.995 # exponentially increasing amplitude #amp = 1 # constant amplitude #amp = 1.005 # exponentially decreasing amplitude freq = 137 # a lovely frequency for a 1000 long array si...
from django.urls import include, path from django.conf.urls import include, url from rest_framework import routers from . import views router = routers.DefaultRouter() #router.register(r'heroes', views.HeroViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable ...
"""This gathers information about the random number generator function so that it can be seeded to give any particular series of virtual coin tosses up to a certain length. """ import random FAIR_COIN = lambda: random.randint(0, 1) RANDOM_SEED = random.seed def has_all_sequences(seeds_for_sequences, length): """R...
# Copyright 2019 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://www.apache.org/licenses/LICENSE-2.0 # # or in the "l...
from unittest.mock import patch import pytest from telegram.ext import CommandHandler from autonomia.features import corona @pytest.mark.vcr def test_cmd_retrieve_covid_data(update, context): with patch.object(update.message, "reply_markdown") as m: context.args = ["ireland"] corona.cmd_retrieve...
import os import config # Compile the subject def compile(fileName, userID, language): if os.path.exists("compiled/" + fileName): os.system("chmod 777 compiled/" + fileName) os.system("rm compiled/" + fileName) if language not in config.lang: return "NOLANG" print("Compiling subje...
import logging from sqlalchemy.orm import Session from pydantic import UUID4 from app.api.crud import user, product logger = logging.getLogger("genicons").getChild("ml_caller") async def caller(uid: UUID4, session: Session): logger.info(caller.__name__) # Request to model of StyleTransfer for make Product...
""" Modulo de carga de datos a partir de SQL o un CSV, y construccion de grafos """ import time import networkx as nx import numpy as np import pandas as pd import psycopg2 from h3 import h3 from networkx.algorithms import bipartite from tqdm import tqdm import backboning import funciones as fn import matplotlib.p...
# Write your code here from collections import defaultdict class Graph : def __init__(self,V) : self.V = V self.graph = defaultdict(list) def DFSUtil(self,temp,v,visited) : visited[v] = True temp.append(v) for i in self.graph[v] : if visited[i] == False : ...
""" Copyright 2017 Robin Verschueren 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, softw...
import ctypes import inspect import threading from functools import partial from typing import Any, Callable from tortfunc.exceptions import FunctionTimeOut def threaded_timeout(function: Callable[..., Any], timeout: float) -> Callable[..., Any]: def thread_kill_func(*args, **kwargs): # First param is gi...
import os def test_import_iris(): import iris assert (iris.__version__.count(".") == 2) def test_import_netCDF4(): import netCDF4 assert (netCDF4.__version__.count(".") == 2) def test_import_netcdftime(): import netcdftime assert (netcdftime.__version__.count(".") == 2) def test_import_gdal...
"""Test str render module.""" import hashlib import unittest from bootstrap4c4d.classes.description import Description from bootstrap4c4d.reducers.str import reduce_strings from bootstrap4c4d.render.str import render_strings class TestStringsRender(unittest.TestCase): def test_render_strings(self): des...
""" Functions associated with NetCDF for tracker. """ from lo_tools import Lfun import xarray as xr # Info for NetCDF output, organized as {variable name: (long_name, units)} name_unit_dict = {'lon':('Longitude','degrees'), 'lat':('Latitude','degrees'), 'cs':('Fractional Z','Dimensionless'), 'ot':('Ocean Time',Lf...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilitie...
import yaml import glob import types import bmeg.ioutils from tabulate import tabulate """ simple transform of dvc into md """ DEFAULT_DIRECTORY = 'meta' HUGO_HEADER = """ --- title: Data Sources sidebar: true menu: main: parent: Building Graph weight: 2 --- """ def cardify(papers): """create a 'car...
import theano.tensor as T from .. import init from .. import nonlinearities from ..utils import as_tuple, int_types, inspect_kwargs from ..theano_extensions import conv from .base import Layer __all__ = [ "Conv1DLayer", "Conv2DLayer", "Conv3DLayer", "TransposedConv2DLayer", "Deconv2DLayer", ...
#!/usr/bin/env python # =========================================================== from sklearn import tree import pandas as pd import time import sys # Import lib # =========================================================== import csv from datascience import * import numpy as np import random import matplotlib impo...
class MuzzleTestCase: pass
from selenium import webdriver import time my_file = open("url_list.txt", 'r') url_list = [""] with open("url_list.txt") as file: while (line := file.readline().rstrip()): url_list.append(line) print("here it is") print(url_list) for i in range (1, len(url_list)): driver = webdriver.Chrome() dr...
import firebase_admin from firebase_admin import credentials, db import datetime class FirebaseStream: key, path, type, pathD, data, child = str, str, str, str, str, str @staticmethod def initialize_app(path: str, database_url: str): cred = credentials.Certificate(path) firebase_admin.ini...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author : 陈坤泽 # @Email : 877362867@qq.com # @Date : 2021/06/03 14:22 import textwrap from collections import defaultdict, Counter import math import re import sys from pyxllib.prog.newbie import typename from pyxllib.text.pupil import listalign, int2myalphaenum de...
""" Find more at: https://github.com/l-farrell/isam-ob/settings """ import logging from pyisam.util.model import DataObject from pyisam.util.restclient import RESTClient RISK_PROFILES = "/iam/access/v8/risk/profiles" logger = logging.getLogger(__name__) class RiskProfiles(object): def __init__(self, base_ur...
""" cache implementations Based on python-llfuse/examples/passthroughfs.py written by Nicolaus Rath Copyright © Nikolaus Rath <Nikolaus.org> """ import logging from llfuse import ROOT_INODE, FUSEError from threading import Lock from collections import defaultdict import errno from Libfs.misc import calltrace_logger ...
""" Afterglow Core: OAuth2 server routes """ from flask import redirect, request, url_for, render_template from .. import app from ..errors import MissingFieldError from ..errors.oauth2 import UnknownClientError from ..auth import auth_required from ..oauth2 import oauth_clients, oauth_server from ..resources.users im...
import unittest import numpy as np import ed_geometry as geom import ed_symmetry as symm import ed_fermions import fermi_gas as fg class TestFermions(unittest.TestCase): def setUp(self): pass # single species fermi gas def test_fg_energies(self): """ Test energies o...
calls = { 'Thm': 'theorem', 'Proof': 'proof', 'Soln' : 'soln', 'Solution' : 'solution', 'Cor' : 'corollary', 'Lemma' : 'lemma', 'Prop' : 'proposition', 'Exer' : 'exercise', 'Exercise' : 'exercise', 'Example' : 'example', 'Theorem' : 'theorem', 'Def' : 'definition', 'Fact' : 'fact', 'Problem' : 'problem',...
#!/usr/vin/env python # -*- coding: utf-8 -*- # Copyright: (c) 2018, Vadim Khitrin <me at vkhitrin.com> # 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_vers...
# from conftest import * def test_run_opt_load_results(default_model): """ This test checks that we can serialise optimiser results to YAML and reload, getting the same information after loading. It also checks that resetting the seed and re-running gives the same results. """ facility, prod...
#!/usr/bin/env python import glob import os import matplotlib.pyplot as plt def main(): res_per_k = {} for fn in glob.glob(os.path.expanduser('~/logs/') + '*-Topk-*'): if os.path.isfile(fn): # bfn = os.path.basename(fn) # mechanism, topk, rate, directory, timestep, hh, cm = b...
import environ from .base import * # Read .env if exists env = environ.Env() env.read_env(os.path.join(BASE_DIR, '.env')) ##################### # Security settings # ##################### DEBUG = True SECRET_KEY = env('SECRET_KEY') # ALLOWED_HOSTS = env('ALLOWED_HOSTS') ALLOWED_HOSTS = ['127.0.0.1', 'localhost']...
""" 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 use this ...
from random import choice from copy import deepcopy from collections import defaultdict #import pisqpipe as pp def get_neighbors(location, board): ''' get the neighbors from the board for one location ''' width = len(board) height = len(board[0]) x, y = location start_i = max(x-2, 0) e...
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score from xgboost.sklearn import XGBClassifier import xgboost as xgb def icu(train): df = pd.read_excel(train) df_new = df.groupby('...
from typing import Dict from torch import nn, Tensor from .utils import set_hessian, solve from .. import properties as p class NewtonDirection(nn.Module): def forward(self, mol: Dict[str, Tensor]): mol = set_hessian(mol) mol[p.gen_stp_dir] = -solve(mol[p.gen_grd], mol[p.gen_hes]) return m...
import os import random import numpy as np from nltk import word_tokenize, pos_tag import nltk import csv import string import collections as ct import pandas as pd from CRF_ReceiptGetter import ReceiptGetter annai_data_count = 0 mega_data_count = 0 north_data_count = 50 # annai_data=pd.read_csv("Annotated/annai_f...
import math import pandas as pd import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats from scipy.stats import t from scipy.stats import norm import lib.least_squares as ls def regression_4_by_4(x, y_0, y_1 = None, y_2 = None, y_3 = None, cols = 1, rows = 1, suptitle = N...
import numpy as np import matplotlib.pyplot as plt import glob import sys import re import os from matplotlib import rcParams rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = ['Meiryo', 'Yu Gothic', 'DejaVu Sans'] os.chdir(sys.argv[1]) input = os.path.basename(sys.argv[1]) input = input.replace('_b...
import sys from models.instances import Host from services.config import Configuration from services.logger import print_orange from .selectors import Selector from .connection import DoConnectAndSave class DiscoverHost(object): def __init__(self, account_obj, bounce=False): self.account_obj = account_o...
import numpy as np def align(array, reader): nifti_array = array alignment_matrix = [reader.GetMetaData('srow_x').split()[:3], reader.GetMetaData('srow_y').split()[:3], reader.GetMetaData('srow_z').split()[:3]] for row in range(len(alignment_matrix)): for col in range(len(...
# _*_ coding: utf-8 _*_ from zope.interface import Attribute, Interface __author__ = "Md Nazrul Islam <email2nazrul@gmail.com>" class IBaseClass(Interface): """ """ _finalized = Attribute("Finalized Flag") def finalize(context): """ """ class ICloneable(Interface): """ """ def clone(...
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ import pytest import pytablewriter as ptw class Test_CsvTableWriter_write_table: @pytest.mark.parametrize( ["format_name"], [[tblfmt.names[0]] for tblfmt in ptw.TableFormat.find_all_attr(ptw.FormatAttr.TEXT)], ) def ...
# -*- coding: utf-8 -*- """ Created on Wed Sep 23 10:30:14 2020 @author: Ruben Andre Barreiro """ # Import NumPy Python's Library import numpy # Return Matrix with Planets' Orbital Radius and Orbital Periods # Note: Each row corresponds to a Planet: # - The 1st Column corresponds to the Orbital Radius # ...
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown Copyright 2017-2020 Met Office. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions a...
# See LICENSE for licensing information. # # Copyright (c) 2016-2019 Regents of the University of California and The Board # of Regents for the Oklahoma Agricultural and Mechanical College # (acting for and on behalf of Oklahoma State University) # All rights reserved. # """ This is a module that will import the correc...
from checks import AgentCheck import subprocess import re import time class UnicornCheck(AgentCheck): def check(self, instance): if 'pid_file' not in instance: raise Exception('Unicorn instance missing "pid_file" value.') pid_file = instance.get('pid_file', None) master_pid = open(pid_file, 'r').re...
from datetime import timedelta from doctest import DocTestSuite import pickle import unittest from freezegun import freeze_time from django.contrib.auth import get_user_model from django.db import IntegrityError from django.test import RequestFactory from django.test import TestCase as DjangoTestCase from django.urls...
#!/usr/bin/env python # PyOpenCV - A Python wrapper for OpenCV 2.x using Boost.Python and NumPy # Copyright (c) 2009, Minh-Tri Pham # All rights reserved. # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # * Redistribu...
#!/usr/bin/python """ This python script parses the binary result files of the instrumentation capability. Each file is composed of a header and a variable number of records containing a timestamp and some custom recorded content. """ import sys import struct HEADER_FORMAT = "1024sIL1024si40sLLLQQQ" HEADER_FIELDS = ...
# Generated by Django 2.2.13 on 2020-11-18 11:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("workflow_handler", "0031_task_correct"), ] operations = [ migrations.AlterField( model_name="taskactivity", name="a...
print("done!")
import os import time import datetime import hashlib import urllib from urllib.parse import urljoin import sqlite3 import json import operator import requests import detector key = '' class MstdnStream: """Mastodon Steam Class Usage:: >>> from mstdn import MstdnStream, MstdnStreamListner >>>...
import itertools from django.core.exceptions import ValidationError from django.core.validators import URLValidator def get_bsn(): for n in itertools.count(): eight_first_digits = [int(x) for x in str(n + 10 ** 7).zfill(8)] total = sum((9 - i) * digit for i, digit in enumerate(eight_first_digi...
import os import logging from google.cloud import storage logger = logging.getLogger(__name__) class RemoteGCS: def __init__(self, bucket='', project=None, credentials=None): self._storage_client = storage.Client( project=project, credentials=credentials) self._bucket = self._storage_c...
# Time: O(r - l) # Space: O(1) import math class Solution(object): def abbreviateProduct(self, left, right): """ :type left: int :type right: int :rtype: str """ PREFIX_LEN = SUFFIX_LEN = 5 MOD = 10**(PREFIX_LEN+SUFFIX_LEN) curr, zeros = 1, 0 ...
import re from pathlib import Path import git from .colors import styles from .defaults import * headBranchExtractionRegExp = re.compile("^\\s*HEAD\\s+branch:\\s+(.+)\\s*$", re.M) def getRemoteDefaultBranch(remote): # get_remote_ref_states return headBranchExtractionRegExp.search(remote.repo.git.remote("show", r...