content stringlengths 5 1.05M |
|---|
'''
This module contains utility functions for dealing with skos providers.
'''
import logging
from rdflib import Graph
from rdflib import Literal
from rdflib import Namespace
from rdflib.namespace import DCTERMS
from rdflib.namespace import RDF
from rdflib.namespace import SKOS
from rdflib.namespace import VOID
from ... |
from django.urls import path
from . import views
app_name = "ui"
urlpatterns = [
path('students/', views.studentlist),
path('students/<int:pk>/', views.studentdetail),
path('lessons/', views.lessonlist),
path('lessons/<int:pk>/', views.lessondetail),
path('', views.index),
]
|
# -*- coding: utf-8 -*-
import BU_RvNN
def str2matrix(Str, MaxL): # str = index:wordfreq index:wordfreq
wordFreq, wordIndex = [], []
l = 0
for pair in Str.split(' '):
wordFreq.append(float(pair.split(':')[1]))
wordIndex.append(int(pair.split(':')[0]))
l += 1
ladd = [0 for i in... |
# 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
# d... |
n = int(input('Digite um número inteiro positivo: '))
soma = 0
conta = 0
num = 2
while conta < n:
primo = True
for i in range(2, num):
if num % i == 0:
primo = False
break
if primo:
print(num)
soma += num
conta += 1
num += 1
print(soma)
#https://pt.... |
import requests
import yaml
import json
import click
gen_host = 'http://bytepower-alb-01-1801127871.us-east-1.elb.amazonaws.com:9090'
def get_download_filename(language, options):
if language == 'csharp':
return '{}_{}.zip'.format(
options['packageName'],
options['packag... |
"""The classes in this file are domain specific, and therefore include
specifics about the design space and the model parameters.
The main jobs of the model classes are:
a) define priors over parameters - as scipy distribution objects
b) implement the `predictive_y` method. You can add
whatever useful helper functi... |
# Copyright (c) 2012 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 ctypes
import json
class ChromeDriverException(Exception):
pass
class UnknownCommand(ChromeDriverException):
pass
class UnknownError(ChromeDr... |
#
# Copyright 2021 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
"""Updates gcp report summary tables in the database."""
import datetime
import logging
from tenant_schemas.utils import schema_context
from masu.database.gcp_report_db_accessor import GCPReportDBAccessor
from masu.external.date_accessor import D... |
import _thread
import sched
import time
import traceback
from pprint import pformat
import requests
from Logger import logger
from MessageQuery import MessageQuery
class Bot:
def __init__(self):
self.__update_id = None
# Token loading
file = open("bot_token.txt", "r")
self.__to... |
from flask import Flask, request,redirect
from os import path,execl
from sys import executable,argv
from function import getNewImage, keepToken, reqToken
from threading import Thread
from time import sleep
app = Flask(__name__)
dir_path = path.dirname(path.realpath(__file__))
# @app.after_request
# def after_request_f... |
from .owner import Owner
def setup(client):
client.add_cog(Owner(client)) |
import numpy
import pytest
import disba
import helpers
@pytest.mark.parametrize(
"wave, parameter, kref, atol",
[
("rayleigh", "thickness", -0.130, 1.0e-3),
("rayleigh", "velocity_p", 0.173, 1.0e-3),
("rayleigh", "velocity_s", 0.722, 1.0e-3),
("rayleigh", "density", 0.000245, ... |
import logging
from viadot.tasks import AzureSQLCreateTable, AzureSQLDBQuery
logger = logging.getLogger(__name__)
SCHEMA = "sandbox"
TABLE = "test"
def test_azure_sql_create_table():
create_table_task = AzureSQLCreateTable()
create_table_task.run(
schema=SCHEMA,
table=TABLE,
dtype... |
import pygame
class Box(pygame.sprite.Sprite):
def __init__(
self, x, y, canvas_width, canvas_height, player_group, block_group,
width=10, height=10,
color=(0, 0, 0)
):
pygame.sprite.Sprite.__init__(self)
self.width = width
self.height = height
self.canv... |
# python sprite.
# surface로 그리기가 가능하나 더 편리한 기능이 있는 지 살펴본다.
# update, draw : self.image 사용 |
#importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pandas as pd
import numpy as np
import random as rd
from sklearn.decomposition import PCA
from sklearn import preprocessing
import matplotlib.pyplot as plt # NOTE: This was tested with matplotlib v. 2.1.0
import xlrd... |
from component import config
from component import layout_manager
from component import scene_manager
from util import Node
from .system import System
from logcat import LogCat
class SceneFactory(System):
@LogCat.log_func
def __init__(self):
super().__init__()
self.on("cmd_scene_change", s... |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from mach import MachSolver, Mesh, Vector
num_magnets_true = 40
num_magnets = 40
mag_pitch = num_magnets // num_magnets_true
num_slots = 24
start = 0
nturns = 1
torque = []
if __name__ == "__main__":
for rotation in range(start, start+nturns):... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import numpy as np
import time
from deprecated import deprecated
from sklearn import datasets
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import Linea... |
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import zfit
def pltdist(data, bins, bounds):
y, bin_edges = np.histogram(data, bins=bins, range=bounds)
bin_centers = 0.5 * (bin_edges[1:] + bin_edges[:-1])
yerr = np.sqrt(y)
plt.errorbar(bin_centers, y, yerr=yerr, fmt=".", col... |
import matplotlib.pyplot as plt
import pandas as pd
from scripts.python.experiments.data_reader import read_data
from scripts.python.utils.figure_config import fig_size_in, fig_format
from scripts.python.utils.system_config import plot_output_path
from scripts.python.utils.utils import modes_title_string
if __name__ ... |
import tensorflow as tf
def build_fc_net(input_tfs, layers,
activation=tf.nn.relu,
weight_init=tf.contrib.layers.xavier_initializer(),
reuse=False):
curr_tf = tf.concat(axis=-1, values=input_tfs)
for i, size in enumerate(layers):
with tf.vari... |
from ReferenceModification.NavAgents.AgentNav import NavTrainVehicle
from ReferenceModification.NavAgents.AgentMod import ModVehicleTrain
from toy_f110 import ForestSim
def train_vehicle(env, vehicle, steps):
done = False
state = env.reset()
print(f"Starting Training: {vehicle.name}")
for n in r... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
import asyncio
from asyncio import sleep
from userbot import BOTLOG, BOTLOG_CHATID
from userbot import CMD_HANDLER as c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import os,re,h5py,pyproj
def atl06_to_dict(filename, beam, field_dict=None, index=None, epsg=None):
"""
Read selected datasets from an ATL06 file
Input arguments:
filename: ATl06 file to read
beam: a string specifying which ... |
from july.models import User
from django import forms
from django.contrib.auth.forms import UserCreationForm
class RegistrationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = User
fields = ('username',)
def clean_username(self):
# Since User.username is unique, thi... |
import argparse
import os
import time
import copy
import torch
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
class ObjPushDataset(Dataset):
def __init__(self, dirname, size=None):
self.dirname = dirname
self.data = np.loadtxt(dirname + '.txt')
... |
from astropy.io import fits
import numpy as np
import os
from pathlib import Path
import pytest
from astrosource.periodic import plot_with_period, phase_dispersion_minimization
TEST_PATH_PARENT = Path(os.path.dirname(__file__)) / 'test_files'
TEST_PATHS = {'parent': TEST_PATH_PARENT / 'period',
'outca... |
import logging
__author__ = 'leif and david'
import math
import datetime
from django.contrib.auth.models import User
from pytz import timezone
from django.conf import settings
from ifind.seeker.trec_qrel_handler import TrecQrelHandler
from models import DocumentsExamined
from experiment_configuration import event_l... |
"""
This is the DSPython implementation of the Arduino example.
Modified for DSPython by Donghyeok Tak <tdh8316@naver.com>
The original code is:
/*
Blink
Turns an LED on for one second, then off for one second, repeatedly.
Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO
it is ... |
from .lib_template import *
class mDNSSeeker(Seeker):
"""Seeker (Identifier) for the mDNSResponder open source library."""
# Library Name
NAME = "mDNSResponder"
VERSION_STRING = NAME
# Overridden base function
def searchLib(self, logger):
"""Check if the open source library is located... |
import logging
import requests
import base64
from asn1crypto.cms import ContentInfo, IssuerAndSerialNumber
from .builders import PKIMessageBuilder, Signer
from .certificate import Certificate
from .crl import RevocationList
from .cryptoutils import digest_for_data, hex_digest_for_data
from .envelope import PKCSPKIEn... |
# inspired by the NmtMaster code
from ..node import RemoteNode
# status word 0x6041 bitmask and values in the list in the dictionary value
POWER_STATES_402 = {
'NOT READY TO SWITCH ON': [0x4F, 0x00],
'SWITCH ON DISABLED' : [0x4F, 0x40],
'READY TO SWITCH ON' : [0x6F, 0x21],
'SWITCHED ON' ... |
from .models import Template
from django.contrib import admin
admin.site.register(Template)
|
from spacel.provision.app.alarm.endpoint.email import EmailEndpoints
from test.provision.app.alarm.endpoint import RESOURCE_NAME, BaseEndpointTest
class TestEmailEndpoints(BaseEndpointTest):
def setUp(self):
super(TestEmailEndpoints, self).setUp()
self.endpoint = EmailEndpoints()
def topic_re... |
#!/usr/bin/env python
import urllib
import json
import os
#import psycopg2
from flask import Flask
from flask import request
from flask import make_response
# Flask app should start in global layout
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook():
req = request.get_json(silent=True... |
import pytest
from inqry.system_specs import cfgutil
@pytest.mark.skip
def test_get_hardware_overview_for_all_devices():
assert cfgutil.get_hardware_properties_for_attached_devices()
@pytest.mark.skip
def test_get_device_properties_for_all_devices():
assert cfgutil.get_device_properties_from_cfgutil_output(... |
# モデルの定義
from sqlalchemy import Column, Integer, String
from pydantic import BaseModel
# userテーブルのモデルUserTableを定義
class TestTable():
__tablename__ = 'test_table'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(20), nullable=False)
# POSTやPUTのとき受け取るRequest Bodyのモデルを定義
class ... |
import os
from dataclasses import dataclass
from pathlib import Path
@dataclass
class PathManager:
"""
Utility class that can be used to path related operations. It can resolve
local files relative to the rooth_path passed to the class at instantiation.
It can resolve absolute partial absolute paths, ... |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
import os
import cv2
import sys
import shutil
import random
import logging
import argparse
import tempfile
import traceback
import numpy as np
from glob import glob
from os.path import join
from pathlib import Path
from os.path import exists
from os.path import dirname
from os.path import basename
from datetime import ... |
from time import sleep
import pytest
from pymongo import MongoClient
from skython.db_interface import db_interface
@pytest.fixture(autouse=True)
def setup():
interface().nuke()
yield
interface().nuke()
def interface():
client = MongoClient("127.0.0.1")
system_db = "test"
schedule_col = "cata... |
import sublime_plugin
class PhpactorClassSearchCommand(sublime_plugin.TextCommand):
def run(self, edit):
keyword = self.get_current_word()
if not keyword:
return
request = {
'action': 'class_search',
'parameters': {
'short_name': keyword... |
'''
Created on Apr 23, 2020
@author: riaps
'''
from riaps.run.comp import Component
from enum import Enum
import inspect
import functools
from threading import RLock
try:
import cPickle
pickle = cPickle
except:
cPickle = None
import pickle
import traceback
# import pprint
class FSM(... |
from neo4j.v1 import GraphDatabase
uri = "bolt://localhost:7687"
driver = GraphDatabase.driver(uri)
|
#!/usr/bin/env python
import sys
with open("data/{0}/{0}_cb.log".format(sys.argv[1]), "a+") as log:
log.write(" ".join(sys.argv[-3:]) + "\n")
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
#Local or AWS machine:
#DEBUG = False
DEBUG = True
# In[2]:
#DL machine or not:
#DLM = False
DLM = True
# In[3]:
import os, sys, json, resource
import pandas as pd
import numpy as np
from random import shuffle
# In[4]:
# In[5]:
isup_classes= ['0', '1', '2... |
# Generated by Django 2.2.6 on 2019-10-17 16:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('scraper', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='post',
name='type',
field=m... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'gaochao'
import os
import pika
import json
import config.filesystem as filesystem
from module.storage.Db import Db
from module.aria2.Aria2 import Aria2
class RabbitMq(object):
def __init__(self):
self._connection = pika.BlockingConn... |
"""
Modified from https://github.com/tizita-nesibu/lidc-idri-visualization
"""
class NoduleCharstics:
def __init__(self):
self.subtlety = 0
self.internal_struct = 0
self.calcification = 0
self.sphericity = 0
self.margin = 0
self.lobulation = 0
s... |
from threading import Lock
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit, join_room, leave_room, \
close_room, rooms, disconnect
async_mode = None
app = Flask(__name__)
app.config['KEY'] = 'HAHA'
socketio = SocketIO(app, async_mode=async_mode)
thread = None
thr... |
num = int(input('\033[1;95;40mDigite um valor: '))
if num <= 10:
print('\033[49m\n\033[91;40m - Tabuada do {} - \033[49m'.format(num))
elif num <= 100:
print('\033[49m\n\033[91;40m - Tabuada do {} -\033[49m'.format(num))
else:
print('\033[49m\n\033[91;40m- Tabuada do {} -\033[49m'.format(num))
print('\033[9... |
# -*- coding: utf-8 -*-
import json
import re
from collections import OrderedDict
from http_service import HttpService
class AudiobooService(HttpService):
URL = 'http://audioboo.ru'
ARCHIVE_URL = "https://archive.org"
def available(self):
return True
def get_letters(self):
data = []
... |
# simple.py --
#
# Python implementation of the SIMPLE language from _Understanding Computation_
# by Tom Stuart.
#
# Note that printing the guillemet characters is troublesome when running Python
# from within Emacs; rather than try to debug the problem, I've substituted '<<'
# and '>>' for them below.
from __future_... |
# -*- coding: utf-8 -*-
from snoopy import db, pluginregistry
@pluginregistry.add('client-data', 'wigle', 'Wigle', js='/static/js/wigle.js')
def wigle(mac):
results = []
with db.SessionCtx() as session:
query = session.query(db.Probe, db.Wigle).\
filter(
db... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import vtk
def main(filename, curvature=0, scalarRange=None, scheme=None):
print("Loading", filename)
reader = vtk.vtkXMLPolyDataReader()
reader.SetFileName(filename)
curvaturesFilter = vtk.vtkCurvatures()
... |
import unittest
from footy.src.clubs.club_gateway import ClubGateway
from footy.test_data.test_data_paths import get_season_path
class ClubTest(unittest.TestCase):
def setUp(self):
season_path = get_season_path("Premier League", 2015, 2016)
self.club = ClubGateway(season_path).get_all()[0]
... |
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... |
# pylint: disable=inconsistent-return-statements
def sanitize(value, output_type):
"""
Handy wrapper function for individual sanitize functions.
:param value: Input value to be sanitized
:param output_type: Class of required output
:type output_type: bool or int
"""
# pylint: disable=no-e... |
from allennlp.data.data_loaders.data_loader import DataLoader, TensorDict, allennlp_collate
from allennlp.data.data_loaders.multiprocess_data_loader import MultiProcessDataLoader, WorkerError
from allennlp.data.data_loaders.multitask_data_loader import MultiTaskDataLoader
from allennlp.data.data_loaders.simple_data_loa... |
from flask import Flask, request
import pandas as pd
from flask_sqlalchemy import SQLAlchemy
import sqlite3
app = Flask(__name__)
DB = SQLAlchemy()
df = pd.read_csv('SpotifyAudioFeaturesApril2019.csv')
conn = sqlite3.connect('songs_df.sqlite3')
df.to_sql('songs', conn, if_exists='replace')
# class Song(DB.Model):... |
import networkx as nx
def find123Nei(G, node):
nodes = list(nx.nodes(G))
nei1_li = []
nei2_li = []
nei3_li = []
for FNs in list(nx.neighbors(G, node)):
nei1_li .append(FNs)
for n1 in nei1_li:
for SNs in list(nx.neighbors(G, n1)):
nei2_li.append(SNs)
... |
from utils import detector_utils as detector_utils
from keras.models import model_from_json
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import cv2
from DatasetLoader import DatasetLoader
from PIL import ImageOps
loader = DatasetLoader()
loader.load_data()
classes = loader.get_classes()
... |
from __future__ import print_function
import Pyro4
import chain
this = "B"
next = "C"
servername="example.chain."+this
daemon=Pyro4.core.Daemon()
obj=chain.Chain(this,next)
uri=daemon.register(obj)
ns=Pyro4.naming.locateNS()
ns.register(servername,uri)
# enter the service loop.
print("Server started... |
import streamlit as st
from src.data import check_all_datasets
from src.frontend.SessionState import session_get
from src.frontend.page_handling import handler
st.set_page_config(page_title="Recommender Systems",
page_icon="\U0001F4BE",
initial_sidebar_state='auto',
... |
#!/usr/bin/env python
import re, glob, json
# this script is intended to take a .txt of raw 650 fields content broken by lines. The data should not have indicators or the quotation marks which may wrap a term if it contains commas and was extracted from a CSV.
###############
# Sample Data #
###############
# $aAfrica... |
from django import forms
import re
class AnalyticsSettingsForm(forms.ModelForm):
class Meta:
model = dashboard_models.DashboardSetting
fields = ['google_analytics', 'google_tag_manager',
'google_optimize', 'google_ads', 'facebook_pixels', 'mailchimp']
widgets = {
... |
from zope.interface import implements
from twisted.python import usage
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from pinky.node.service import NodeService
class Options(usage.Options):
optParameters = [
['port', None, None, 'The port number to listen on.']... |
"""
Handle all things related to CLI functionality.
"""
|
import operator
from typing import Any, Callable
from .base import Matcher
class ComparisonMatcher(Matcher[Any]):
def __init__(self, value: Any, operator_func: Callable[[Any, Any], bool]):
self.value = value
self.operator = operator_func
def match(self, actual: Any) -> bool:
try:
... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
# Register your models here.
from django.contrib import admin
from websiteapp.models import WebSite,WebSiteGroup,UserInfo
admin.site.register(UserInfo)
admin.site.register(WebSiteGroup)
admin.site.register(WebSite) |
#!/usr/bin/env python
"""Test demo 11.3 for chapter 11."""
from operator import add, mul
from functools import partial
add1 = partial(add, 1)
mul100 = partial(mul, 100)
print add1(10)
print mul100(5)
print ""
base_two = partial(int, base=2)
base_two.__doc__ = 'Convert base 2 string to int'
print base_two('10010')
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from iso8601 import parse_date
from pytz import timezone
import urllib
import json
import os
def convert_time(date):
date = datetime.strptime(date, "%d/%m/%Y %H:%M:%S")
return timezone('Europe/Kiev').localize(date).strftime('%... |
# Generated by Django 3.2.11 on 2022-02-05 00:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rolodex', '0026_auto_20211109_1908'),
]
operations = [
migrations.AlterField(
model_name='client',
name='id',
... |
import os
os.system('black . --skip-string-normalization')
os.system('isort . --profile black')
|
"""
@author Huaze Shen
@date 2019-07-16
"""
def is_valid_sudoku(board):
return is_valid_row(board) and is_valid_column(board) and is_valid_sub_box(board)
def is_valid_row(board):
size = len(board)
for i in range(size):
s = set()
for j in range(size):
ch = board[i][j]
... |
from traceback import format_tb
from django.urls.base import reverse
from django.template.loader import get_template
from django.conf import settings
from django.core.mail import send_mail
def send_email_on_failure(task_watcher=None, exception=None, traceback=None):
"""Function to send an email on task success sig... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/12_linkage.ipynb (unless otherwise specified).
__all__ = ['base', 'paramlink2', 'pedprobr', 'pedtools', 'get_allele', 'name_haps', 'get_fam_hap', 'get_fam_geno',
'format_haps_bunch', 'calculate_ped_lod', 'parallel_lods', 'sum_variant_lods']
# Cell
import nump... |
# Generated by Django 2.1 on 2018-09-05 04:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0005_auto_20180831_0522'),
]
operations = [
migrations.CreateModel(
name='Admin',
fields=[
... |
#!/usr/bin/env python
import os
from matplotlib.path import Path
import numpy as np
import pandas as pd
from scipy.interpolate import griddata
from qcore import geo
DATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "zdata")
# constant regions and max bounds for faster processing
POLYGONS = [
(os.... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
# O(n) time | O(n) space - where n is the min depth of binary tree
def minDepth(self, root: Optional[Tr... |
#!/usr/bin/env python
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
from matplotlib import rcParams
from numpy import *
import pickle
import sys,os,string
import sigfig
import EBV
import STANstats
from A_lamb import A_lamb
#import bspline
import bspline2
d0 = 1
rcParams['font.size'] = 1... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018-2019 Linh Pham
# wwdtm is relased under the terms of the Apache License 2.0
"""Testing module for wwdtm.guest"""
import json
import mysql.connector
from wwdtm.guest import info, details, utility
def test_id_exists(guest_id: int,
database_connection: mysq... |
#!/usr/bin/python
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
... |
#! /usr/bin/python3
import sys
import pennylane as qml
from pennylane import numpy as np
def parameter_shift(weights):
"""Compute the gradient of the variational circuit given by the
ansatz function using the parameter-shift rule.
Write your code below between the # QHACK # markers—create a dev... |
# -*- coding: utf-8 -*-
# @Time : 2020/3/18 0018 17:35
# @Author : songzhenxi
# @Email : songzx_2326@163.com
# @File : leetcode1160.py
# @Software: PyCharm
# 给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。
#
# 假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
#
# 注意:每次拼写时,chars 中的每个字母都只能用一次。
#
# ... |
# Generated by Django 3.2.5 on 2021-07-13 16:50
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('shop', '0008_review'),
]
operations = [
migrations.AlterField(
model_name='review',
... |
def number_of_friends():
n_friends = int(input("Enter the number of friends joining (including you): "))
return n_friends
def friend_names(n_friends: int):
names = []
for i in range(n_friends):
name = input(f"Enter the name of the friend number {i+1}: ")
names.append(name)
return n... |
# -*- coding: utf-8 -*-
#pylint: skip-file
import sys
import os
import os.path
import time
from operator import itemgetter
import numpy as np
import cPickle as pickle
from random import shuffle
from transformer.utils import subsequent_mask
class BatchData:
def __init__(self, flist, modules, consts, options):
... |
from PIL import Image
from torchvision import transforms
from torch import Tensor
def image_loader(image_path: str, img_size: tuple = (128, 128)) -> Tensor:
"""
Loading and preprocessing an image
:param image_path: path to image
:param img_size: image size
:return: image format torch.Tensor
""... |
from rest_framework.pagination import PageNumberPagination
class SetPagination(PageNumberPagination):
"""
自定义后端分页处理类,需要在settings中覆盖默认分页处理类(全局)
非全局时,要在需要分页的视图类中指定当前类
"""
# 使用当前类,前端需要传入当前页码page 和 每页的数量 page_size
page_size_query_param = 'page_size' # 设置每页数量
max_page_size = 100 # 设置每页最大数量
... |
"""chemfp.decoders - decode different fingerprint representations into chemfp form
The chemfp fingerprints are stored as byte strings, with the bytes in
least-significant bit order (bit #0 is stored in the first/left-most
byte) and with the bits in most-significant bit order (bit #0 is
stored in the first/right-most b... |
from flask import Blueprint, render_template, request, redirect, url_for, session
from src.routes.warps.wraps import loginRequired, onlyPOST
from src import mysql
medicinesRoutes = Blueprint('medicines', __name__)
@medicinesRoutes.route('/medicines')
@loginRequired
def medicines():
cursor = mysql.get_db().cursor... |
from .activation import *
from .argparser import *
from .causal import *
from .config import *
from .constraint import *
from .context import *
from .module import *
from .property import *
from .receptor import *
from .spike import *
from .state import *
|
import os
from pathlib import Path
import hydra
import pytorch_lightning as pl
from omegaconf import DictConfig, OmegaConf
from pytorch_lightning.callbacks import RichProgressBar
from classy.data.data_modules import ClassyDataModule
from classy.utils.log import get_project_logger
python_logger = get_project_logger(_... |
#!/usr/bin/env python
##############################################################################
# Copyright (c) 2015 Huawei Technologies Co.,Ltd and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompan... |
from rest_framework import viewsets
from ._mixins import (
CreateMixin,
ListMixin,
RetrieveMixin,
DestroyMixin,
UpdateMixin,
FilterMixin
)
from ..models import (
DateTimeField,
NumberField,
TextField,
BooleanField,
ChoicesField,
ImagesField,
FileField,
ItemField
... |
import os
import requests
from metagrok import keys
import logging
logger = logging.getLogger(__name__)
_keys = keys.get()
def send(subject, text, attachments = []):
if _keys is None:
logger.warn('Not sending out email, metagrok.keys module is not set up properly')
return None
files = []
for a in a... |
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from ..segmentation import SimilarityIndex
def test_SimilarityIndex_inputs():
input_map = dict(
ANNContinuousVolume=dict(
argstr='--ANNContinuousVolume %s',
extensions=None,
),
args=dict(argstr='%s', ),
e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.