content
stringlengths
0
894k
type
stringclasses
2 values
from uwsgidecorators import * import gevent @spool def longtask(*args): print args return uwsgi.SPOOL_OK def level2(): longtask.spool(foo='bar',test1='test2') def level1(): gevent.spawn(level2) def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) ...
python
st=input("Enter String") r=st.split(" ") l=[] s=" " for i in r: d=list(i) if d[0]=='i' or d[0]=='o': for ele in d: s=s+ele l.append(s) s=" " vowel=" ".join(l) print(vowel)
python
# 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. import secrets import sys import tempfile import time import boto3 import bottle import sqlalchemy as db import common.auth as _auth import co...
python
import jax.numpy as jnp from jax import jit from onnx_jax.handlers.backend_handler import BackendHandler from onnx_jax.handlers.handler import onnx_op from onnx_jax.pb_wrapper import OnnxNode @onnx_op("Less") class Less(BackendHandler): @classmethod def _common(cls, node: OnnxNode, **kwargs): @jit ...
python
from flask import Flask, jsonify, request, render_template, flash, redirect, url_for from flask_cors import CORS import subprocess from subprocess import Popen, PIPE from subprocess import check_output import pandas as pd import pickle import sklearn import numpy as np from PIL import Image import os from werkzeug.util...
python
# This File Will Loop execute. from machine import Pin import time LED = Pin(18, Pin.OUT) # Set Running Led # Python and WebDAV cross, which leads to the Python sequence is not stable. # So You Can Switch Python and WebDAV through external Button to stable execute. Button = Pin(27, Pin.IN) while 0 == Button.value():...
python
from .utils import * Any = Var(annotation=typing.Any) AnyList = Var(annotation=list) Int = Var(annotation=int) Float = Var(annotation=float) Str = Var(annotation=str) Array = Var(annotation=np.ndarray, name='Array') ArrayList = Var(annotation=TList[Array], name='ArrayList') FloatDict = Var(annotation=TDict[str, float]...
python
while True: try: a=input() except EOFError: break except KeyboardInterrupt: break print(a)
python
import logging import numpy as np import pandas as pd import pytest import calc # noqa from const import ProdStatRange from schemas import ProductionWellSet from tests.utils import MockAsyncDispatch from util.pd import validate_required_columns logger = logging.getLogger(__name__) @pytest.fixture(scope="session")...
python
import glob import matplotlib.image as mpimg import os.path from davg.lanefinding.Pipeline import Pipeline def demonstrate_lane_finding_on_test_images(data): pipeline = Pipeline() for idx in range(len(data)): # Read in a test image img = mpimg.imread(data[idx]) # Process it ...
python
import argparse import os import torch import torch.nn as nn import torch.nn.parallel import torch.optim as optim import torch.utils.data import torch.nn.functional as F import time from dataloader import KITTILoader as DA import utils.logger as logger import models.anynet parser = argparse.ArgumentParser(description...
python
import os import logging from typing import Dict, Tuple from .read import AppDataReader from .fstprocessor import FSTDirectory, FSTFile from ... import utils _logger = logging.getLogger(__name__) class AppExtractor: def __init__(self, fst_entries: Tuple[Dict[str, FSTDirectory], Dict[str, FSTFile]]): se...
python
""" vtelem - A module for basic frame interfaces. """ # built-in import math from typing import Any, Dict, Tuple # internal from vtelem.classes.byte_buffer import ByteBuffer from vtelem.classes.type_primitive import TypePrimitive, new_default from vtelem.enums.primitive import random_integer FRAME_OVERHEAD = new_def...
python
##################################################################################### # # Copyright (c) Microsoft Corporation. All rights reserved. # # This source code is subject to terms and conditions of the Microsoft Public License. A # copy of the license can be found in the License.html file at the root of this...
python
import source import rssfeeds from flask import Flask app = Flask(__name__) # Server test route @app.route('/hello') def hello_world(): return 'Hello, multiverse!' # Server main route @app.route('/') def display_urls(): test_response = "\n*** START ***\n" # Read the source file feed_urls = sourc...
python
# Copyright 2013 Cloudera 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...
python
from kivy.app import App from kivy.uix.widget import Widget from color_util import get_normalized_color from Chessboard import Chessboard, Color, Square class ChessGame(Widget): def on_touch_down(self, touch): return class ChessApp(App): def build(self): game = ChessGame() return ga...
python
# -*- coding: utf-8 -*- """Implentation of command `/logs`. """ from docker_utils import ( ContainerSelector, DockerCommand ) class Logs(DockerCommand): """Implementation of command `/start`. """ __HELP__ = """▪️ Usage: `/logs CONTAINER`: Shows logs of a container.""" LOG_LINES_TO_FETCH: int...
python
"""Test searching volume content.""" from itertools import repeat from random import randrange import json from django.test import TestCase, Client from django.test import RequestFactory from django.urls import reverse from apps.users.tests.factories import UserFactory from ...iiif.manifests.tests.factories import Mani...
python
from pyliterature import Pyliterature urls = [ 'http://science.sciencemag.org/content/355/6320/49.full', 'http://www.nature.com/nature/journal/v541/n7635/full/nature20782.html', 'http://www.sciencedirect.com/science/article/pii/S1751616116301138', 'http://pubs.acs.org/doi/full/10.1021/acscatal.6b029...
python
class Simple: def hello(self): return 'Hello' def world(self): return 'world!' def hello_world(self): return '%s %s' % (self.hello(), self.world())
python
import json f = open('./config.json') config = json.load(f) print(config['URL']) for k, v in config.items() : print(k, ":", v)
python
import socket print(socket.gethostbyaddr("8.8.8.8")) print(socket.gethostbyname("www.google.com"))
python
"""Sokoban environments.""" import random import numpy as np from gym_sokoban.envs import sokoban_env_fast from alpacka.envs import base class Sokoban(sokoban_env_fast.SokobanEnvFast, base.ModelEnv): """Sokoban with state clone/restore and returning a "solved" flag. Returns observations in one-hot encodin...
python
from registration.models import Events, Registration from rest_framework import serializers class EventListSerializer(serializers.HyperlinkedModelSerializer): has_users = serializers.SerializerMethodField() class Meta: model = Events fields = ['title', 'text', 'date', 'has_users'] def ge...
python
from __future__ import print_function from pipelineWrapper import PipelineWrapperBuilder import logging import os import yaml logging.basicConfig(level=logging.INFO) log = logging.getLogger() desc = """UCSC Precision Immuno pipeline""" config = ("""patients: {sample_name}: tumor_dna_fastq_1 : {tumor_dn...
python
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-05-12 05:48 from __future__ import unicode_literals import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('trans', '0003_auto_20170512_0537'), ...
python
# Generated by Django 2.2.6 on 2019-10-28 21:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0021_delete_pnotes'), ] operations = [ migrations.AlterField( model_name='note', name='modified', ...
python
""" This file is based on the code from https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py. """ from torchvision.datasets.vision import VisionDataset import torch import torch.utils.data as data import torchvision.transforms as transforms from PIL import Image import os import os.path impor...
python
# <Copyright 2022, Argo AI, LLC. Released under the MIT license.> """Geometric utilities for manipulation point clouds, rigid objects, and vector geometry.""" from typing import Tuple, Union import numpy as np from scipy.spatial.transform import Rotation from av2.utils.constants import PI from av2.utils.typing impo...
python
# Generated by Django 3.0.7 on 2020-07-28 14:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('disdata', '0028_auto_20200728_0924'), ] operations = [ migrations.AlterField( model_name='disease', name='vaccinatio...
python
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import unicode_literals import functools import logging import threading import re import uuid import tenacity from past.builtins import xrange from tenacity import (after_log, retry_if_exception, stop_after_attempt, ...
python
# -*- coding: utf-8 -*- import astropy.units as u import numpy as np import os.path import astropy.io.fits as fits import numbers from operator import itemgetter import scipy.interpolate import scipy.optimize class OpticalSystem(object): """Optical System class template This class contains al...
python
# Copyright (c) ACSONE SA/NV 2018 # Distributed under the MIT License (http://opensource.org/licenses/MIT). import logging from ..router import router from ..tasks.main_branch_bot import main_branch_bot from ..version_branch import is_main_branch_bot_branch _logger = logging.getLogger(__name__) @router.register("p...
python
import os import pathlib import pytest from mopidy_local import translator @pytest.mark.parametrize( "local_uri,file_uri", [ ("local:directory:A/B", "file:///home/alice/Music/A/B"), ("local:directory:A%20B", "file:///home/alice/Music/A%20B"), ("local:directory:A+B", "file:///home/alic...
python
import torch import numpy as np from torch import nn, optim, Tensor from ..envs.configuration import Configuration from .abstract import Agent # Default Arguments. bandit_mf_square_args = { 'num_products': 1000, 'embed_dim': 5, 'mini_batch_size': 32, 'loss_function': nn.BCEWithLogitsLoss(), 'opti...
python
expected_output = { 'traffic_steering_policy': { 3053: { "sgt_policy_flag": '0x41400001', "source_sgt": 3053, "destination_sgt": 4003, "steer_type": 80, "steer_index": 1, "contract_name": 'Contract2', "ip_version": 'IPV4', "refcnt": 1, "flag": '0x41400000', "stale": False, "traffic_...
python
def find_smallest(array): smallest = array[0] smallest_index = 0 for i in range(1, len(array)): if(array[i] < smallest): smallest = array[i] smallest_index = i return smallest_index res = [] my_array = [32,2,25,3,11,78,-2,32] print("my_array:", my_array) for i in range(l...
python
from enum import Enum class PayIDNetwork(Enum): # Supported networks RIPPLE_TESTNET = "xrpl-testnet" ETHEREUM_GOERLI = "eth-goerli" # ETHEREUM_MAINNET = "eth-mainnet" # RIPPLE_MAINNET = "xrpl-mainnet" @property def environment(self) -> str: return self.value.split("-")[1].upper()...
python
nome = input("Nome do cliente: ") dv = int(input("Dia do vencimento: ")) mv = input("Digite o mes de vencimento: ") fatura = input("Fatura: ") print("Olá,",nome) print("A sua fatura com vencimento em",dv,"de",mv,"no valor de R$",fatura,"está fechada.")
python
# integer Knapsack problem implementation def knapsack(size, inputs): inputs = sorted(inputs) history = {0: ()} for cur_input in inputs: for prev_value, prev_history in history.items(): # items instead of iteritems, to take a deep copy new_value = prev_value + cur_input new_...
python
from itertools import count import numpy as np import tensorflow as tf from sklearn.model_selection import train_test_split from nets.resnet_v2 import resnet_arg_scope, resnet_v2_50 from utils import preprocess, preprocess_val import argparse import os def parse_args(): parser = argparse.ArgumentParser("A scrip...
python
import os from dynaconf import settings from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database.models.transaction import Transaction from database.models.trade import Trade from database.models.types import Types from database.models.status import Status class Database(object): ...
python
## # Copyright (c) 2012 Sprymix Inc. # All rights reserved. # # See LICENSE for details. ## import sys from setuptools import setup, Extension if sys.version_info[:2] < (3, 3): raise RuntimeError('metamagic.json requires python 3.3 or greater') readme = open('README.rst').read() setup( name='metamagic.j...
python
from flask_sqlalchemy import SQLAlchemy from api.db.data_request import DataRequest db = SQLAlchemy() class ParachainData(db.Model): __tablename__ = 'parachain_data' id = db.Column(db.Integer, primary_key=True, autoincrement=True) para_id = db.Column(db.String) account_id = db.Column(db.String) re...
python
from IMLearn.learners import UnivariateGaussian, MultivariateGaussian import numpy as np # import plotly.graph_objects as go # import plotly.io as pio from matplotlib import pyplot as plt # pio.templates.default = "simple_white" def test_univariate_gaussian(): # Question 1 - Draw samples and print fitted model ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2021 Intel 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 # # Unl...
python
# 将带分割的圆的坐标信息写入文件 class SegmentInfoWriter(object): def __init__(self, file): self.file=file def setSegmentInfo(self,all_circles, needSegment_idx): self.all_circles = all_circles self.needSegment_idx = needSegment_idx self.__write() def __write(self): num=len(self....
python
from midiutil import MIDIFile from itertools import repeat import sys bpm = 60 vartrack = 2 toadd = [1,(60,1,2),(62,1,25),(64,1,64),(65,1,53),(67,1,32),(69,1,14),(71,1,87),(72,1,69),2] toadd1= [1,(60,1,5),(62,1,55),(64,1,31),(65,1,45),(67,1,115),(69,1,54),(71,1,87),(72,1,69),2] midi = MIDIFile(vartrack) #it takes the...
python
import time import datetime import webbrowser import pyperclip import pyautogui AzkharAlsabah = [ "اللَّهُمَّ أنْتَ رَبِّي لا إلَهَ إلَّا أنْتَ، خَلَقْتَنِي وأنا عَبْدُكَ، وأنا علَى عَهْدِكَ ووَعْدِكَ ما اسْتَطَعْتُ، أعُوذُ بكَ مِن شَرِّ ما صَنَعْتُ، أبُوءُ لكَ بنِعْمَتِكَ عَلَيَّ، وأَبُوءُ لكَ بذَنْبِي فاغْف...
python
import numpy as np import pandas as pd import freqtrade.vendor.qtpylib.indicators as qtpylib def test_crossed_numpy_types(): """ This test is only present since this method currently diverges from the qtpylib implementation. And we must ensure to not break this again once we update from the original sour...
python
import os import subprocess def export_script_and_view(model, os_path, contents_manager): if model["type"] != "notebook": return dir_name, file_name = os.path.split(os_path) file_base, file_ext = os.path.splitext(file_name) if file_base.startswith("Untitled"): return expor...
python
import os from collections import defaultdict from tempfile import NamedTemporaryFile from django.conf import settings from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin from django.contrib.messages.views import SuccessMessageMixin from django.core.ex...
python
#!/usr/bin/env python3 from pybytom.wallet import Wallet from pybytom.assets import BTM as ASSET from pybytom.utils import amount_converter import json # Choose network mainnet, solonet or testnet NETWORK: str = "mainnet" # Default is mainnet # Wallet seed SEED: str = "b3337a2fe409afbb257b504e4c09d36b57c32c452b71a0...
python
""" 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...
python
# vim:ts=4:sw=4:expandtab '''Simple echo server. ''' from diesel import Application, Service, until_eol, send def hi_server(addr): while 1: inp = until_eol() if inp.strip() == "quit": break send("you said %s" % inp) app = Application() app.add_service(Service(hi_server, 8013)) ...
python
from flask import Flask,request,redirect,render_template,url_for,send_from_directory from markupsafe import escape import calculator as hsc application = Flask(__name__) @application.route('/') def index(): return redirect(url_for('calculation')) @application.route('/calculation', methods=["POST", "G...
python
import json import logging from typing import TYPE_CHECKING, Any, Optional, TypeVar from redis.asyncio import Redis, from_url from mognet.exceptions.base_exceptions import NotConnected from mognet.state.base_state_backend import BaseStateBackend from mognet.state.state_backend_config import StateBackendConfig from mo...
python
import logging import tempfile import zipfile from collections import OrderedDict from pathlib import Path import numpy as np from PIL import Image from scipy.io import loadmat from . import download from .enums import Split logger = logging.getLogger(__name__) class LeedsSportBase: FOLDER_NAME = None DATA...
python
import torch import os from sklearn.neighbors import kneighbors_graph import time import datetime import numpy as np from scipy import sparse class GraphConstructor(object): """ K-NearestNeighbors graph by Euclidean distance. """ def __init__(self, config): self.temperature = config.temperatur...
python
from collections import deque import pandas as pd import numpy as np RT_lambda = int(input("Input inter-arrival time of RT messages: ")) nonRT_lambda = int(input("Input inter-arrival time of non RT messages: ")) RT_service = int(input("Input service time of an RT message: ")) nonRT_service = int(input("Input service t...
python
# coding:utf-8 from gevent import monkey;monkey.patch_all() import config from config import COURSEURL from spider.parser import Parser from spider.downloader import Downloader from filedeal.file_downloader import File_Downloader ''' 这个类是爬虫的主逻辑 ''' class SpiderMan(object): def __init__(self): self.downloa...
python
import mimetypes from collections import OrderedDict import json import requests from django.http import HttpResponse from django.shortcuts import render from .client import RestClient from .forms import * import datetime import time def index(request): return render(request, 'home/index.html') cl...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 4 12:01:56 2018 Flow Visualization module within the FlowTools package. @author: nhamilto @contact: nicholas.hamilton@nrel.gov. @version: v.0.1 """ import matplotlib.pyplot as plt import numpy as np #%% # 2D contour plot: coords = ['y', 'z'], v...
python
''' File: addModel.py Project: restful Author: Jan Range License: BSD-2 clause ----- Last Modified: Wednesday June 23rd 2021 7:44:17 pm Modified By: Jan Range (<jan.range@simtech.uni-stuttgart.de>) ----- Copyright (c) 2021 Institute of Biochemistry and Technical Biochemistry Stuttgart ''' from flask import request, se...
python
from sklearn.base import TransformerMixin, BaseEstimator from gensim.models import LdaMulticore, CoherenceModel from gensim.corpora import Dictionary from gensim.matutils import corpus2dense, corpus2csc import numpy as np class GensimLDAVectorizer(BaseEstimator, TransformerMixin): def __init__(self, num_topics, r...
python
# -*- coding: utf-8 -*- # Author: Olaf Hauk <olaf.hauk@mrc-cbu.cam.ac.uk> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # Eric Larson <larson.eric.d@gmail.com> # # License: BSD (3-clause) import os.path as op import numpy as np from numpy.testing import (assert_equal, assert_array_almost_equal, ...
python
"""Module for local file system saving.""" import os import shutil from save_base import BaseSaver import util class FileSaver(BaseSaver): """A class for operations on files, handling the interaction with the local filesystem.""" def __init__(self, base_path): super().__init__(base_path) def ex...
python
''' 实验名称:人体感应传感器 版本:v1.0 日期:2021.1 作者:01Studio 社区:www.01studio.org ''' import time from machine import SoftI2C,Pin #从machine模块导入I2C、Pin子模块 from ssd1306 import SSD1306_I2C #从ssd1306模块中导入SSD1306_I2C子模块 #初始化oled i2c = SoftI2C(scl=Pin(10), sda=Pin(11)) #SoftI2C初始化:scl--> 10, sda --> 11 oled = SSD1306_I2C(128, 64, ...
python
# # PySNMP MIB module F5-BIGIP-COMMON-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/F5-BIGIP-COMMON-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:57:38 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
python
# Copyright (c) ZJUTCV. All rights reserved. def points2xyxy(points): """ Args: points (list): Returns: """ x_list = [points[i] for i in range(0, 8, 2)] y_list = [points[i] for i in range(1, 8, 2)] x_min = min(x_list) x_max = max(x_list) y_min = min(y_list) y_max = max...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.shortcuts import get_object_or_404 from django.utils import six from django.views.generic import ArchiveIndexView, DateDetailView from glitter.mixins import GlitterDetailMixin from .models import Category, Po...
python
import random from pyecharts import options as opts from pyecharts.charts import Polar c = ( Polar() .add("", [(10, random.randint(1, 100)) for i in range(300)], type_="scatter") .add("", [(11, random.randint(1, 100)) for i in range(300)], type_="scatter") .set_series_opts(label_opts=opts.LabelOpts(is...
python
from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.utils.timezone import now from django.utils import timezone # from froala_editor.fields import FroalaField from django.contrib.auth import get_user_model # Create your models here. # from .models impo...
python
def gcd(a, b): if a % b == 0: return b else: return gcd(b, a % b) def main(): A = B = 1 for a in xrange(10, 100): for b in xrange(a + 1, 100): x = a % 10 y = b / 10 if x != y: continue x = ...
python
""" Vowel to Vowel Links Given a sentence as txt, return True if any two adjacent words have this property: One word ends with a vowel, while the word immediately after begins with a vowel (a e i o u). Examples vowel_links("a very large appliance") ➞ True vowel_links("go to edabit") ➞ True vowel_links("an open fire...
python
import pytest from pathlib import Path # pylint: disable=wrong-import-position,import-error import basicgit as git # Module Under Test import get_mpy # No Mocks, does actual extraction from repro # TODO: allow tests to work on any path, not just my own machine @pytest.mark.parametrize( "path, port, board", ...
python
# # Autogenerated by Thrift Compiler (0.9.0) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py # from thrift.Thrift import TType, TMessageType, TException, TApplicationException import Status.ttypes import ErrorCodes.ttypes import Types.ttypes import Exprs.ttypes import Catal...
python
# 基于梯度下降的线性回归 # 线性回归方程: y = w1 * x + w0 * 1 # 用线性代数中的矩阵表述为: y = [w1, w0] * [x, 1]T # 目标:使用梯度下降的方法,根据样本数据,反复迭代获取最佳的 w0,w1。最后得到目标方程。 # 数据 bread_price = [[0.5,5],[0.6,5.5],[0.8,6],[1.1,6.8],[1.4,7]] # 更新一次 w0, w1 的值 BGD(Batch Gradient Descent,批量梯度下降法) def BGD_step_gradient(w0_current, w1_current, points, learninggRate)...
python
#!/usr/bin/env python3 import glooey import pyglet pyglet.font.add_file('Lato-Regular.ttf') pyglet.font.load('Lato Regular') class WesnothLabel(glooey.Label): custom_font_name = 'Lato Regular' custom_font_size = 10 custom_color = '#b9ad86' custom_alignment = 'center' window = pyglet.window.Window() ...
python
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class Norm(nn.Module): """ Graph Normalization """ def __init__(self, norm_type, hidden_dim=64): super().__init__() if norm_type == 'bn': self.norm = nn.BatchNorm1d(hidden_dim) elif norm_t...
python
import ldap import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ARCHIVE_API = { 'DATASET_ARCHIVE_ROOT': os.getenv('DATASET_ARCHIVE_ROOT', os.path.join(BASE_DIR, 'archives')), 'DATASET_ARCHIVE_URL': '/archives/', # not used 'DATASET_ADMIN_MAX_UPLOAD_SIZE': 2147483648, # in byt...
python
from django.conf.urls import url from ClassView import views from ClassView.views import check_ip urlpatterns = [ #方案1 直接在路由中进行装饰 # url(r'^post2$', check_ip(views.PostView.as_view())), url(r'^post2$', views.PostView.as_view()), url(r'^index$',views.index), url(r'^block$',views.block) ]
python
#BookStore class Book: def __init___(self, pages, price, author, id1, title): self.pages = pages self.price = price self.author = author self.id1 = id1 self.title = title class BookStore: def __init__(self, book_store_name, book_list): self.book_list = book_list ...
python
import math def area_circle( r ): area = (math.pi * (r ** 2)) return area def volume_sphere( r ): volume = ((4/3) * math.pi) * (r ** 3) return volume #MAIN radius = float(input("Enter a radius:")) #call the area function radius_circle = area_circle(radius) print(f'The area of the circle is {radius_c...
python
# -*- coding: utf-8 -*- """Flask extensions that can be lazily accessed before instantiation of the web application.""" from flasgger import Swagger from flask_sqlalchemy import SQLAlchemy from embeddingdb.version import VERSION __all__ = [ 'db', 'swagger', ] db = SQLAlchemy() swagger_config = Swagger.DEF...
python
# Copyright (c) 2014-2016, Intel Corporation All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions...
python
import time import logging import numpy as np # from scipy.optimize import brent # from math import gcd # from qcodes import Instrument from qcodes.utils import validators as vals # from qcodes.instrument.parameter import ManualParameter from pycqed.analysis import analysis_toolbox as atools # from pycqed.utilities.ge...
python
def word2byte_array(array): assert len(array) == 32 res = [] for word in array: assert word >= 0 assert word <= 0xffff res.append(word & 0xff) res.append(word >> 8) return res def avx512_dwords(array): assert len(array) == 64 dwords = [] for i in range(0, 6...
python
#!/usr/bin/env python # Copyright 2016 The Kubernetes 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 appli...
python
#!/usr/local/bin/python3 -u import minecraft_launcher_lib as mll import subprocess # Minecraft version mc_version = "1.18.1-rc2" # Asset index is same but without final revision asset_index = "1.18" # Your email, username and password below login = "yourEmailUsername" password = "seekritPasswordHere" # Get Mine...
python
from concurrent import futures import logging import grpc import app_pb2 import app_pb2_grpc class Greeter(app_pb2_grpc.GreeterServicer): def SayHello(self, request, context): for key, value in context.invocation_metadata(): print('Received initial metadata: key=%s value=%s' % (key, value))...
python
# flake8: noqa: F401 from dataclasses import dataclass, field from datetime import datetime from typing import Any, Dict, List, Optional from trakt.core.models import ( Comment, Episode, Movie, Person, Season, Show, TraktList, User, ) from trakt.core.paths.response_structs.movie_struct...
python
import cPickle as pickle import theano_funcs import utils import vgg16 from lasagne.layers import set_all_param_values from tqdm import tqdm from os.path import join def warp_images(): print('building model') layers = vgg16.build_model((None, 3, 227, 227)) batch_size = 32 infer_dir = join('data', 'i...
python
from copy import deepcopy from re import match from .error import throw __all__ = [ 'Type', 'ModuleType', 'BooleanType', 'NoneType', 'NumberType', 'StringType', 'TupleType', 'ListType', 'NameType', 'SliceType', 'ArgType', 'ArgumentsType', 'FunctionType', 'Built...
python
from __future__ import division import subprocess import ase print(ase.data.chemical_symbols) for pseudo,pseudo_min in zip(["LDA", "GGA"], ["lda", "gga"]): for sym in ase.data.chemical_symbols: cmd = "wget https://departments.icmab.es/leem/siesta/Databases/Pseudopotentials/Pseudos_" + pseudo + "_Abinit/" +...
python
import Item import Shop item = Item.Item("first module item", 10) shop = Shop.Shop() if __name__ == "__main__": print item print shop
python
import os, sys # import FIFE main module from fife import fife # import the ApplicationBase from fife.extensions.basicapplication import ApplicationBase # import FIFE pychan module from fife.extensions import pychan # import scripts from scripts import gameplay from scripts.common import eventListenerBase class Ga...
python
import re from modules import RGSubModule from functions import RGFunctionFactory import base import state module = RGSubModule('t') base.base(module) #__all__ = ["module"] apply = base.apply @module @RGFunctionFactory('a') def ta(stack): stack.append(input()) @module @RGFunctionFactory('b') def tb(stack): stack.appe...
python
# Basic libraries import numpy as np import tensorflow as tf import os from data_gen import get_next_batch from util import is_existing tf.reset_default_graph() tf.set_random_seed(2016) np.random.seed(2016) # LSTM-autoencoder from LSTMAutoencoder import * # Constants batch_num = 1 hidden_num = 128 step_num = 200 # ...
python