content stringlengths 5 1.05M |
|---|
# coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
from typing import TYPE_CHECKING, Any, Dict, List, Tuple
from feishu.dt_calendar import Calendar, CalendarAttendee, CalendarEvent
from feishu.dt_enum import CalendarEventVisibility, CalendarRole
from feishu.dt_help imp... |
# coding=utf-8
# Author: Jianghan Li
# Question: 278. First Bad Version
# Date: 14/03/2017
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):
class Solution(object):
def firstBadVersion(self, right, left=1):
"""
:type n: ... |
# check buttons, the easy way
from tkinter import *
root = Tk()
states = []
for i in range(10):
var = IntVar()
chk = Checkbutton(root, text=str(i), variable=var)
chk.pack(side=LEFT)
states.append(var)
root.mainloop() # let tkinter keep track
print([var.get() for var in stat... |
from django.contrib import admin
from orders.models import Order, Item, ItemOrder, Discount, Category, Receipt
class ItemOrderInline(admin.TabularInline):
model = ItemOrder
extra = 1
class ItemAdmin(admin.ModelAdmin):
list_display = ('name', 'price', 'discountstring', 'description')
class OrderAdmin(a... |
import os
import subprocess
from loguru import logger
from time import sleep
import random
import requests
from packaging import version as pyver
from django.conf import settings
from tacticalrmm.celery import app
from agents.models import Agent, AgentOutage
logger.configure(**settings.LOG_CONFIG)
@app.task
def ... |
from django.apps import AppConfig
class ImoveisConfig(AppConfig):
name = 'imoveis'
|
# k-fold cross validation evaluation of xgboost model
import pandas as pd
from xgboost import XGBRegressor
from sklearn.model_selection import TimeSeriesSplit
from sklearn.model_selection import cross_val_score
from xgboost import plot_tree
from matplotlib import pyplot
#from sklearn.metrics import explained_variance_... |
# This was originally copied from an AdaFruit Learning System Guide (https://github.com/adafruit/Adafruit_Learning_System_Guides)
# specifically https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/MagTag_Cat_Fed_Clock/code.py
# Modifications have since been made, but the original is copyright AdaFruit... |
#-*- coding: utf-8 -*-
"""
иногда нужно
listForWrite = list(u'')
for at in resultList:
#print type(at[0].decode('cp1251'))#.encode('cp1251')
for it in at:
listForWrite.append(it.decode('cp1251'))
"""
from io_wrapper import *
def testRead( sets ):
file = FabricOpen( sets )
listLines = Non... |
import cv2
from numpy import *
import numpy as np
import math
##
##define sampling function
def sampling(image_original,ratio):
size_original=image_original.shape
length=size_original[0]
width=size_original[1]
length_adj=math.floor(length/ratio)
width_adj=math.floor(width/ratio)
rgb_or_gray=len(... |
from .scalar import plot_scalar
from .vector import plot_vector |
## Copyright 2011, IOActive, Inc. All rights reserved.
##
## AndBug is free software: you can redistribute it and/or modify it under
## the terms of version 3 of the GNU Lesser General Public License as
## published by the Free Software Foundation.
##
## AndBug is distributed in the hope that it will be useful, but W... |
import sys
sys.setrecursionlimit(2**20)
mod = int(1e9 + 9)
dx = [2, 2, -2, -2, 1, -1, 1, -1]
dy = [1, -1, 1, -1, 2, 2, -2, -2]
def pot(x, n):
if (n == 0): return(1)
ret = pot(x, n // 2)
ret = (ret * ret) % mod
if (n & 1): ret = (ret * x) % mod
return(ret)
t = int(input())
for r in range(t):
n,... |
import cgt, numpy as np, numpy.random as nr, itertools as it
from cgt import core, utils
from cgt.numeric_diff import numeric_grad
from cgt.tests import across_configs
DISPLAY=False
@across_configs
def test_scalars():
np.random.seed(0)
x = cgt.scalar('x')
y = cgt.scalar('y')
z = cgt.scalar('z')
va... |
def estimate_square(square, estimate,episolon):
y = (estimate + (square/estimate))/2
print y
# if abs(y-estimate) < episolon:
# print y
# else:
# estimate_square(square,y,episolon)
while abs(y-estimate) > episolon:
estimate_square(square, y, ep... |
import re
import scrapy
from scrapy.http import FormRequest, Request
from w3lib.url import url_query_parameter
from ..items import ReviewItem, ReviewItemLoader, str_to_int
def load_review(review, product_id, page, order):
"""
Load a ReviewItem from a single review.
"""
loader = ReviewItemLoader(Revi... |
# Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
import torch.nn.functional as F
from ..builder import MODULES
@MODULES.register_module()
class GANLoss(nn.Module):
"""Define GAN loss.
Args:
gan_type (str): Support 'vanilla', 'lsgan', 'wgan', 'hinge',
'wgan-logistic-n... |
# -*- coding: utf-8 -*-
"""DPCTF device observation framework configuration parser
Load the configuration files from Test Runner
and parse it to the internal format.
The Software is provided to you by the Licensor under the License, as
defined below, subject to the following condition.
Without limiting other conditi... |
from flask import Flask, render_template, request, redirect, jsonify
from flask import url_for, flash, make_response
from flask import session as login_session
from sqlalchemy import create_engine, asc
from sqlalchemy.orm import sessionmaker
from database_setup import Base, User, Genre, Movie
import random
import strin... |
from gameball.api_requestor import APIRequestor
import gameball.constants
import gameball.utils
from gameball.models.player_object import playerObject, playerAttributes
def initialize_player(player):
api_requestor_instance = APIRequestor()
player_attributes = player.player_attributes.__dict__
bod... |
"""
Vision.py created by Tyler Adam Martinez:
Created: May 17, 2020
Last Updated: May 17, 2020
Robot CV Design (Current plan as of May 17, 2020):
@ Camera
+ LiDar
(A) Camera Name
Top
_________
(A) | @ @ | (B)
| + |
|_________|
"""
import RPi.GPIO as... |
import sys
import unittest
import tornado.testing
import tornado.gen
from nats.io.client import Subscription
from nats.protocol.parser import *
class MockNatsClient:
def __init__(self):
self._subs = {}
self._pongs = []
self._pings_outstanding = 0
self._pongs_received = 0
s... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
""" Demo of using VoteNet 3D object detector to detect objects from a point cloud.
"""
import os
import sys
import json
import numpy as np
im... |
import torch
import torchvision.datasets as datasets
from PIL import Image
class ImageFolderInstance(datasets.ImageFolder):
""": Folder datasets which returns the index of the image as well::
"""
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
... |
from django.forms import ModelForm
from django.forms import *
from heartbeat.models import *
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
class HeartBeatForm(ModelForm):
class Meta:
model = Heartbeat
fields = ['user_id', 'dog_name', 'audio_file']
|
from datetime import timedelta
from random import randint
from django.db import models
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_CENTER
def get_voice_id(... |
import numpy as np
import utilities
class make_SVD:
def __init__(self, f_trace, trig_trace):
def where_trig(trig_trace):
## Boolean search for whether index n > n-1
trig_onset = trig_trace[:-1] > trig_trace[1:]
## Get indices for where n > n-1
self.trig_onset... |
"""
test utilities shared among test classes
these mixins are reused also in openwisp2
change with care.
"""
class TestX509Mixin(object):
def _create_ca(self, **kwargs):
options = dict(name='Test CA',
key_length='2048',
digest='sha256',
... |
#
# Copyright (c) 2021, NVIDIA 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 ... |
dx = int(input("Введите шаг"))
x1 = -7
x2 = 11
while x1 + dx <= 11:
x1 = x1 + dx
if x1 + dx < -3:
y = 3
print(y)
elif(x1 + dx > -3) & (x1 + dx <= 3):
y = 3 + -((9-(x1)**2)**(1/2))
print(y)
elif(x1 + dx > 3) & (x1+ dx <= 6):
y = -2*(x1-3)+3
print(y)
eli... |
# Doris Zdravkovic, March, 2019
# Solution to problem 5.
# python primes.py
# Input of a positive integer
n = int(input("Please enter a positive integer: "))
# Prime number is always greater than 1
# Reference: https://docs.python.org/3/tutorial/controlflow.html
# If entered number is greater than 1, for every numbe... |
from .morshu import Morshu
|
import time
import unittest
from Data.parameters import Data
from Telemetry.check_with_lastday import lastday_timeperiod
from Telemetry.check_with_lastmonth import lastmonth_timeperiod
from Telemetry.check_with_lastweek import last7day_timeperiod
from Telemetry.check_with_overall import overall_timeperiod
from Telemetr... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from aiohttp import web, ClientSession, ClientConnectorError
from argparse import ArgumentParser
from asyncio import create_task, gather, TimeoutError, set_event_loop_policy, new_event_loop, set_event_loop
from copy import deepcopy
from logging import error, getLogger
from os... |
from typing import Callable, Optional
import json
from dataclasses import dataclass
from autodidaqt_common.remote.command import deserialize_wire_types, serialize_wire_types
__all__ = ["Middleware", "LogMiddleware", "TranslateCommandsMiddleware", "WireMiddleware"]
@dataclass
class Middleware:
outbound: Optiona... |
import sys
def solve():
read = sys.stdin.readline
def root(u):
while uf[u][0] != u:
uf[u][0] = uf[uf[u][0]][0]
u = uf[u][0]
return u
res = []
for _ in range(int(read())):
f = int(read())
# uf[name] = [parent_name, count_name]
uf = {}
... |
angle1=int(input("enter first angle"))
angle2=int(input("enter second angle"))
angle3=int(input("enter third angle"))
if(angle1+angle2+angle3==180 and angle1>0 and angle2>0 and angle3>0):
if(angle1<90 and angle2<90 and angle3<90):
print("acute angle triangle")
elif(angle1>90 or angle2>90 or angle3>90):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@file : roberta_tokenize.py
@author: zijun
@contact : zijun_sun@shannonai.com
@date : 2020/10/22 21:13
@version: 1.0
@desc :
"""
from transformers import RobertaTokenizer
import os
import numpy as np
from argparse import ArgumentParser
from typing import Dict, Li... |
import logging
from abc import ABC, abstractmethod
from enum import Enum
from sqlalchemy import select
from api.core.config import settings
from api.core.event_bus import Event
from api.core.profile import Profile
from api.db.models import Tenant
from api.db.session import async_session
from api.endpoints.models.webho... |
# -*- coding: utf-8 -*-
"""
Author : kouyafei
date: 2018/4/20
"""
|
import os
import sys
import math
import numpy as np
sys.path.append(os.path.join('../'))
#sys.path.append(os.path.join('.'))
# Converts grid indices (i,j,k) to 1d array indices
# 1-D: fieldAs1DArray[i] = fieldOn1DGrid[i]
# 2-D: fieldAs1DArray[(Ny+1)*i + j] = fieldOn2DGrid[i]... |
from .rover import Rover
from .gps import Gps
from .gpsposition import GpsPosition
|
#
# VAZ Projects
#
#
# Author: Marcelo Tellier Sartori Vaz <marcelotsvaz@gmail.com>
from .staging import *
# General
#---------------------------------------
ENVIRONMENT = 'local'
# Static and media files
#---------------------------------------
STATIC_URL = f'http://{environ["staticFilesDomain"]}:9000/{AWS_... |
#!/usr/bin/env python3
import PIL
import os
import unittest
from io import StringIO
from unittest.mock import patch
from .context import *
class TestBasic(unittest.TestCase):
def test_first(self):
pass
if __name__ == '__main__':
unittest.main()
|
from pygments.lexer import RegexLexer, bygroups
from pygments.token import (Comment, Keyword, Text, Name, String)
# Need pick squash, etc.
# And reflog
class RysGitOutputLexer(RegexLexer):
tokens = {
'root': [
(r'(commit)(\s)(\w{40})$',
bygroups(Keyword, Text, String), 'default-... |
# Copyright 2022 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
"""
@brief test log(time=2s)
"""
import unittest
import os
from pandas import read_csv
from pyquickhelper.pycode import ExtTestCase
from mlprodict.onnxrt.validate.validate_summary import (
merge_benchmark, summary_report)
class TestBenchmarkTools(ExtTestCase):
def common_test_benchmark_merge(self, f1, f... |
# -*- coding: utf-8 -*-
"""Testing class for pyicane package.
"""
from pyicane import pyicane
import unittest
import logging
import requests
from datetime import datetime
import pandas as pd
from collections import OrderedDict
logging.basicConfig(level=logging.INFO)
LOGGER = logging.getLogger(__name__)
REQUESTS_LOG =... |
#!/usr/bin/env python3
import re, sys, string, csv, os
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup
import pandas as pd
# Global Vars
SubjectAreaLinks = []
SubjectAreaHeaders = []
SubjectAreaClasses = []
QuarterSubjectAreaLinks = []
QuarterSubjec... |
#!/usr/bin/env python3
import sys
from hw01 import HW01
if __name__ == '__main__':
# Rock'n'Roll
h = HW01('XX:XX:XX:XX:XX:XX', debug=True)
h.connect()
h.setup_services()
try:
battery = h.get_battery_level()
print(battery)
h.set_distance_unit('metric')
version = h.g... |
#!/usr/bin/env python
#unittests for liten
import unittest
import doctest
from doctest import DocTestSuite
from liten import Liten, LitenController
class TestLitenBaseClass(unittest.TestCase):
"""Tests for LitenBaseClass Class."""
def setUp(self):
self.fakePath = 'testData/testDocOne.txt'
sel... |
#
# -*- coding: utf-8 -*-
# Copyright 2021 Red Hat
# 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
"""
The iosxr_ntp_global config file.
It is in this file where the current configur... |
from panel.orbital.orbit_plot import OrbitPlot
from panel.orbital.orbital_points_plot import OrbitalPointsPlot
from panel.orbital.trajectory_hyperbole import TrajectoryHyperbole
from panel.telemetry.hyperbole import HyperboleData
class OrbitalPointsHyperbole(OrbitalPointsPlot):
def update(self, telemetry):
... |
import json
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import warnings
from glob import glob
plt.xkcd()
# ignore warning
warnings.filterwarnings('ignore')
def bar_plot(df, label, title, column):
fig, ax = plt.subplots(figsize=(20, 5))
bar_width = 0.35
opa... |
import collections
import dataclasses
from typing import Any
from . import utils
from .bytecode_transformation import create_instruction
from .guards import Guard
from .guards import GuardSource
from .utils import rename_implicit
_GUARD_SOURCE_NN_MODULE = {
GuardSource.LOCAL: GuardSource.LOCAL_NN_MODULE,
Guar... |
import time
import ujson
from django.test import TestCase
from django.test.client import Client
from model_mommy import mommy
from web.models import WebUrl, UrlTime
class TestPostData(TestCase):
def setUp(self):
self.client = Client(HTTP_X_UDID='9527')
self.label = mommy.make("Label", id=1)
... |
"""
Represents the Derusting passive
--
Author : DrLarck
Last update : 04/03/20 (DrLarck)
"""
# dependancies
import asyncio
# util
from utility.cog.character.ability._effect import Effect
from utility.cog.character.ability.util.effect_checker import Effect_checker
from utility.cog.character.ability.effect.buff.der... |
"""
__State2ProcDef_MDL.py_____________________________________________________
Automatically generated AToM3 Model File (Do not modify directly)
Author: gehan
Modified: Wed Oct 15 14:32:49 2014
___________________________________________________________________________
"""
from stickylink import *
from widthXfillXdec... |
import unittest
from ds2.tree import Tree
class TestTree(unittest.TestCase):
def testinit(self):
Tree(['root'])
Tree([1, [2, [3], [4]], [5, [6], [7], [8]]])
def teststr(self):
self.assertEqual(str(Tree([1, [2], [3]])), "1\n 2\n 3")
self.assertEqual(str(Tree([1, [2, [3]]])), "... |
from train import *
from mock import MagicMock
def load_classifier():
config = CustomArgParser().parse()
checkpoint_path = 'checkpoints/model_9.pt'
glue_task = config['glue_task']
data = MagicMock()
classifier = recipe_factory(glue_task, data_interface = data, **config['mi'])
sd = torch.load(ch... |
#!/usr/bin/env python
#
# Copyright 2016-present Tuan Le.
#
# Licensed under the MIT License.
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://opensource.org/licenses/mit-license.html
#
# Unless required by applicable law or agreed to in writing, so... |
from itertools import product
import iris
import numpy as np
import pandas as pd
from remake import Task, TaskControl, remake_task_control
from cosmic import util
from cosmic.config import CONSTRAINT_ASIA
from orog_precip_paths import (orog_path, land_sea_mask, cache_key_tpl, surf_wind_path_tpl,
... |
from typing import List
from fastapi import APIRouter, Depends, Response, status
from sqlalchemy.orm import Session
from models import User, Directory
from schema import BookmarkOut, DirectoryIn, DirectoryOut
from database import get_db
from router.admin.auth import get_current_user
from util import error
router = AP... |
#!/usr/local/bin/managed_python3
#
# Written by Vaughn Miller
#
#
# Modify REPO_ROOT to match your environment
import os
import plistlib
import sys
#==== This should be modified to match your environment ====
REPO_ROOT = '/Volumes/its_munki_repo'
#-----------------------------------------------------------
manifest_... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 Ian Ottoway <ian@ottoway.dev>
# Copyright (c) 2014 Agostino Ruscito <ruscito@gmail.com>
#
# 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 withou... |
#! /usr/local/bin/python
import argparse
import os
import shutil
import sys
import tempfile
import git
IGNORE_PATTERNS = ('.git', ".DS_Store")
SAFE_CHARS = ["-", "_", "."]
MAX_LENGTH = 100
STUDENT = "student"
DEVELOP = "develop-"
DEVELOP_DEFAULT = "all develop branches"
DIFF_FORMAT = """
You can download a zip of... |
import errno
import os
import sys
import appdirs
_appdirs = appdirs.AppDirs('art')
artifacts_file = 'artifacts.yml'
artifacts_lock_file = 'artifacts.lock.yml'
config_file = os.path.join(_appdirs.user_config_dir, 'config.yml')
cache_dir = _appdirs.user_cache_dir
def mkdirs(path):
"""
Like `os.makedirs`, but... |
import statistics, numpy
with open("data.txt", "r") as fh:
dataline = fh.read()
positions = dataline.strip().split(",")
positions = numpy.array([int(a) for a in positions], dtype=numpy.int)
# Spoiler alert: It's the median. I double check with other methods too:
# median, mean, mode(s), then iterating thr... |
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
# word1Len = len(word1)
# word2Len = len(word2)
# minimumChanges = [[0 for _ in range(word2Len+1)] for _ in range(word1Len+1)]
# for i in range(word1Len+1):
# for j in range(word2Len+1):
# ... |
import csv
from site_crawler.cleaner.cleaner import Cleaner
class Dataset_Builder:
def __init__(self):
self.cleaner = Cleaner()
self.create_csv_headers()
def create_csv_headers(self):
csv_files = [
'negative_sentiment',
'positive_sentiment',
'dataset... |
from medmnist import environ
import os
import numpy as np
from torch.utils.data import Dataset
from PIL import Image
INFO = "medmnist/medmnist.json"
class MedMNIST(Dataset):
flag = ...
def __init__(self, split='train', transform=None, target_transform=None):
''' dataset
:param split: 'trai... |
from flask import Flask, url_for, request, render_template;
from app import app;
import redis;
#Connect to redis data store
r = redis.StrictRedis(host='flaskmva.redis.cache.windows.net',port=6380,ssl=True,db=0, charset="utf-8", decode_responses=True, password='kxmLxHPfw5Xx8piaTlyv5VrPBBkKMoNTG6TNta+Pd5I=');
# server... |
from __future__ import print_function
import argparse
import io
import json
import jinja2
import yaml
from sphinxcontrib.datatemplates import helpers
def _load_data(filename):
if filename.endswith('.yaml'):
with open(filename, 'r') as f:
return yaml.load(f)
elif filename.endswith('.json... |
from tests import utils
import bmesh
import bpy
import re
class TestObjectExport_IncompatibleSG(utils.XRayTestCase):
def test_sharpEdgeAdjacentsHasSameSmoothingGroups(self):
# Arrange
bm = utils.create_bmesh((
(0, 0, 0),
(-1, -1, 0), (+1, -1, 0), (+1, +1, 0), (-1, +1, 0),... |
import sys, os
sys.path.insert(1, "../../")
import h2o
import random
def pub_444_spaces_in_filenames(ip,port):
# Connect to h2o
h2o.init(ip,port)
# tempdir = "smalldata/jira/"
# if was okay to write to smalldata, it's okay to write to the current directory
# probably don't want to, but can't find ... |
import unittest
import threading
import time
from chuck import *
class BaseTests(unittest.TestCase):
def setUp(self):
self.api = ChuckTester()
def test_auth_init(self):
self.api.activate_scenario("scenario-1", "id-1")
json = self.api.auth_init()
self.assertEqual(json["code"],... |
from snakemake.shell import shell
import pysam
log = snakemake.log_fmt_shell(stdout=True, stderr=True)
sort_cmd = ""
bamtofastq_cmd = (
" bedtools bamtofastq -i {snakemake.input.bam_file} "
"-fq {snakemake.output.fastq1} "
"-fq2 {snakemake.output.fastq2}"
)
# if bam is not sorted by query name, it must ... |
# MIT License
#
# Copyright (c) 2018 Evgeny Medvedev, evge.medvedev@gmail.com
#
# 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
# ... |
from pymediainfo import MediaInfo as mi
def get_track_info(movie):
mediainfo_dat = mi.parse(movie)
video_track = []
audio_track = []
video_track_count = 0
audio_track_count = 0
for track in mediainfo_dat.tracks:
if track.track_type == "Video":
video_track_count += 1
... |
#!/usr/bin/python
import httplib2
import os
import sys
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run
# The CLIENT_SECRETS_FILE variable specifies... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 27 15:06:30 2019
@author: asabater
"""
import os
os.chdir(os.getcwd() + '/..')
# %%
from evaluate_model import main
from tensorboard.backend.event_processing import event_accumulator
import train_utils
import numpy as np
# =====================... |
# -*- coding: utf-8 -*-
"""
Common code for the tests.
All tests using locust.io will need to create a HttpLocust class and run
the tests doing:
from user import launch
launch(classname, n_clients, rate, run_time):
"""
from __future__ import print_function, unicode_literals
import datetime
import gevent
impo... |
import math
n = int(raw_input())
lista = [int(raw_input()) for _ in range(n)]
for i in lista:
sq_sum = (i*(i+1)*(2*i+1))/6
whole_sqsum = (i*(i+1))/2
whole_sqsum = whole_sqsum**2
print abs(sq_sum - whole_sqsum)
'''
j=1
sq_sum = 0
whole_sqsum = 0
using formula above
while j<=i:
sq_sum += j**2
whole_sqsum +=... |
import sys
import pysam
import subprocess
from re import sub
import os
import numpy as np
import utils
mergedsortfn = sys.argv[1]
origroibamfn = sys.argv[2]
sampledbamfn = sub('.sorted.bam$',".sampled.sorted.bam", mergedsortfn)
GAIN_FINAL= sys.argv[3]
ratio = float(utils.countReads(mergedsortfn))/float(utils.coun... |
from PIL import Image
from typing import List
from .types import RawImage
from ..palette import Palette
def generate_png(data: RawImage, w: int, h: int, palette: Palette) -> Image.Image:
n_pal: List[int] = []
for triplet in palette.data:
n_pal.extend(triplet)
img = Image.new("P", (w, h), color=0)... |
from __future__ import print_function # For printing no newline
import sympy # symbolic library
import re # regular expressions: for saving useful output
def fixPowers(s):
return re.sub(r'q(\d+)\*\*(\d+)', r'pow( q\1, \2 )', s)
meqn = 3
# Conserved variables:
q1 = sympy.symbols("q1")
q2 = sympy.symbols("q2... |
from django.core.mail import send_mail
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import ContactForm
def get_name(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
return HttpResponseRedi... |
"""
request_interceptor.py
~~~~~~
Created By : Pankaj Suthar
"""
def intercept_request(request):
"""
intercept_request
:param request: Flask Request Object
:return: updated request
"""
pass
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import time
import argparse
import textwrap
import traceback
import base64
import dash
import dash_bio
import dash_html_components as html
import dash_core_components as dcc
# from dash.dependencies import Input, Output
from collections import OrderedD... |
from setuptools import setup
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(name='SaltIching',
version='0.6',
description='A python package for Iching',
long_des... |
from .drastic import nonable, init, strict, enable, disable |
#! /usr/bin/python3
#
# MIT License
#
# Copyright (C) 2019 Akamai Technologies, Inc.
#
# 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 ri... |
import bs4
from bs4 import BeautifulSoup
import requests
import time
class PyPoem:
def __init__(self):
self.poem = ""
self.poet = ""
self.title = ""
name = input('Poem name?\n')
print('Connecting to server...')
self.getPoem(name)
beg = '*' * 50 + '\n'
... |
import json
# codigo para criar arquivo de opcoes options.json
# Gera um template para que o bot apresente estas opcoes para o usuario
# Gerador de Opcoes para Bot 1.0
print (f"Gerador de opcoes para bot 2.0\n")
# Se nao for valor inteiro, sai
try:
z=int(input ("Quantas opcoes deseja criar? "))
except... |
# match对象
import re
pattern = re.compile(r'(\w+) (\w+) (?P<word>.*)')
match = re.match(pattern, 'I love you!')
# the property of match
print(match.string)
print(match.re)
print(match.pos)
print(match.endpos)
print(match.lastindex) # 被捕获的最后一个分组后号码 编号从1开始
print(match.lastgroup)
# the method of match
print(match.g... |
import pyshark
from datetime import datetime, time, timedelta
import time
import json
import os
import sys
import pymysql.cursors
pathname = os.path.dirname(sys.argv[0])
appPath = os.path.abspath(pathname) + "/globals.json"
with open(appPath, 'r') as myfile:
data=myfile.read()
globalconf=json.loads(data)
listenerl... |
#-------------------------------------------------------------------------------
# StrainPorosity
#-------------------------------------------------------------------------------
from PYB11Generator import *
from Physics import *
from PhysicsAbstractMethods import *
from RestartMethods import *
@PYB11template("Dimensi... |
"""
SHISO: a log template generation algorithm proposed in [1].
[1] Masayoshi Mizutani. Incremental Mining of System Log Format.
in IEEE 10th International Conference on Services Computing, pp. 595–602, 2013.
"""
import logging
import numpy as np
from amulog import lt_common
from amulog import lt_misc
_logger = ... |
begin_unit
comment|'# Copyright 2012 IBM Corp.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'# a copy of the License at'
nl|'\n'
commen... |
import bs4
import re
import os
from datetime import datetime
from typing import Iterable, Tuple
from common.utils.text_utils import trim_string
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By
from selen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.