content stringlengths 5 1.05M |
|---|
# /2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}
# /2010-04-01/Accounts/{AccountSid}/Calls
#!/usr/bin/env python
#
# Copyright 2007 Google 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 Licen... |
"""
Plot a snapshot of a food web graph/network.
Needs: Adjacency list of who eats whom (consumer name/id in 1st
column, resource name/id in 2nd column), and list of species
names/ids and properties such as biomass (node abundance), or average
body mass.
"""
import networkx as nx
import scipy as sc
import... |
from django.core import mail
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
class TestResendMail(APITestCase):
fixtures = ["user.json"]
url: str
@classmethod
def setUpTestData(cls):
cls.url = reverse("account_resend_email")
d... |
"""
Given a string of numbers and operators, return all possible results from computing all the different possible ways to
group numbers and operators. The valid operators are +, - and *.
Example 1
Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]
Example 2
Input: "2*3-4*5"
(2*(3-(4*5))) = -34
((2*3)-(4*... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 23 20:16:57 2020
@author: Soumya Kanti Mandal
"""
import cv2
import urllib.request
from matplotlib import pyplot as plt
from pylab import rcParams
image_url="https://skm96.github.io/image/s2.jpg"
image_name="skm.jpg"
urllib.request.urlretrieve(image_url, im... |
import torch
@torch.enable_grad()
def sample(net, m=64, n_ch=3, im_w=32, im_h=32, K=10, device='cpu', p_0=None):
if p_0 is None:
sample_p_0 = lambda: torch.FloatTensor(m, n_ch, im_w, im_h).uniform_(-1, 1).to(device)
else:
sample_p_0 = lambda: p_0.uniform_(-1, 1).to(device)
x_k = torch.autog... |
# Generated by Django 3.1.7 on 2021-04-09 14:20
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('rest_api', '0010_delete_country'),
]
operations = [
migrations.CreateModel(
name='Country',
... |
from django.shortcuts import render
from rest_framework import generics
from .models import Book
from .serializer import BookSerializer
from rest_framework.response import Response
# Create your views here.
class GetInfo(generics.RetrieveAPIView):
def get(self, request, *args, **kwargs):
# serializer_clas... |
r = 15
def setup():
global location, velocity
size(640, 360)
this.surface.setTitle("Bouncing Ball with PVectors")
location = PVector(100, 100)
velocity = PVector(2.5, 5)
def draw():
background(235, 215, 182)
location.add(velocity)
# check boundaries
if (location.x > width - r) or (... |
import os, glob
import numpy as np
from tqdm import tqdm
import tensorflow as tf
from tensorflow import keras
from scipy.interpolate import interp1d
from astropy.table import Table, Column
__all__ = ['ConvNN']
class ConvNN(object):
"""
Creates and trains the convolutional
neural network.
"""
def ... |
from nasbench import api
import deep_architect.core as co
import deep_architect.contrib.misc.search_spaces.tensorflow_eager.nasbench_space as nb
INPUT = 'input'
OUTPUT = 'output'
node_op_names = {
'conv1': 'conv1x1-bn-relu',
'conv3': 'conv3x3-bn-relu',
'max3': 'maxpool3x3'
}
class NasbenchEvaluator:
... |
# -*- coding: utf-8 -*-
from mahjong.constants import TERMINAL_INDICES
from mahjong.hand_calculating.yaku import Yaku
from mahjong.utils import is_chi
class Junchan(Yaku):
"""
Every set must have at least one terminal, and the pair must be of
a terminal tile. Must contain at least one sequence (123 or 789... |
pa = int(input("Digite o primeiro termo da PA: "))
ra = int(input("Digite a razão da PA: "))
soma = pa
for c in range(1, 11):
print(c, "° = ", soma)
soma = soma + ra
|
from paises import Sulamericanos
from paises import Europeus
def main(args):
sul = Sulamericanos()
sul.print_paises()
eu = Europeus()
eu.print_paises()
return
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))
|
from config.bank_config import BankConfig
from helper.enum_definitions import AmountFormatEnum
"""
It possible to read this configuration from JSON file
but for simplicity I have constructed Python object
"""
BanksConfigDict = {
"bank1": BankConfig.default("bank1").update(
DateExpr = r"%b %d %Y", # Oct ... |
from django.db import models
class APFund(models.Model):
event = models.ForeignKey('Event', on_delete=models.CASCADE)
contribution = models.PositiveIntegerField(default=0)
notes = models.CharField(max_length=200)
last_updated = models.TimeField(auto_now=True)
|
import unittest
from nextnanopy import commands
from nextnanopy.utils.formatting import _path, _bool
import os
folder_nnp = os.path.join('tests', 'datafiles', 'nextnano++')
folder_nn3 = os.path.join('tests', 'datafiles', 'nextnano3')
folder_negf = os.path.join('tests', 'datafiles', 'nextnano.NEGF')
folder_msb = os.pa... |
import datetime
from app.api.v2.utils.db_connection import connect
from psycopg2.extras import RealDictCursor
from instance.config import app_config
# from manage import Database
import psycopg2
import os
# db = Database()
environment = os.environ["APP_SETTINGS"]
DATABASE_URL = app_config[environment].DATABASE_URL
... |
import os
class Processor:
def __init__(self, node_coappearance_file_name):
hyperedge_file_name = "hyperedges.csv"
print "Processing file " + node_coappearance_file_name
self.process_node_coappearance_file(node_coappearance_file_name, hyperedge_file_name)
def dict_to_string(self, D):
... |
import ast
import meta
import coral_ast as cast
import coral_types as ct
# Public API
# Turn this on for printing.
verbose = False
def vprint(a):
global verbose
if verbose:
print a
def convert_to_coral_ast(func):
"""
Converts a Python function to a Coral AST.
"""
# A Python AST.
... |
# coding: UTF-8
from xml.etree.ElementTree import Element, SubElement
import xml.etree.ElementTree as ET
import uuid
import libvirt
import uuid
from kvmconnect.base import BaseOpen
class VmGen:
"""
Create VM
parameters:
name: VM (domain) name
cpu:
arch: cpu architecture
... |
# -*- coding: utf-8 -*-
import json
import logging
import werkzeug
from werkzeug.exceptions import BadRequest
from odoo import SUPERUSER_ID, api, http, _, exceptions
from odoo import registry as registry_get
from odoo.addons.auth_oauth.controllers.main import OAuthLogin
from odoo.addons.web.controllers.main import (log... |
#!/usr/bin/env python
#
# ======================================================================
#
# Brad T. Aagaard, U.S. Geological Survey
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copyright (c) 2010-2017 University of California, Davis
#
#... |
from flask import Flask, redirect, url_for, render_template, request, session, send_file
app = Flask(__name__)
@app.route("/")
def home():
return render_template("index.html")
@app.route("/login", methods=["POST", "GET"])
def login():
if request.method == "POST":
user = request.form["nm"]
session["user"] = ... |
import json
import jsonlines
import spacy
from spacy.kb import KnowledgeBase
def save_500():
# Prepare datafiles
json_loc = "../../data/prodigy_data/annotations_input.jsonl"
new_loc = "../../data/prodigy_data/iaa_input.jsonl"
# Prepare resources
nlp = spacy.load('../resources/nen_nlp')
kb = K... |
from datetime import datetime
from threading import Timer
from . import now
from . import start_web_interface
port = 8765
class Scheduler(object):
"""
Manages Job objects and the waiting between job executions
"""
def __init__(self, log=None):
self.jobs = []
self.current_job = None
self.sleeper = None
se... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
## Copyright 2018 KYOHRITSU ELECTRONIC INDUSTRY CO., LTD.
##
## 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 with... |
# -*- coding: utf-8 -*
import urllib
import re
import os
import json
from imdbpie import Imdb
from datetime import datetime
class Movie():
"""Movie object storing detailed information and related media links
Parameters
----------
title
Movie title
storyline
A short excerpt of the ... |
#!/usr/bin/env python3
from housepy import config, log, util, strings
from mongo import db
def main():
log.info("core_tagger...")
t = util.timestamp()
features = db.features.find({'properties.Expedition': config['expedition'], 'properties.CoreExpedition': {'$exists': False}})
for feature in ... |
from typing import List
from morpho.error import NoWorkerFunctionError
from morpho.rest.models import TransformDocumentRequest
import httpretty
from pydantic.main import BaseModel
import pytest
from morpho.config import ServiceConfig
from morpho.consumer import RestGatewayConsumer, RestGatewayServiceConfig, WorkConsum... |
import time
from functools import wraps
from nose.tools import nottest
from selfdrive.hardware import PC
from selfdrive.version import training_version, terms_version
from selfdrive.manager.process_config import managed_processes
def set_params_enabled():
from common.params import Params
params = Params()
para... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import json
from abc import ABC, abstractmethod
from typing import Any, Iterable, List, Mapping, MutableMapping, Optional, Tuple
import pendulum
import requests
from airbyte_cdk.models import SyncMode
from airbyte_cdk.sources import AbstractSource
from airb... |
from enum import Enum
class KnowledgeBaseFormatException(Exception):
pass
class KnowledgeBaseFormat(Enum):
MODELS = 1
KEYS = 2
|
from xml.etree.ElementTree import Element, SubElement,ElementTree, tostring
import xml.etree.ElementTree as ET
from xml.dom.minidom import parseString
import sys, re
def prettify(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = tostring(elem, 'utf-8')
reparsed... |
from __future__ import annotations
from typing import Optional
from asn1crypto import keys, pem
from ... import hashes
from ...padding import pss
from ...padding.v15 import enc_digestinfo, pad_pkcs1_v15
from ...public import key, rsa
from ..hashlib import HashlibHash
class PartialRsaPublicKey(rsa.RsaPublicKey):
... |
from django.core.exceptions import PermissionDenied
from functools import wraps
def ajax_login_required(view):
@wraps(view)
def wrapper(request, *args, **kwargs):
if not request.user.is_authenticated():
raise PermissionDenied
return view(request, *args, **kwargs)
return wrapper... |
from distutils.core import setup
setup(
name="repless",
version='0.1.0',
author="VulcanoAhab",
packages=["repless/aws_peices", "repless/fab_shorts"],
url="https://github.com/VulcanoAhab/repless.git",
description="Severless Utils",
install_requires=[
]
)
|
import sys
val1 = sys.argv[0]
val2 = len(sys.argv)
val3 = str(sys.argv)
print("nombre script: {}".format(val1))
print("cantidad de val3: {}".format(val2))
print("lista de val3: {}" .format(val3))
|
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Periodic Discovery Job
# ---------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------... |
# Copyright 2015 MongoDB, 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, so... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import feedgen.feed
import lxml.html
import re
import selenium
import selenium.webdriver.chrome.options
def magic():
url = 'https://24h.pchome.com.tw/books/store/?q=/R/DJAZ/new'
chrome_options = selenium.webdriver.chrome.options.Options()
chrome_options.add_... |
import time
import numba
import numpy as np
@numba.jit(numba.uint8(numba.complex64, numba.complex64))
def cnt(z, c):
k = 0
while k < 100:
z = z * z + c
if z.real**2 + z.imag**2 > 4:
break
k += 1
return k
@numba.jit
def mand(M, N):
init_z = complex(0.0, 0.0)
g... |
# Copyright 2019 Nicolas OBERLI
#
# 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 writin... |
import json
from typing import Optional
def read_content() -> dict:
try:
with open(r"storage/PasswordVault.txt", "r") as file:
obj = json.load(file)
return obj
except json.decoder.JSONDecodeError:
with open(r"storage/PasswordVault.txt", "w") as file:
obj = j... |
# -*- encoding: utf-8 -*-
"""
Created by Ênio Viana at 22/09/2021 at 23:09:27
Project: py_dss_tools [set, 2021]
"""
class PriceShape:
name = "PriceShape"
name_plural = "PriceShapes"
columns = ['action', 'csvfile', 'dblfile', 'hour', 'interval', 'like', 'mean', 'minterval', 'npts', 'price',
... |
import numpy as np
import pandas as pd
def numerical_summary(series: pd.Series) -> dict:
"""
Args:
series: series to summarize
Returns:
"""
aggregates = [
"mean",
"std",
"var",
"max",
"min",
"median",
"kurt",
"skew",
... |
import unittest
from pylgrum.card import Card, Rank, Suit
from pylgrum.hand import Hand
from pylgrum.errors import OverdealtHandError
class TestHand(unittest.TestCase):
def test_too_many_cards(self):
"""Implicitly tests the add() override in Hand, too."""
h = Hand()
self.assertEqual(h.size... |
import argparse
import collections
import csv
import logging
import math
import pathlib
import random
from typing import Dict, List, NamedTuple, Optional, Sequence, Tuple, TypeVar
import requests
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
Vector = List[float]
def subtract(v: Vector, w: Vecto... |
"""Utility functions only called by tests """
#%%
from natural_bm import dbm
from natural_bm import regularizers
#%%
def nnet_for_testing(nnet_type, W_reg_type=None, b_reg_type=None):
"""
This makes some small neural networks that are useful for testing.
# Arguments
nnet_type: Str; neural ne... |
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return 'Здесь всё Ок! Но график синуса <a href="/sin/">дальше</a>.', 200
@app.route('/sin/')
def graph_sin():
return render_template('sin.html')
@app.errorhandler(404)
def page_not_found(error):
return 'Вы поте... |
"""Events keep an audit trail of all changes submitted to the datastore
"""
from sqlalchemy import and_, func
from . import db
from namex.exceptions import BusinessException
from marshmallow import Schema, fields, post_load
from datetime import datetime
from sqlalchemy.orm import backref
from sqlalchemy import cast, ... |
import pandas as pd
data = pd.read_csv("data/2016.csv")
df = pd.DataFrame(data)
df = df.replace('[Mæ(=)]', '', regex=True)
print(df)
df.to_csv("data/2022.csv", index=False)
|
import pandas as pd
df = pd.read_csv('all_me.csv')
df = df['Message']
all_text = []
for msg in df:
msg = str(msg)
if (('"channel_id":' not in msg) and '"user_id":' not in msg) and ('"users":' not in msg) and ('"chat_id":' not in msg) and ('"photo":' not in msg) and ('nan' != msg):
print(msg)
a... |
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the MIT License.
# To view a copy of this license, visit https://opensource.org/licenses/MIT
from bongard import LineAction, ArcAction, OneStrokeShape, BongardImage, BongardProblem, BongardImagePainter, \
BongardProblemP... |
class TTSFactory:
from text2speech.modules.espeak_tts import ESpeak
from text2speech.modules.espeakng_tts import ESpeakNG
from text2speech.modules.google_tts import GoogleTTS
from text2speech.modules.mary_tts import MaryTTS
from text2speech.modules.mimic_tts import Mimic
from text2speech.module... |
"""
Base finders
"""
import functools
from collections import namedtuple
from pathlib import Path
from demosys.conf import settings
from demosys.exceptions import ImproperlyConfigured
from demosys.utils.module_loading import import_string
FinderEntry = namedtuple('FinderEntry', ['path', 'abspath', 'exists'])
class ... |
from dependency_injection.decorators.autowired import autowired
from dependency_injection.decorators.autowired_enums import AutoWiredType
from dependency_injection.test_dependency_injection.injected_class1 import InjectedClass
from dependency_injection.test_dependency_injection.injected_class2 import InjectedClass2
c... |
# Copyright (c) 2020 PaddlePaddle 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... |
import sys
BANNER_TEXT = "---------------- Starting Your Algo --------------------"
def get_command():
"""Gets input from stdin
"""
try:
ret = sys.stdin.readline()
except EOFError:
# Game parent process terminated so exit
debug_write("Got EOF, parent game process must have d... |
#!/usr/bin/env python3
"""
Created on 14 Jul 2021
@author: Bruno Beloff ([email protected])
"""
from scs_core.data.recurring_period import RecurringPeriod
from scs_core.data.datetime import LocalizedDatetime
# ----------------------------------------------------------------------------------------... |
import os
from django.conf import settings
from django.test import TestCase
from django.urls import reverse
from django.core.files.uploadedfile import SimpleUploadedFile
# from mixer.backend.django import mixer
from rest_framework.test import APITestCase, APIClient
from board.serializers import BoardSerializer, List... |
class Solution:
def firstUniqChar(self, s: str) -> int:
uniq = {}
for ch in s:
if ch in uniq:
uniq[ch] = False
else:
uniq[ch] = True
for i, ch in enumerate(s):
if uniq[ch]:
return i
return -1
|
import numpy as np
from scipy.signal import hilbert
from numpy.linalg import eigh, inv
from operators import *
import scipy.sparse as ssp
import matplotlib as mpl
import scipy.linalg as sla
import scipy.signal
from time import gmtime
import json
import matplotlib.pyplot as plt
mpl.rcParams['figure.figsize'] = 16, 9
#... |
import builtins
import copy
import types
from collections import defaultdict, deque
from typing import TypeVar, Any, Optional, Callable, Type, Dict, Iterable
__all__ = ['common_ancestor', 'create_class', 'resolve_bases', 'static_vars', 'static_copy']
T = TypeVar('T')
def create_class(name: str,
b... |
import sys
import time
import random
from sync_utils import Thread, Semaphore, watch
NUM_LEADERS = 0
NUM_FOLLOWERS = 0
LEADERS_QUEUE = Semaphore(0)
FOLLOWERS_QUEUE = Semaphore(0)
MUTEX = Semaphore(1)
RENDEZVOUS = Semaphore(0)
def print_queue():
global NUM_LEADERS
global NUM_FOLLOWERS
sys.stdout.write("... |
#._cv_part guppy.etc.Code
def co_code_findloadednames(co):
"""Find in the code of a code object, all loaded names.
(by LOAD_NAME, LOAD_GLOBAL or LOAD_FAST) """
from opcode import HAVE_ARGUMENT, opmap
hasloadname = (opmap['LOAD_NAME'],opmap['LOAD_GLOBAL'],opmap['LOAD_FAST'])
code = co.co_code
n... |
# -*- coding: utf-8 -*-
from requests import Response, Session
class SafeResponse(object):
def __init__(self, success, response=None, session=None):
self.__success: bool = success
self.__response: Response = response
self.__session: Session = session
def __repr__(self):
if se... |
# 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 under t... |
"""Unit tests for :mod:`prov_interop.provtranslator.converter`.
"""
# Copyright (c) 2015 University of Southampton
#
# 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,
# inc... |
# -*- coding: utf-8 -*-
"""Three-dimensional U-Net implemented in TensorFlow.
Reference
---------
Çiçek, Ö., Abdulkadir, A., Lienkamp, S. S., Brox, T., & Ronneberger, O. (2016)
3D U-Net: learning dense volumetric segmentation from sparse annotation.
International Conference on Medical Image Computing and Computer-Assi... |
import numpy as np
import matplotlib.pyplot as plt
import scipy.cluster.hierarchy as hac
a = np.array([[0.11, 2.5],[1.45, 0.40],
[0.3, 1.1],[0.9 , 0.8],
[0.5, 0.01],[0.1 , 0.5],
[0.6, 0.5],[2.6, 2.1],
[2.3, 3.2],[3.1, 2.2],
[3.2, 1.3]])
name='... |
# -*- coding: utf-8 -*-
import colorama # pip3 install colorama
from colorama import Fore as F
import requests as r # pip3 install requests
import argparse as arg
import os as sistema
sistema.system('' if sistema.name == '' else '')
index = r"""
"""
def arruma(url):
if url[-1] != "/":
url = url + "/"
if url[:7] != ... |
import logging
import os
from pathlib import Path
from torchvision import datasets
import datasetinsights.constants as const
from datasetinsights.storage.gcs import GCSClient
from .base import Dataset
CITYSCAPES_GCS_PATH = "data/cityscapes"
CITYSCAPES_LOCAL_PATH = "cityscapes"
ZIPFILES = [
"leftImg8bit_trainval... |
from distutils.core import setup
setup(
name = 'pyfluidsynth3',
version = '1',
description = "Fluidsynth bindings for Python 3.",
author = 'Stefan Gfroerer',
url = 'https://github.com/tea2code/pyfluidsynth3',
packages = ['pyfluidsynth3'],
)
|
from IMLearn.learners import UnivariateGaussian, MultivariateGaussian
import numpy as np
import plotly.graph_objects as go
import matplotlib.pyplot as plt
import plotly.io as pio
pio.templates.default = "simple_white"
def test_univariate_gaussian():
# Question 1 - Draw samples and print fitted model
c = Univa... |
from .task import Task
from .activity_task import ActivityTask
from .timer import Timer
from .generator import Generator
from .child_workflow import ChildWorkflow
|
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES O... |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.5'
# jupytext_version: 1.13.3
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# %%
# Uncomment this cell if running in Google Col... |
from __init__ import *
from utils import *
import plots
def censi(dataset, sequence, scan_ref, scan_in):
base_path = os.path.join(Param.results_path, sequence, str(scan_ref))
pose_path = os.path.join(base_path, "T_censi.txt")
cov_path = os.path.join(base_path, "cov_censi.txt")
if not Param.b_cov_icp a... |
"""
tests.fixtures.listings
"""
from apartmentbot.models import Listing
listing_data = {
'id': 'h23idk9i3r8349hufi3hr2eu',
'url': 'https://www.listing.net',
'name': 'New Listing! Great Location!',
'geotag': (42.49835, 71.23898),
'price': '$1,500',
}
def listing() -> Listing:
return... |
__version__ = "0.80.0"
version = tuple(map(int, __version__.split('.'))) # pylint: disable=invalid-name
|
import os
import py
import pytest
def auto_detect_cpus():
try:
from os import sched_getaffinity
except ImportError:
if os.environ.get("TRAVIS") == "true":
# workaround https://bitbucket.org/pypy/pypy/issues/2375
return 2
try:
from os import cpu_coun... |
# coding: utf-8
from datetime import datetime
from flask import Flask
from flask import render_template
from flask.ext.login import LoginManager
from leancloud.errors import LeanCloudError
from leancloud.query import Query
from leancloud.user import User
from models.auth_token import AuthToken
from models.user import... |
"""empty message
Revision ID: 385d83d68b71
Revises: 5a3a877698c8
Create Date: 2021-01-08 17:09:07.858288
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '385d83d68b71'
down_revision = '5a3a877698c8'
branch_labels = None
depends_on = None
def upgrade():
# ... |
import sys
from time import sleep
import cloudsigma
snapshot = cloudsigma.resource.Snapshot()
snapshot_done = False
if len(sys.argv) < 3:
print('\nUsage: ./snapshot.py drive-uuid snapshot-name\n')
sys.exit(1)
snapshot_data = {
'drive': sys.argv[1],
'name': sys.argv[2],
}
create_snapshot = snapshot.... |
class JSONSerializable:
def toJSON(self):
pass
class Ownership(JSONSerializable):
def __init__(self, investor, shares, cash_paid, ownership):
self.investor = investor
self.shares = shares
self.cash_paid = cash_paid
self.ownership = ownership
def toJSON(self):
... |
import pytest
from vartoml import VarToml
@pytest.fixture
def vtoml():
return VarToml()
def test_simple(vtoml):
"""A simple TOML document without any variables
This works the same as when using the `toml` package
without any extensions
"""
tomls_str = """
[default]
h = "/... |
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
'''
data informations
-----------------
:copyright (c) 2014 Xavier Bruhiere.
:license: Apache2.0, see LICENSE for more details.
'''
"""
# World exchanges caracteristics
Exchanges = {
# Market code, from yahoo stock code to google market code (needed for
# rel... |
"""*****************************************************************************
* Copyright (C) 2019 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to ... |
import attr
@attr.dataclass
class License:
features: str
nlevel: int
software_id: str
|
from .file_record import File
import sqlite3
class Database:
def __init__(self):
self.conn = {}
self.queries = {}
def cursor(self):
return self.conn.cursor()
def init(self):
self.conn = sqlite3.connect('db_files/prv.db', check_same_thread=False)
self.queries = {
... |
import setuptools
from distutils.core import setup
with open("README.md", "r") as fh:
LONG_DESCRIPTION = fh.read()
def setup_package():
metadata = dict(name='deepstack',
packages=['deepstack'],
maintainer='Julio Borges',
long_description=LONG_DESCRI... |
from module import *
def genToC(data, printLev, lastOneLine, lev, prevRef):
treeDepth = getDepth(data)
#print(treeDepth)
# return if printLev is activated,
# and lev exceeded it
if printLev != -1 and lev > printLev:
return
# if not dict type return
if not ( isinstance(data, dict... |
from heapq import heappop, heappush, heappushpop, heapify, _heapify_max, _heappushpop_max, _siftdown_max, _siftup_max
from collections import Iterable
from math import cos, ceil, pi, sin
from shapely.geometry import Polygon, Point
def circle(o, r, resolution=None):
if r <= 0:
raise ValueError("r must be... |
from unittest import TestCase
from NiaPy.algorithms.basic import GeneticAlgorithm
class MyBenchmark(object):
def __init__(self):
self.Lower = -5.12
self.Upper = 5.12
@classmethod
def function(cls):
def evaluate(D, sol):
val = 0.0
for i in range(D):
... |
from json import dumps
from httplib2 import Http
import config
def robot(content):
"""Hangouts Chat incoming webhook quickstart."""
url = config.robot["tsaitung"]
bot_message = {
'text' : content }
message_headers = {'Content-Type': 'application/json; charset=UTF-8'}
http_ob... |
import streamlink
from flask import jsonify
class decode:
pass |
from pathlib import Path
from gi.repository import GLib, Gtk
from gaphor.abc import Service
from gaphor.core import event_handler
from gaphor.event import ModelLoaded, ModelSaved
from gaphor.ui import APPLICATION_ID
class RecentFiles(Service):
def __init__(self, event_manager, recent_manager=None):
self... |
#!/usr/bin/python
# encoding: utf-8
#
# Copyright 2011-2014 Greg Neagle.
#
# 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 require... |
import psutil
percpu = psutil.cpu_percent(interval=None, percpu=True)
for i in range(len(percpu)):
print(i+1,"-" ,percpu[i])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.