content stringlengths 5 1.05M |
|---|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 19-3-6 下午3:43
# @Author : Hubery
# @File : celery.py
# @Software: PyCharm
from __future__ import absolute_import
import os
from celery import Celery
from celery.schedules import crontab
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HuberyBlog.settings')... |
#-*- coding: utf-8 -*-
from app import app
@app.route('/')
def root():
return app.send_static_file('index.html')
|
from numpy import linspace, logspace, log10
mbh = 10
mdot = 0.01
alpha = 0.007
radius = 9.22
izip = lambda x: zip(range(len(x)), x)
for inu, nu in izip(logspace(log10(0.1), log10(20), 12)):
for izet, zeta in izip(logspace(log10(alpha), 0.0, 12)):
beta = 2 * zeta / alpha - 1 + nu
if beta <= 0: co... |
import time
import json
import random
from urllib.error import URLError
from urllib import request
import http.client
import requests
import gevent
from gevent import monkey
import json
from flask import jsonify
from flask import Flask
app = Flask(__name__)
ctx = app.app_context()
ctx.push()
import j... |
from django.shortcuts import render, HttpResponse
from django.utils.safestring import mark_safe
import datetime
from datetime import timedelta
import json
import requests
import csv
import os
from bs4 import BeautifulSoup
import numpy as np
import pandas as pd
from .models import CSV
def home_page(request):
print... |
# Copyright 2016 gRPC authors.
#
# 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 twisted.internet.defer import inlineCallbacks
from autobahn.twisted.util import sleep
import util
NODE_ID = u'node1'
WORKER_ID = u'myworker'
REALM_ID = u'myrealm'
REALM_CONFIG = {
u'name': REALM_ID
}
ROLE_CONFIG = {
u"name": u"dummy",
u"permissions": [
{
u"uri": u"com.example.dummy... |
# -*- coding: utf-8 -*-
__commit_comment = '''
{{ sender.login }} {{ action }} comment on commit {{ repository.full_name }}@{{ comment.commit_id|truncate(7, True, '') }}
{{ comment.body|trim|truncate }}
{{ comment.html_url }}
'''
__create = '''
{{ sender.login }} created {{ ref_type }} {{ ref }} at {{ repository.fu... |
class Fetcher(object):
def fetch_addr(self, ref, app, facilities, auto_extract=False):
from caty.util.path import is_mafs_path
from caty.core.command import VarStorage
from caty.core.command.param import Option, Argument
from caty.core.script.interpreter.executor import CommandExecu... |
import numpy as np
import torch
import pdb
# A buffer that stores and sample based on episodes that have different step size
class ReplayBuffer_VarStepsEpisode(object):
def __init__(self, state_dim, action_dim, expert_episode_num, max_episode=10100):
self.max_episode = max_episode
self.max_size = max_epis... |
class transform(object):
def __init__(self):
pass
def __call__(self,x):
raise NotImplementedError
def __repr__(self):
x = "{}(".format(self.__class__.__name__)
for key,value in self.__dict__.items():
if key[0] is not "_":
x+= "{} = {}, ".forma... |
"""
DESAFIO 039: Alistamento Militar
Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com sua idade,
se ele ainda vai se alistar ao serviço militar, se é a hora de se alistar, ou se já passou
do tempo do alistamento. Seu programa também deverá mostrar o tempo que falta ou que passou do pr... |
from db_orms import *
import numpy as np
import psrchive as ps
from threading import Thread
class Cleaner(object):
def __init__(self, config, type, tolerance=1):
self.type = type
self.tolerance = tolerance
self.config = config
self.logger = Logger.get_instance()
def clfd_cleaner(self, observation_chunk, ... |
import cirq
import numpy as np
from typing import Tuple
from networkx import nx
# from qiskit import
from src import SurfaceCodeGraph
class CirqSurfaceCodeCircuit():
def __init__(self, sigma: Tuple[Tuple[int]], alpha: Tuple[Tuple[int]]):
# super().__init__()
self.sigma = sigma
self.alpha... |
from asyncio import CancelledError, create_task, sleep
from datetime import timedelta
from typing import Callable
import pytest
from aioredis import Redis
from httpx import AsyncClient
from tests.aiohttp import run_on_aiohttp
from uapi.aiohttp import App as AiohttpApp
from uapi.cookies import CookieSettings
from uapi... |
import sys
from os.path import join as pjoin
import math
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
from lib.utils import debug, str_to_labels, chart, load_image, display_imgs, np_macro_f1
from lib.utils_heavy import gen_macro_f1_metric
from lib.classes import class... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main_window_ui.ui'
#
# Created by: PyQt5 UI code generator 5.15.1
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCor... |
#!/usr/bin/env python
# Copyright 2019 Cloudbase Solutions Srl
#
# 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 re... |
"""Inference scripts for Stanford 2D3DS dataset.
"""
from __future__ import print_function
import argparse
import os
import time
import math
import tensorflow as tf
import numpy as np
import scipy.io
from PIL import Image
#from stanford_scenes.models.fcrn import structured_predictor
from stanford_scenes.models.struc... |
# #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Модуль реализации занятия памяти или многоканального устройства
"""
# pylint: disable=line-too-long
from pyss import pyssobject
from pyss.pyss_const import *
from pyss import queue_event_priorities
from pyss.block import Block
class Enter(Block):
"""Блок Enter пом... |
import csv, unittest
from importlib.resources import open_text
from myanmartools import ZawgyiDetector
class TestZawgyiDetector(unittest.TestCase):
'''
Tests the ZawgyiDetector class.
'''
def setUp(self):
'''
Creates a ZawgyiDetector object for testing.
'''
self.detector... |
'''
Copyright (c) 2018 Uber Technologies, 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 wri... |
# Copyright (c) 2018 getcarrier.io
#
# 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 i... |
"""
URL: https://codeforces.com/problemset/problem/1359/B
Author: Safiul Kabir [safiulanik at gmail.com]
Tags: brute force, dp, greedy, implementation, two pointers, *1000
"""
t = int(input())
for _ in range(t):
n, m, x, y = map(int, input().split())
count = 0
for __ in range(n):
a = list(input())... |
# -*- coding: utf-8 -*-
"""
Tests of neo.io.exampleio
"""
# needed for python 3 compatibility
from __future__ import absolute_import, division
import warnings
import unittest
import quantities as pq
import numpy as np
from neo.io.nestio import ColumnIO
from neo.io.nestio import NestIO
from neo.test.iotest.common_io... |
from itertools import chain
from typing import Union, Optional, Tuple
from hwt.doc_markers import internal
from hwt.hdl.operatorDefs import OpDefinition
from hwt.hdl.types.array import HArray
from hwt.hdl.types.defs import BIT
from hwt.hdl.types.hdlType import HdlType
from hwt.hdl.types.struct import HStruct
from hwt.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pyinotify
import re
import aioredis
import asyncio
import logging
import os
class NetBanLocalFile(object):
"""Watch the local file with your auth logs for failed attempts"""
def __init__(self, cfg, ban_manager):
super(NetBanLocalFile, self).__init__()
self.__... |
"""
Displays the frame within a window for the user to see.
Automatically sizes the window to the user's screen.
"""
import tkinter as tk
import os
import cv2
from baboon_tracking.mixins.capture_mixin import CaptureMixin
from pipeline import Stage
from pipeline.decorators import last_stage, stage
from pipel... |
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
"""
If enterprise support is enabled.
Will automatically create a ticket in your OU root account
to register the newly created account for support.
"""
from enum import Enum
import boto3
from botocore.exceptions... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import gzip
import zipfile
import tarfile
import numpy as np
import skimage
from skimage import io, transform
import six
from six.moves import urllib, ra... |
from . import prospa
from . import topspin
from . import vnmrj
from . import h5
from . import power
from . import csv
from . import vna
|
from typing import Callable, Generator
import tensorflow as tf
import numpy as np
from .utils import euclidean_distance
class PrototypicalNetwork:
"""Implements Prototypical Networks from the original paper (Snell et al., 2017).
Args:
encoder (tf.keras.Model): The encoder used to map the image onto... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 11 08:49:13 2019
@author: Emilia Chojak
@e-mail: emilia.chojak@gmail.com
"""
input_file = open("input.txt")
seqs = input_file.read().splitlines()
output_file = open("trimmed_sequences.txt", "w")
for seq in seqs[:-1]:
output_file.write(seq+"\n")
output_file.write(se... |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import pandas as pd
import requests, os, time
def prep_updatex(lscol,lsval):
hp = ''
if isinstance(lscol, list) and isinstance(lsval, list):
if len(lscol) == len(lsval):
for i in range(len(lscol)):
x = str(lscol[i]) + "='" + str(lsval[i]) + "'"
if hp == '' an... |
from js2xml import parse, pretty_print as tostring
from js2xml.utils.objects import make as objects_make
MAKE_OBJECTS_TYPES = (
# Types that can be handled by make_dict.
'array',
'object',
'property',
'string',
'boolean',
'number',
'undefined',
)
def make_obj(tree, ignore_tags=(), _i... |
import pandas as pd
from pathlib import Path
import numpy as np
from datetime import datetime
def getTeamPart(teamColumn ,fromFrame):
teams = []
for team in fromFrame[teamColumn].unique():
teams.append(fromFrame[fromFrame[teamColumn]==team])
return teams
def getRollingMean(target ,team, window=3):... |
#! /usr/bin/python3
#
# Copyright (c) 2017 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
#
"""
Flash the target with JTAGs and other mechanism
------------------------------------------------
"""
import time
import requests
from . import tc
from . import ttb_client
from . import msgid_c
class images(t... |
#!/usr/local/Cellar/python/3.7.3/bin/python3.7
import sys, os
import json
import time
from random import randint
from pprint import pprint
import ast
import requests
###################################################################################################
GCP_PROJECT = "saas-rally-dev-integrations"
OCM_DAT... |
#!/usr/bin/python
import subprocess
import argparse
from prometheus_client import Summary
from prometheus_client import start_http_server, Gauge
import random
import time
def bandwidth_measure_metric(server_ip,server_port):
'''
Returns current network bandwidth in Mbps
'''
try:
p = subprocess.... |
# *********
# -*- Made by VoxelPixel
# -*- For YouTube Tutorial
# -*- https://github.com/VoxelPixel
# -*- Support me on Patreon: https://www.patreon.com/voxelpixel
# *********
# we'll be using ASCII in this
def encryption():
print("Encryption")
print("Message can only be Lower or Uppercase alphab... |
import pytest
from karp5.context.auth import dummy_auth # pytype: disable=import-error
from karp5.tests.util import mk_headers
def test_check_user_w_no_user(app):
with app.test_request_context("/"):
result = dummy_auth.check_user()
assert result["authenticated"]
assert result["username"] == "T... |
from selenium.webdriver.common.by import By
from .abstract import PageElement
from .abstract import PageObject
class MainPage(PageObject):
h1 = PageElement(By.CSS_SELECTOR, "h1")
p = PageElement(By.CSS_SELECTOR, "main p")
|
# Test imports.
import utilities
from datetime import datetime
from mock import patch, MagicMock
import MySQLdb
import sys
import unittest
sys.path.append('../..')
# Source imports.
import database.connector as connector
import configuration.settings as settings
""" This module contains the DatabaseConnector class,... |
"""Tests for thermostat traits."""
from typing import Any, Callable, Dict
from google_nest_sdm.device import Device
def test_thermostat_eco_traits(fake_device: Callable[[Dict[str, Any]], Device]) -> None:
device = fake_device(
{
"name": "my/device/name",
"traits": {
... |
"""Generate a large version of a number in a pseudo-monocode font."""
from typing import Dict, List
import piltdown.literals as lit
def scaled_up_number(
number: str,
font: Dict[str, List[str]] = lit.DEFAULT3X5FONT,
leading_pad: int = 4,
) -> str:
"""Given a number as a string, produce a larger versio... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 9 00:21:43 2018
@author: gurjaspal
"""
#!/usr/bin/env python3
# Author: Sahil
import pickle
import pandas as pd
import numpy as np
import scipy.spatial.distance as dist
import random
import math
from random import sample, randint
from collections import defaultdict, Co... |
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import trianglesCore as tc
def draw(*surfaces, figure_size_tuple=(15,15)):
sizex, sizey = figure_size_tuple
matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
# necessary adjustment if `draw... |
"""
Reporter Module
"""
#####Imports#####
import copy
import logging
import numpy as np
#####Instantiate Logger#####
logging.basicConfig(level = logging.NOTSET)
_logger = logging.getLogger("reporters")
_logger.setLevel(logging.DEBUG)
class Reporter():
"""
Generalized reporter object for Particles
"""
... |
# 读取my.txt内容
class GetData():
def getJjCode(self):
f = open('my_jijin.txt', 'r', encoding='utf-8')
jj_codes = f.readlines()
return jj_codes
# def getGgCode(self):
# f = open('my_gegu.txt', 'r', encoding='utf-8')
# gg_codes = f.readlines()
# return gg_co... |
from aioalice.types.base import AliceObject
from aioalice.types.interfaces import Interfaces
from aioalice.types.meta import Meta
from aioalice.types.markup import Markup
from aioalice.types.entity_tokens import EntityTokens
from aioalice.types.entity_value import EntityValue
from aioalice.types.entity import Entity, E... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 10
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from isi_sdk_9_0_0.models.auth_a... |
# 写一个函数,求两个整数之和,要求在函数体内不得使用 “+”、“-”、“*”、“/” 四则运算符号。
#
#
#
# 示例:
#
# 输入: a = 1, b = 1
# 输出: 2
#
#
# 提示:
#
# a, b 均可能是负数或 0
# 结果不会溢出 32 位整数
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/bu-yong-jia-jian-cheng-chu-zuo-jia-fa-lcof
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution:
def add(self, a: in... |
from tensorflow import keras
from keras.preprocessing import image
import sys
import cv2
import numpy as np
import os
model = keras.models.load_model('python/model')
model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
image_path = sys.argv[1]
img_size = 150
data = []
img_arr = cv2.im... |
import pygame
import random
import pickle
import easygui
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode([1920, 1080])
screen.fill([255, 255, 255])
background = pygame.image.load("Background.png")
x_pos = random.randint(1, 1920)
y_pos = random.randint(1, 1080)
crowd = 75
x_pos_ki = rando... |
import mechanize
import cookielib
# Browser Globals
br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
cookieArray = []
globalLogging = False
br.set_cookiejar(cj)
br.set_handle_robots(False)
#br.set_handle_refresh(mechanize.HTTPRefreshProcessor(), max_time=1)
br.set_handle_refresh(False)
br.set_handle_redirect(Tr... |
from ocdskingfisher.sources.digiwhist_base import DigiwhistBaseSource
class DigiwhistCyprusSource(DigiwhistBaseSource):
publisher_name = 'Digiwhist Cyprus'
url = 'https://opentender.eu/download'
source_id = 'digiwhist_cyprus'
def get_data_url(self):
return 'https://opentender.eu/data/files/CY... |
#!/usr/bin/env python
"""Compiles student and teacher PDFs for each LaTeX source file."""
from __future__ import print_function
import os
import shutil
import sys
# command to use for os.system
LATEX = "pdflatex -interaction=nonstopmode"
# remove temporary output files
CLEAN = True
def latex(name, suff):
"""Run... |
import os
import markdown as md
from django.db import models
from django.conf import settings
from django.utils.safestring import mark_safe
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.mail import send_mail
class Cate... |
"""
http://crypto.stackexchange.com/questions/8845/finding-a-keylength-in-a-repeating-key-xor-cipher
"""
from __future__ import division
import operator
import sys
import os
import itertools
import re
import base64
import string
#Adding directory to the path where Python searches for modules
cmd_folder = os.path.dirn... |
import ast
import functools
from .base import SerializedArgs, Format
__all__ = ['PythonLiteral']
def load_file(file) -> SerializedArgs:
python_source = file.read()
args = ast.literal_eval(python_source)
assert args is not None
assert isinstance(args, dict)
objects = args['objects']
properti... |
# -*- coding: utf-8 -*-
"""
:copyright: Copyright 2017-2018 by the contributors (see AUTHORS file).
:license: BSD, see LICENSE.txt for details.
"""
from sphinxcontrib.confluencebuilder.state import ConfluenceState
from sphinxcontrib_confluencebuilder_util import ConfluenceTestUtil as _
import os
import unittes... |
import csv
import requests
from datetime import datetime, timedelta
import re
# get json file of appellates based on circuit and year
def query(circuit, year):
return requests.get(f'https://www.govinfo.gov/wssearch/rb//uscourts/appellate/{circuit}/{year}?fetchChildrenOnly=1&offset=0')
# get new appellates for a ... |
from django.urls import path
from .views import ArticleDetail, ArticleIndex
app_name = "news"
urlpatterns = [
path("", ArticleIndex.as_view(), name="index"),
path("<slug:slug>/", ArticleDetail.as_view(), name="detail"),
]
|
from rest_framework.viewsets import ModelViewSet
from apps.page.models import Page
from apps.page.serializers import PageSerializer
class PageViewSet(ModelViewSet):
serializer_class = PageSerializer
queryset = Page.objects.all()
search_fields = ["name", "description"]
filterset_fields = ["name", "desc... |
def println(args):
print(*args)
def py_call(args):
f, args, kwargs = args
args = list(args)
kwargs = dict([tuple(e) for e in kwargs])
return f(*args, **kwargs)
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
from django.http import Http404
from django.shortcuts import reverse
from django.views.generic import DetailView, ListView, CreateView, UpdateView, RedirectView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.timezone import now
from django.utils.translation import gettext as _
from dateuti... |
import json
import logging
import os
from datetime import datetime
import locale
from bs4 import BeautifulSoup
from src.network_utils import get_content_make_soup
logger = logging.getLogger()
# locale.setlocale(locale.LC_ALL, "fa_IR")
def ukIndependentScraper(url:str, page_soup:BeautifulSoup) -> dict:
"""
Scrape o... |
# -*- coding: utf-8 -*-
import unittest
from apiutil.json_api import (MANDATORY,
OPTIONAL,
TYPE,
PROPERTIES,
PROPERTY,
DEFAULT,
JsonApiPro... |
import json_lines
import matplotlib
import pandas as pd
import os
import sys
import numpy as np
from scipy import stats
from typing import List
import json
import matplotlib.pyplot as plt
plt.ion()
plt.rcParams['figure.figsize'] = [10, 8]
plt.style.use('seaborn-whitegrid')
plt.ion()
plt.rcParams['figure.figsize'] = [1... |
import boto, urllib2
from boto.ec2 import connect_to_region
from fabric.api import env, run, cd, settings, sudo, put
from fabric.api import parallel
import os
import sys
REGION = os.environ.get("AWS_EC2_REGION")
env.user = "ubuntu"
env.key_filename = ["insertKeyPair.pem"]
accessKey = 'insertAccessKey... |
import contextlib
import babel
import langcodes
from langcodes.tag_parser import LanguageTagError
from redbot.core import commands, i18n
from redbot.core.utils.chat_formatting import humanize_number
tick = "\N{WHITE HEAVY CHECK MARK} "
cross = "\N{CROSS MARK} "
valid = lambda t, b: tick + t if b else cross + t
#####... |
import operator
import numpy as np
import pytest
import pytz
from pandas._libs.tslibs import IncompatibleFrequency
import pandas as pd
from pandas import Series, date_range
import pandas._testing as tm
def _permute(obj):
return obj.take(np.random.permutation(len(obj)))
class TestSeriesFlexArithmetic:
@py... |
# Databricks notebook source
# MAGIC %md
# MAGIC
# MAGIC ###  Batch processing with Delta Lake
# MAGIC
# MAGIC <img src="https://drive.google.com/uc?export=download&id=1cZJCR5Z_9VDG05u0VfKplDjk7k5r6Y7I" width=1012/>
#... |
from __future__ import absolute_import
from collections import Mapping, Sequence
from cerberus.platform import _int_types, _str_type
def normalize_schema(schema):
if not isinstance(schema, dict):
return schema
for key, value in schema.iteritems():
if key == 'coerce':
try:
... |
import matplotlib.pyplot as plt
import ukpopulation.nppdata as NPPData
import ukpopulation.snppdata as SNPPData
import ukpopulation.utils as utils
# initialise the population modules
npp = NPPData.NPPData()
snpp = SNPPData.SNPPData()
# 50 years, roughly half is extrapolated
years = range(2016, 2067)
lad = "E08000021... |
#
# General-purpose Photovoltaic Device Model - a drift diffusion base/Shockley-Read-Hall
# model for 1st, 2nd and 3rd generation solar cells.
# Copyright (C) 2008-2022 Roderick C. I. MacKenzie r.c.i.mackenzie at googlemail.com
#
# https://www.gpvdm.com
#
# This program is free software; you can redist... |
# coding: utf-8
# TODO: - init_fem is called whenever we call discretize. we should check that
# nderiv has not been changed. shall we add quad_order too?
# TODO: avoid using os.system and use subprocess.call
import sys
import os
import importlib
from mpi4py import MPI
from psydac.api.ast.fem import... |
import sys
import os
import csv
from rdflib.term import Statement
from wikiFunctions import CreateClaim, getClaim, CreateProperty, CreateItem, CreateReferenz, SetTarget, CheckForEntry, CreateWerk, CreateAuthor, getItems
from wikiSQL import GetEntryOverSPARQL, SparQL_Mode, SparQL_Properties, get_results
import pywikibo... |
#!/usr/bin/env python3
# This file produces Figure 1, Figure 2, Table 1, Figure S3 of Arnscheidt and Rothman - Asymmetry of extreme Cenozoic climate-carbon cycle events (2021)
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as signal
import scipy.fft as fft
from scipy.special import gammainc
p... |
def test_demo(py):
py.visit('https://weathershopper.pythonanywhere.com/')
assert py.title() == 'Current Temperature'
py.get('a[href="/sunscreen"]').click()
assert py.title() == 'The Best Sunscreens in the World!'
#add item to cart
py.get('button[class="btn btn-primary"]').is_displaye... |
#!/usr/bin/env python
#
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import collections
import re
import optparse
import os
from string import Template
import sys
from util import build_utils
class En... |
import torch
from torch.autograd import Function
from .solvers import pdipm
from .solvers.pdipm import KKTSolvers
from .util import bger, extract_batch_size
class LCPOptions():
def __init__(self, eps=1e-12, verbose=-1, not_improved_lim=3,
max_iter=10, extend=0, solver_type=1):
self.eps =... |
from .resource import Resource
from .ec2 import EC2InstanceResource
from .iam import IAMRoleResource, IAMInstanceProfileResource
import pkg_resources
class ElasticBeanstalkEnvironment(EC2InstanceResource):
"""
Creates an EC2 server resource with the code deploy agent running.
Takes the same keyword paramet... |
from flask import current_app as app, jsonify, abort, request
from arachneserver.scrapy_utils import start_crawler
def list_spiders_endpoint():
"""It returns a list of spiders available in the SPIDER_SETTINGS dict
.. version 0.4.0:
endpoint returns the spidername and endpoint to run the spider from
... |
# Sets do not contain duplicate elements
example = set()
example.add(42)
example.add(False)
example.add(3.14159)
print(example)
print("Length of set : ",len(example))
print("Removing element 42 from the set")
example.remove(42)
print(example)
# element can also be removed using discard method
print("Adding element 50 ... |
class FileCacheManager:
filecontent=[]
def __init__(self,fileName):
'''
constructor
@param fileName: filename containing config
@type fileName: parses the content and stores the lines in filecontent
'''
f=open(fileName,'r')
for text in f.readlines():
... |
class Algorithm:
def __init__(self, context):
self.__context = context
def start(self):
self.__func38()
def __func38(self):
if self.__context.perception(5):
return self.__func6()
if self.__context.perception(0):
if self.__context.perception(6):
... |
import numpy as np
def next_batch(x, y, batch_size):
N = x.shape[0]
batch_indeces = np.random.permutation(N)[:batch_size]
x_batch = x[batch_indeces]
y_batch = y[batch_indeces]
return x_batch, y_batch
|
#!/usr/bin/env python
# coding: utf-8
# In[3]:
###------NYC Crimes by precinct data -----###
# In[4]:
# Data exploration
import pandas as pd
import numpy as np
from NYC_GetCleaned_HistoricData import getCleanedDataFrame
from data_utility import getCurrentDirectory, readCsvFile
from NYC_GetCleaned_TotalPopulation... |
file = input("Enter a file name: ")
fhand = open(file)
for line in fhand:
line_new = line.strip()
print(line_new.upper()) |
from kivymd.uix.screen import MDScreen
from kivy.clock import Clock
from modules.core.exerciseinfo import *
from modules.ui.eprogressbar import EProgressBar
import mido
import threading
class ExerciseScreen(MDScreen):
def __init__(self, **kwargs):
super(ExerciseScreen, self).__init__(**kwargs)
s... |
from inspect import getmembers
class CohortProperty(object):
"""
Instances of this are useful as properties of Cohort instances.
If a Cohort declares a property X, of type CohortProperty, its __init__ will try to
do this: self.X = data.X and raise an exception if it can't
"""
class Cohort(object... |
# -*- coding: utf-8 -*-
import unittest
from nose.tools import * # PEP8 asserts
from flask import Flask, url_for
from framework.routing import Rule, json_renderer, process_rules
class RuleTestCase(unittest.TestCase):
def setUp(self):
# create a new app for every test
self.app = Flask(__name__)... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
import hmac
import hashlib
def is_webhook_authentic(webhook_secret, request_body, sent_signature):
"""Used to verify that requests sent to a webhook endp... |
import os
from datetime import timedelta
DEBUG = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
SITE_ID = 1
MIDDLEWARE_CLASSES = [
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
... |
from .entity import Entity, EntityType
from .validator import PropertyValidator
from .calm_ref import Ref
from calm.dsl.log import get_logging_handle
LOG = get_logging_handle(__name__)
class AccountProviderType(EntityType):
__schema_name__ = "AccountProvider"
__openapi_type__ = "app_account_provider"
clas... |
from flask import request, Blueprint
from flask_restful import Resource
from flask_jwt_extended import jwt_required, get_current_user, get_jwt_identity
from {{cookiecutter.app_name}}.commons import db_util, common_fun
from {{cookiecutter.app_name}}.api.schemas.user import UserSchema
from {{cookiecutter.app_name}}.commo... |
import arcade
from game.entity import Entity
import game.constants as constants
class Projectile(Entity):
"""A projectile. Who knows what it does?"""
projectile_sound = arcade.load_sound(constants.PROJECTILE_SOUND)
def __init__(self, sprites: dict, path: str, scaling:int, position: tuple, velocity: tup... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.