content stringlengths 5 1.05M |
|---|
import sqlalchemy
from sqlalchemy import Column, Integer, String, Table, create_engine, engine_from_config, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
class Quest(Base):
__tablename__ = 'quest'
id = Column(sqlalchemy.I... |
from django.contrib import admin
# from .models import Dummy
# Register your models here.
# admin.site.register(Dummy) |
class Solution:
def reverseBits(self, n: int) -> int:
res = 0
for _ in range(32):
res = (res<<1) | (n&1)
n>>=1
return res
|
import openaq
import folium
api = openaq.OpenAQ()
COUNTRY_COLORS = {'CH': 'red', 'AT': 'cyan'}
locs = {country: api.locations(country=country, df=True)
for country in COUNTRY_COLORS.keys()}
basemap = folium.Map(location=[47.4308, 11.8728], zoom_start=6)
for country, color in COUNTRY_COLORS.items():... |
from setuptools import setup, find_packages
setup(
name='file_tree_check',
packages=find_packages("src"),
package_dir={"": "src"},
url='https://github.com/btoutee/file_tree_check',
license='LICENSE.txt',
author='Bertrand Toutée',
author_email='bertrand.toutee@gmail.com',
description='Fi... |
from office365.directory.identities.identity_set import IdentitySet
from office365.entity import Entity
from office365.onedrive.listitems.item_reference import ItemReference
class BaseItem(Entity):
"""The baseItem resource is an abstract resource that contains a common set of properties shared among several
o... |
from django import template
from django.db.models import Count
from django.utils.safestring import mark_safe
import markdown
from ..models import Post
register = template.Library()
####
# Register as simple tags
####
# A simple template tag that returns the number of posts published so far.=
@register.simple_tag
d... |
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
import processout
import json
from processout.networking.request import Request
from processout.networking.response import Response
# The content of this file was automatically generated
class ApplePayAlternativeMerc... |
import logging
from datetime import date, datetime, timedelta
from pricehist import exceptions
def fetch(series, source, output, invert: bool, quantize: int, fmt) -> str:
if series.start < source.start():
logging.warning(
f"The start date {series.start} preceeds the {source.name()} "
... |
from django.urls import include, path
urlpatterns = [
path('edtf/', include('edtf.urls', namespace='edtf'))
]
|
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
plt.plot(x, y, linewidth=5.0)
plt.savefig("0.3_line_prop_plot.png")
# usage of setp
x1 = [1, 2, 3, 4]
y1 = [1, 4, 9, 16]
x2 = [1, 2, 3, 4]
y2 = [2, 4, 6, 8]
lines = plt.plot(x1, y1, x2, y2)
# use keyword args
plt.setp(lines[0], color... |
# Ivan Carvalho
# Solution to https://www.urionlinejudge.com.br/judge/problems/view/1816
#!/usr/bin/env/python2.7
# -*- coding : utf -*-
instancia = 1
while True:
ordem = int(raw_input())
if ordem == 0:
break
print "Instancia %d" % instancia
instancia += 1
resposta = []
array = [i for i in 'ABCDEFGHIJKLMNOPQRST... |
i = 0
while i < 5:
print(f'这是第{i}种颜色')
i += 1
|
# coding: UTF-8
"""
Script: sokoban/record
Auteur: girartim
Date: 19/03/2018
"""
import os
import outil
import collection
# Fonctions
def record_jeu(collec, numero):
"""
Extrait le record sur un puzzle donné
:param collec: collection du puzzle à tester
:param numero: numero du puzz... |
class Solution:
def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int:
@lru_cache(None)
def dp(mask: int) -> int:
i = bin(mask).count("1")
if i == len(nums1):
return 0
return min((nums1[i] ^ nums2[j]) + dp(mask | 1 << j)
for j in range(len(nums2)) if not... |
from typing import Union
import weakref
import torch
import syft as sy
from syft.generic.pointers.object_wrapper import ObjectWrapper
from syft.workers.abstract import AbstractWorker
from syft.workers.base import BaseWorker
class TrainConfig:
"""TrainConfig abstraction.
A wrapper object that contains all t... |
#!/usr/bin/env python
# encoding: utf-8
import logging
from modules.vba_gen import VBAGenerator
import re, os
from vbLib import Base64ToBin, CreateBinFile
import base64
VBS_TEMPLATE = \
r"""
<<<VBS>>>
<<<MAIN>>>
"""
class VBSGenerator(VBAGenerator):
""" Module used to generate VBS file from working dir content""... |
from __future__ import absolute_import, division, print_function, unicode_literals
TOM = 'a person'
FOOD = 'apple', 'pear', 'grape', 'raspberry'
|
import wx
import match_sim.cl.default as default
from match_sim.gui.graphics import Colour
from match_sim.gui.template import TemplatePanel, TemplateButton
from match_sim.reporting.training_report import TrainingReport
class TrainingPanel(TemplatePanel):
def __init__(self, parent):
super().__init__(parent)
... |
"""
Generates a Swagger definition for registered endpoints.
Note that:
- Swagger operations and type names use different conventions from the internal definitions
because we want to make usage friendly for code generation (e.g. bravado)
- Marshmallow to JSON Schema conversion is somewhat simplistic. There ar... |
import sys
from datetime import datetime
from datasets import *
import random, pdb, sys
import numpy as np
import tqdm, util
from models import *
model = CPDModel(node_features=(8, 100), edge_features=(1,32), hidden_dim=(16,100))
optimizer = tf.keras.optimizers.Adam()
util.load_checkpoint(model, optimizer, sys.argv[1... |
import os
from os.path import dirname, join, abspath
BASEDIR = abspath(dirname(__file__))
def create_sqlite_uri(db_name):
return "sqlite:///" + join(BASEDIR, db_name)
class Config:
SECRET_KEY = os.environ.get("SECRET_KEY")
SQLALCHEMY_COMMIT_ON_TEARDOWN = False
SQLALCHEMY_RECORD_QUERIES = True
S... |
from mesa import Model
from mesa.time import RandomActivation
from person import Person
from mesa.space import MultiGrid
from mesa.datacollection import DataCollector
import numpy as np
import matplotlib.pyplot as plt
def total_infected(model):
total = 0
for agent in model.schedule.agents:
if agent.inf... |
"""
AIO -- All Model in One
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn.parameter import Parameter
from torch.nn.init import xavier_uniform, xavier_normal, orthogonal
from models.subNets.AlignNets import AlignSubNet
from models.singleTask imp... |
import os
import click
@click.group()
def main():
'''display help '''
@main.command()
def help():
'''open this file to modify'''
print(
'after installing this package using python setup.py develop... '
'(which you must have already done)... '
'please modify the w.py file at:',
... |
from fastapi.middleware.cors import CORSMiddleware
from matplotlib import pyplot as plt
from sklearn.cluster import KMeans
from fastapi import FastAPI
from typing import List
from io import BytesIO
from skimage import io
import seaborn as sns
import numpy as np
import requests
import colorsys
import sys
def clusterin... |
# -*- coding: utf-8 -*-
# https://towardsdatascience.com/build-a-machine-learning-simulation-tool-with-dash-b3f6fd512ad6
# We start with the import of standard ML librairies
import pandas as pd
import numpy as np
from sklearn.datasets import make_regression
from sklearn.ensemble import RandomForestRegressor
# We ad... |
from src.server.http.server import HttpBaseServer
import paths
HttpBaseServer(port=8000, paths=paths.route).serve_forever() |
def client_app(balance: dict, plot: str) -> str:
balance = '<ul>' + "".join([f'<li>{k}: {v}</li>' for k,v in balance.items()]) + '</ul>'
top = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
... |
from mypy.plugin import ClassDefContext
from mypy_django_plugin import helpers
def make_meta_nested_class_inherit_from_any(ctx: ClassDefContext) -> None:
meta_node = helpers.get_nested_meta_node_for_current_class(ctx.cls.info)
if meta_node is None:
return None
meta_node.fallback_to_any = True
|
import itertools
K, M = list(map(int, input().split(' ')))
L = []
for i in range(K):
t = list(map(int, input().split(' ')))
t = t[1:]
t = [x**2 for x in t]
L.append(t)
P = itertools.product(*L)
R = map(lambda x: (sum(x) % M), P)
print(max(R))
|
from typing import Tuple, Union, List, Dict
from .exceptions import DominoError, InvalidPiece, InvalidSide
from .piece import Piece
from .player import ANNOTATOR, Player
from .table import Table
from .domino import Domino
class Movement(Domino):
def __init__(self, piece: Piece, _from: Union[Player, Tabl... |
#coding:utf-8
import re
import requests
import pymysql
import time
class xiciSpider(object):
def __init__(self):
self.req=requests.Session()
self.headers={
'Accept-Encoding':'gzip, deflate, br',
'Accept-Language':'zh-CN,zh;q=0.8',
'Referer':'http://www.xicidaili.c... |
import numpy as np
from sklearn.preprocessing import Normalizer
from imgmani import collapse_image
class Normalize():
def __init__(self):
pass
def normalize(self, msi):
pass
class NormalizeIQ(Normalize):
"""Normalize by image quotient"""
def __init__(self, iqBand=None):
... |
'''
python evaluate.py \
--gt_path ../datasets/nyu_data/test_depth \
--split indoor --eigen_crop \
--min_depth 0.1 --max_depth 10.0 --normalize_depth 10.0 \
--predicted_depth_path ./results/[] \
python evaluate.py \
--gt_path ../datasets/kitti_data/ \
--split eigen --garg_crop \
--min_depth... |
import whois
import datetime
w = whois.whois('salmanually.com')
w.expiration_date # dates converted to datetime object
datetime.datetime(2013, 6, 26, 0, 0)
w.text # the content downloaded from whois server u'\nWhois Server Version 2.0\n\nDomain names in the .com and .net'
print(w) # print values of all found attrib... |
"""
Utilities for using numpy and sklearn with PyTorch
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
def tensor2float(input_):
"""
Convert a one element tensor into float
"""
if isinstance(input_, torch.Tensor):
... |
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs', type='fanout')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
channel.queue_bind(exchange='logs', queue=queue_name)
pri... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 17 16:16:18 2021
@author: qizhe
"""
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
# 整体思路为双指针,一遍扫描就可以了,时间复杂度为O(n)
N = len(needle)
# 空字符返回零
if N == 0:
return 0
result = -1
poin... |
'''
* Copyright (c) 2014, 2015 Entertainment Intelligence Lab, Georgia Institute of Technology.
* Originally developed by Mark Riedl.
* Last edited by Mark Riedl 05/2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You ma... |
# Copyright (c) 2021, ritwik and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
from frappe.utils import getdate
from accounting.accounting.doctype.gl_entry.gl_entry import make_gl_entry
class PaymentEntry(Document):
def before_save(self):
... |
def build_dataset():
# Importing required libraries
import os
import fnmatch
from glob import glob
import shutil
import zipfile
import random
# Using zipfile library to extract the data from the zipped dataset
with zipfile.ZipFile("../Breast-Cancer-Detection/archive.zip", 'r... |
#
# Hubblemon - Yet another general purpose system monitor
#
# Copyright 2015 NAVER Corp.
#
# 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
#
# U... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 4 2020
@Author: The Author
____________________________________________________
Plots to produce:
1. LCC of equipment for each scenario for all the individuals
2, CO2 of equipment for each scenario for all the individuals
3. CO2 vs LCC scatter plot.
4. CO2 vs chiller ... |
# system imports
import json
# 3rd part imports
import requests
# local imports
from connector.connector import Connector
class Client(Connector):
def id_by_ip(self, address):
url = "https://{}/webacs/api/v3/data/Clients.json?ipAddress=\"{}\"".format(self.cpi_ipv4_address, address)
result = s... |
#!/usr/bin/python
#"usage: 3piece_read_split.py Input_file First_piece_size(bp) Last_piece_size(bp) upstream_to_trim(bp) downstream_to_trim(bp)"
import gzip
import sys
fn1=sys.argv[1]
if 'gz' in fn1:
dfh1=gzip.open(fn1,'r')
if 'gz' not in fn1:
dfh1=open(fn1,'r')
if sys.version_info[0]==3:
ID1=str(dfh1.read... |
from . responsive_styles import *
|
# -*- coding: utf-8 -*-
from django.db.models import Prefetch
from ralph.api import RalphAPIViewSet
from ralph.api.utils import PolymorphicViewSetMixin
from ralph.assets import models
from ralph.assets.api import serializers
from ralph.licences.api import BaseObjectLicenceViewSet
from ralph.licences.models import Base... |
# Generated by Django 3.1.7 on 2021-04-08 13:44
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Message',
fields=[
('id', models.AutoField(... |
from stash.core.modules.base import Module
import collections
class Algorithm(Module):
__group__ = 'algorithm'
@property
def archive(self):
return self.stash.archive
@property
def cache(self):
return self.stash.cache
def compact(self, force=False):
raise NotImplemen... |
# Copyright (c) 2013, Element Labs and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
def execute(filters=None):
sqlq = """select
a.modified_by,
SUM(a.coins_expected),
SUM(b.coin_count),
SUM(b.error),
COUNT(a.modified_by)
from `tabCol... |
from .YX import YX, userInterfaceShell
from .eMall import Item, SuperCategory, Category, EMall
name = 'crazybee'
all = ['YX', 'userInterfaceShell', 'Item', 'SuperCategory', 'Category', 'EMall'] |
# SPDX-FileCopyrightText: 2020 Hlib Babii <hlibbabii@gmail.com>
#
# SPDX-License-Identifier: Apache-2.0
from typing import List, Tuple, Set, Optional
from codeprep.preprocess.metadata import PreprocessingMetadata
class ParsedToken(object):
def wrap_in_metadata_for_full_word(self, tokens: List[str], non_proc: Op... |
from baseball.enums.PlayerPositionEnum import PlayerPositionEnum
class LineUp:
def __init__(self):
pass |
# Env that models a 1D corridor (you can move left or right)
# Goal is to get to the end (i.e. move right [length] number of times)
import gym
class CorridorEnv(gym.Env):
metadata = {"render.modes": ["human"]}
# Check [env_config] for corridor length, default to 10
def __init__(self, env_config=None):
... |
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# 풀이 1 (coins의 개수가 커질 수록 매우 비효율적일 듯)
from itertools import combinations
def solution(coins):
result = set()
for i in range(1, len(coins)):
for comb in combinations(coins, i):
result.add(sum(comb))
return min(set(range(1, max(result) + 2)) - result)
# 풀이 2 (모든 금액들의 조... |
#!/usr/bin/env python
import aselite
import numpy as np
from sys import argv, exit
if len(argv) < 3 or '-h' in argv:
print "usage: xyz2con.py FILENAME BOXSIZE\n"
exit(0)
filename = argv[1]
atoms = aselite.read_xyz(filename)
atoms.positions -= np.min(atoms.positions)
a = float(argv[2])
atoms.set_cell((a,a... |
import numpy as np
from scipy import constants
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib as mpl
import meep
import meep_ext
import pinboard
job = pinboard.pinboard()
nm = 1e-9
um = 1e-6
### geometry
radius = 75*nm
gold = meep_ext.material.Au()
gold = meep.Medium(index=... |
import os
import vtk, qt, ctk, slicer, logging
#
# Abstract class of python scripted segment editor effects
#
class AbstractScriptedSegmentEditorEffect():
""" Abstract scripted segment editor effects for effects implemented in python
USAGE:
1. Instantiation and registration
Instantiate segment ... |
# -*- coding: utf-8 -*-
"""Script de consola para Pyrobo."""
import sys
import click
from pyrobo.pyrobo import hablame, cuentame
@click.command()
@click.option('--pos', default=None, type=int,
help='Número de la frase deseada.')
@click.option('--culto', default=False, type=bool,
help='Mos... |
import requests
from bs4 import BeautifulSoup
from rssitem import RssItem
class RssReader:
"""The class handles the acquisition of the posts from the RSS feed url"""
def __init__(self, feed_url):
self._feed_url = feed_url
def get_data(self):
"""Getting the RSS feed xml from the given url... |
import json
def test_priorities_success(client, valid_token):
headers = {
'content-type': 'application/json',
'token': valid_token
}
response = client.get('/api/priorities', headers=headers)
response.status_code == 200
def test_priorities_fail_no_token(client):
headers = {
... |
import asyncio
import websockets
import subprocess
async def time(websocket, path):
script = await websocket.recv()
with subprocess.Popen(script.split(' '),
stdout=subprocess.PIPE,
bufsize=1,
universal_newlines=True) as process:
... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("Demo")
process.MessageLogger = cms.Service("MessageLogger")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(20)
)
process.source = cms.Source("EmptySource",
numberEventsInRun = cms.untracked.uint32(3)
)
#stuck something int... |
code = {"台北市":{"中正區": 100, "大同區": 103, "中山區": 104, "松山區": 105, "大安區": 106, "萬華區": 108, "信義區": 110, "士林區": 111, "北投區": 112, "內湖區": 114, "南港區": 115, "文山區": 116}, "基隆市":{"仁愛區": 200, "信義區": 201, "中正區": 202, "中山區": 203, "安樂區": 204, "暖暖區": 205, "七堵區": 206},"新北市": {"萬里區": 207, "金山區": 208, "板橋區": 220, "汐止區": 221, "深坑區": 222, "... |
from fractions import gcd
n = input()
mx = 0
if n == 1:
print 1
elif n == 2:
print 2
else:
if n%2 == 1:
print n*(n-1)*(n-2)
else:
if n%3 == 0:
print (n-1)*(n-2)*(n-3)
else:
print n*(n-1)*(n-3)
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import ttk
import tkFileDialog
from Local import Local
from resource_path import resource_path
class EventTable(object):
def __init__(self, root):
self.tree = tree = ttk.Treeview(root, columns = ('event', 'val'))
tree.heading('#0', text = Local('Date'... |
# Setup Python ----------------------------------------------- #
from dijikstra import dijikstra
from Astar import AStar
from mst import kruskal
from fft import fft
from utils import *
import pygame, sys
# Setup pygame/window ---------------------------------------- #
mainClock = pygame.time.Clock()
from pygame.loca... |
"""
A simple console-based ftp client for taXaminer datasets
"""
import ftplib
import os
from ftputil import FTPHost
from configparser import ConfigParser
def main():
"""
Main program loop. Requests user input for host, login credentials and
dataset to download
:return:
"""
# greetings
pri... |
"""
This code was generated by Codezu.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
"""
from mozurestsdk.mozuclient import default as default_client
from mozurestsdk.mozuurl import MozuUrl;
from mozurestsdk.urllocation import UrlLocation
from mozure... |
# -*- coding: utf-8 -*-
#求两个点之间的欧几里得距离
#输入a和b是含有点坐标的列表
from math import sqrt
def EucliDis(a,b):
return sqrt(sum([pow(a[i]-b[i],2) for i in range(len(a))]))
#求两个轮廓线之间的Hausdorff Distance
#对于A中的每一个点,求该点与B中所有点的欧几里得距离,取最小值
#然后在A中的所有点中,取最大值
def HausDis(a,b):
t1=[]
for i in range(len(a)):
t2=[]
... |
def listToString(s):
str1 = ""
for ele in s:
str1 += ele
return str1
s = ['wow', 'cool', 'damm']
print(listToString(s)) |
import os
os.system('copy .\\MipiRffeAnalyzer\\vs2013\\Release\\x64\\MipiRffeAnalyzer.dll .\\')
os.system('git status')
input("Press ENTER to continue")
os.system("git add *")
note = input('Enter the note:\n>')
os.system('git commit -m "%s"' % note)
os.system("git pull")
os.system("git push origin main")
input() |
from v1.self_configurations.helpers.self_configuration import get_self_configuration
from v1.tasks.confirmation_block_queue import handle_bank_confirmation_services
def test_seconds_purchased(confirmation_validator_configuration):
"""Test that the correct amount of time is purchased"""
self_configuration = ge... |
import os
import pytest
import boto.dynamodb2
from boto.dynamodb2.table import Table
from boto.dynamodb2.fields import HashKey
from boto.dynamodb2.fields import GlobalAllIndex
from vinyldns_context import VinylDNSTestContext
def pytest_addoption(parser):
"""
Adds additional options that we can parse when we r... |
#Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 para viagens mais longas.
km = float(input('Qual a distância da viagem? '))
if km <200:
preco = 0.50
else:
preco = 0.45
print(f'Você esta próximo de começ... |
"""
Copyright (c) 2014-2017 Wind River Systems, Inc.
SPDX-License-Identifier: Apache-2.0
"""
from cgcs_patch.patch_functions import LOG
PATCHMSG_UNKNOWN = 0
PATCHMSG_HELLO = 1
PATCHMSG_HELLO_ACK = 2
PATCHMSG_SYNC_REQ = 3
PATCHMSG_SYNC_COMPLETE = 4
PATCHMSG_HELLO_AGENT = 5
PATCHMSG_HELLO_AGENT_ACK = 6
PATCHMSG_QUERY... |
from abaqusConstants import *
class BCDisplayOptions:
"""The BCDisplayOptions object stores settings that specify how assemblies are to be
displayed in a particular viewport when
session.viewports[name].assemblyDisplay.bcs=ON
The BCDisplayOptions object has no constructor. When you create a new view... |
import itertools
import logging
import pprint
from django.conf import settings
from django.contrib import messages
from django.contrib.sites.shortcuts import get_current_site
from django.core.urlresolvers import reverse
from django.db.models import Count, Sum, Q
from django.forms import formset_factory
from django.htt... |
# Generated by Django 2.2.12 on 2020-04-23 19:28
from django.db import migrations
import djongo.models.fields
import project.models
class Migration(migrations.Migration):
dependencies = [
("project", "0003_project_name"),
]
operations = [
migrations.RemoveField(model_name="project", na... |
#-*- coding:utf-8 -*-
__version__ = '0.0.8'
__maintainer__ = 'Benjamin Fuchs 12.11.2019'
__email__ = 'Benjamin.Fuchs@dlr.de'
__birthdate__ = '26.07.2019'
__status__ = 'dev' # options are: dev, test, prod
# CURRENTLY NOT USED IN VENCOPY
import functools
import time
import inspect
import logging.handlers
logger = lo... |
x = input("enter numbers with space\n").split()
a=0
p=input("enter searching No\n")
for i in range (len(x)):
if x[i]==p:
a+=1
if a==1:
print("\npresent")
else:
print("\nnot present")
|
import torch
from torch._C import device
x = torch.tensor([[1., -1.], [1., 1.]]).cuda().requires_grad_()
out = x.pow(2).sum()
out.backward()
print(x.grad)
torch.cuda.empty_cache()
x = torch.tensor([[2., -1.], [1., 1.]]).cuda().requires_grad_()
print(x)
print(x.grad)
input(0)
|
from marshmallow import Schema
from marshmallow.fields import Bool, String
from server.models.issue import IssueStatus
from server.models.util import BikeType
from server.serializer import BytesField, EnumField
class PaymentSourceSchema(Schema):
token = String(required=True)
class MasterKeySchema(Schema):
... |
import numpy as np
import cv2
from pykinect_azure.k4abt import _k4abt
from pykinect_azure.k4abt.body import Body
from pykinect_azure.k4abt.body2d import Body2d
from pykinect_azure.k4abt._k4abtTypes import k4abt_body_t, body_colors
from pykinect_azure.k4a import Image, Capture, Transformation
from pykinect_azure.k4a._... |
# -*- coding: utf-8 -*-
from tornado.web import url
from main.handlers import MainHandler
from auth.handlers import LoginHandler, LogoutHandler, RegHandler
from wschat.handlers import ChatHandler, WebSocketHandler
urls = [
url(r"/", MainHandler, name="main"),
url(r"/chat", ChatHandler, name="chat"),
url(... |
import pymongo
client = pymongo.MongoClient("localhost", 27017)
db = client.nashenas_telegram_bot
|
import re
import logging
import warnings
import django
from django.db import IntegrityError, transaction
from django.utils import timezone
from django.utils.encoding import smart_text
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
from bims.models import... |
__author__ = 'swebb'
|
#!/usr/bin/env python
from distutils.core import setup
setup(name='csxbot',
version='0.3',
description='CSX Crawler (a crawler extension and a django project)',
author='Shuyi Zheng',
author_email='zhengshuyi@gmail.com',
packages=['csxcrawler', 'citeseerx_crawl', 'citeseerx_crawl.main_cra... |
from rest_framework import serializers
from core.models import UserModel
from core.serializers.common import UserBlacklistSerializer, AuthorSubscriptionSerializer
from core.utils import build_full_url
from core.validators import RequiredValidator
class UserDetailsSerializer(serializers.ModelSerializer):
avatar_link... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
c.durr, a.durr - 2017-2019
Solve the consecutive all ones column problem using PQ-trees
In short, a PQ-tree represents sets of total orders over a ground set. The
leafs are the values of the ground set. Inner nodes are of type P or Q. P
means all pe... |
import logging
from urllib.parse import urlparse
from django.conf import settings
from django.http import Http404, HttpResponsePermanentRedirect, HttpResponseRedirect
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect
import re
from wagtail.contrib.redirects.middleware import g... |
from django.contrib.auth.models import User, Group
from rest_framework_jwt.utils import jwt_payload_handler as default_jwt_payload_handler
def jwt_payload_handler(user: User):
payload = default_jwt_payload_handler(user)
payload['user_id'] = user.id
groups = [g.name for g in user.groups.all()]
payload[... |
from enum import Enum
class MerossEventType(Enum):
# Fired when the MQTT client connects/disconnects to the MQTT broker
CLIENT_CONNECTION = 10
DEVICE_ONLINE_STATUS = 100
DEVICE_SWITCH_STATUS = 1000
DEVICE_BULB_SWITCH_STATE = 2000
DEVICE_BULB_STATE = 2001
GARAGE_DOOR_STATUS = 3000
DEVIC... |
# Copyright 2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file accom... |
from griddly import GymWrapper, gd
import numpy as np
def create_env():
env = GymWrapper(
yaml_file="Single-Player/Mini-Grid/minigrid-spiders.yaml",
global_observer_type=gd.ObserverType.VECTOR,
player_observer_type=gd.ObserverType.VECTOR,
level=3,
)
env.reset()
return ... |
import sklearn
from classifiers.classification_model import ClassificationModel
class DecisionTree(ClassificationModel):
def __init__(self, training_samples, test_samples, training_labels, test_labels):
super().__init__(training_samples, test_samples, training_labels, test_labels)
self.in... |
from django.forms import TextInput
class CalendarWidget(TextInput):
template_name = 'widgets/CalendarWidget.html'
class Media:
css = {
'all': (
'js/fullcalendar-4.2.0/packages/core/main.css',
'js/fullcalendar-4.2.0/packages/bootstrap/main.css',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.