text stringlengths 38 1.54M |
|---|
from string import ascii_letters, digits
from django.contrib import admin
from django.db import transaction
from django.db.models import Count
from django.db.utils import IntegrityError
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils.crypto import get_random_string
from d... |
class A:
def __init__(self):
print("A.__init__")
class B(A):
def __init__(self):
print("B.__init__")
print(super().__init__)
super().__init__()
class C(A):
def __init__(self):
print("C.__init__")
print(super().__init__)
super().__init__()
class... |
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
# write code here
import copy
if root == None:
... |
from five import grok
from plone.directives import dexterity, form
from dkiscm.jobmatrix.content.jobgroup import IJobGroup
grok.templatedir('templates')
class Index(dexterity.DisplayForm):
grok.context(IJobGroup)
grok.require('zope2.View')
grok.template('jobgroup_view')
grok.name('view')
|
#!/usr/bin/python3
# RA, 2018-10-26
## ================== IMPORTS :
import os
import sklearn.neighbors
import geopy.distance
import numpy as np
import builtins
import json
import inspect
import pickle
import time
import urllib.request, urllib.parse
import base64
import re
import datetime as dt
from collections impor... |
# -*- python -*-
load("//tools/skylark:py.bzl", "py_binary")
load("//tools/skylark:drake_py.bzl", "drake_py_unittest")
load("//tools/lint:lint.bzl", "add_lint_tests")
package(default_visibility = ["//visibility:public"])
# Used by :python_env.bzl.
config_setting(
name = "linux",
values = {"cpu": "k8"},
)
ex... |
#
# $Id$
#
"""module to do div, grad, curl (but not 'all that') for pencil-code data.
"""
import numpy as N
from .der import *
from sys import exit
def div(f,dx,dy,dz):
"""
take divervenge of pencil code vector array
"""
if (f.ndim != 4):
print("div: must have vector 4-D array f[mvar,mz,my,mx]... |
import codecs
import re
import sys
from collections import OrderedDict
from fnmatch import fnmatch
from invisibleroads_macros.configuration import (
RawCaseSensitiveConfigParser, format_settings, load_relative_settings,
load_settings, make_absolute_paths, make_relative_paths, save_settings)
from invisibleroads_... |
from django.contrib.auth import get_user_model
from django.shortcuts import render, get_object_or_404
from .models import Customer
from .models import EnergyData
from rest_framework import status
from .serializer import NodeSerializer
from django.contrib.humanize.templatetags.humanize import naturaltime
from django.vie... |
from operator import methodcaller
from readers import FileReader
COM = "COM"
YOU = "YOU"
SAN = "SAN"
def main():
raw_orbits = list(map(methodcaller("split", ")"), map(str.strip, FileReader.read_input_as_list())))
orbits = {o[1]: o[0] for o in raw_orbits}
you_planets = set_of_planets_to_home(YOU, orbits... |
from peachpy.x86_64 import *
from peachpy import *
from peachpy.c.types import *
# =================================================
# ADDITION
# =================================================
avx_vector_add_map = {
Yep8s : VPADDB,
Yep8u : VPADDB,
Yep16s: VPADDW,
Yep16u: VPADDW,
Yep32s: VPADDD,
... |
# author: Hendrik Werner s4549775
# author: Constantin Blach s4329872
from datetime import datetime
from random import randint
import socket
from typing import Tuple
from bTCP.exceptions import ChecksumMismatch
from bTCP.message import BTCPMessage, MessageFactory
from bTCP.state_machine import State, StateMachine
c... |
#!/usr/bin/env python3
def parse_note(string, note_search, note_dict):
note = get_note(string,note_search,note_dict)
return(note, get_chord(string, note).lower().replace(" ", ""))
def get_note(string, note_search, note_dict):
for n in note_search:
if n == string[:len(n)].capitalize():
... |
##################################################################
#----------------- Initial conditions for modRSW -----------------
# (T. Kent: amttk@leeds.ac.uk)
##################################################################
'''
Functions generate different initial conditions described below f... |
import time
import numpy as np
import pandas as pd
import xgboost as xgb
import shap
import itertools
import scipy
#_________________________________
# run transshipment_trips.sql and save as transhipment_trips.csv
encounter = pd.read_csv('transshipment_trips.csv')
# run transshipment_loitering.sql and save as trans... |
s=input()
d=dict()
for i in s:
if i in d:
d[i]+=1
else:
d[i]=1
for i in d:
if (d[i]==1):
print (i)
break
|
# -*- coding: utf-8 -*-
#
# __init__.py
# ========================
# A low-entropy nucleic/amino acid
# sequencing masking library.
# ========================
#
# Copyright 2017 Joseph Szymborski
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compli... |
# coding: utf-8
from __future__ import absolute_import
from google.appengine.ext import ndb
from flask.ext import restful
import flask
from api import helpers
import auth
import model
import util
from main import api_v1
@api_v1.resource('/project/', endpoint='api.project.list')
class ProjectListAPI(restful.Resour... |
#encoding=utf-8
from gensim.models import word2vec
if __name__ == '__main__':
sentences=word2vec.Text8Corpus(u'data/words.txt')
model=word2vec.Word2Vec(sentences, size=50)
for i in model.most_similar(u"北京"):
print(i[0],i[1])
|
# 1. test case 수를 입력받는다.
test_case = int(input())
# 2. 각 테스트 케이스가 공백문자로 구분되어 입력된다.
for i in range(test_case):
nums = map(int, input().split())
print(f'#{i+1} {max(nums)}') |
#!/usr/bin/python3
from main import *
from matplotlib import pyplot as plt
import numpy as np
import argparse
def rainbow_colors(n):
colormap = plt.cm.gist_rainbow
return [colormap(i) for i in np.linspace(0, 1, n)]
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--fil... |
class Human():
'''인간'''
def __init__(self, name,weight):
"""초기화 함수"""
print("__init__실행")
self.name=name
self.weight= weight
def __str__(self):
"""문자열과 함수"""
def eat(self):
person.weight += 0.1
print("{}가 먹어서{}kg이 되었습니다".format(person.name,person... |
import threading
from .cli import Console
from .concurrent import AtomicMemoryReference
from .concurrent import MemoryUpdater
class MemvisController(object):
def __init__(self, pid, width=26, height=10, start_address=None, use_ptrace=True, convert_ascii=True):
self.pid = pid
self.memory_reference ... |
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table as dt
from dash.dependencies import Input,Output,State
import pandas as pd
import sqlalchemy
import random
from server import app
from global_var import label_table,mean_table,db_0_50,get_source_show_table,get_show_t... |
# Generated by Django 3.1 on 2020-08-09 16:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('comments', '0005_auto_20200424_1144'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='metadata',
... |
import keras
import keras.backend as K
from keras.models import Model
from keras.layers import (Input, Convolution2D, Activation, BatchNormalization,
merge, GlobalAveragePooling2D, Dense, Dropout)
from keras.regularizers import l2
from rme.datasets import cifar10, cifar100, svhn, mnist, prepro... |
def on_enter(event_data):
""" """
pocs = event_data.model
pocs.next_state = 'parked'
pocs.say("Parking Huntsman.")
# Clear any current observation
pocs.observatory.current_observation = None
pocs.observatory.close_dome()
pocs.say("I'm takin' it on home and then parking.")
pocs.obse... |
import cv2
import urllib
import sys, os
import xml.etree.ElementTree as ET
pwd = os.path.abspath(os.path.dirname(__file__))
image_dir_name = pwd + '/../images/'
tmp_folder = pwd + '/../tmp/'
if __name__ == '__main__':
for x in os.walk(pwd):
if (x[0] != pwd):
label = x[0].split('/')[-1]
... |
# 10845_큐.py
import sys
input = sys.stdin.readline
n = int(input())
q = []
for i in range(n):
cmd = list(map(str, input().split()))
if cmd[0] == 'push':
q.append(cmd[1])
elif cmd[0] == 'front':
if q:
print(q[0])
else:
print(-1)
elif cmd[0] == 'back':
... |
from flask import Flask, request
import json
import uuid
from util import Address
app = Flask(__name__)
addresses = set()
@app.route("/allocate", methods=["POST"])
def allocate():
ip = request.remote_addr
port = request.form.get("port")
addresses.add((ip, port))
return json.dumps({
"addres... |
# # lua bindings shootout
# The MIT License (MIT)
#
# Copyright � 2018 ThePhD
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the ri... |
"""data process tools"""
from __future__ import annotations
import csv
from typing import List, Literal
from src.schema import InputExample
class DataProcessor(object):
"""Base class for data converters for sequence classification data sets."""
def get_train_examples(self, data_dir):
"""Gets a colle... |
import cv2
import numpy
import numpy as np
import pywt
import math
import scipy
import matplotlib.pyplot as plt
import os
import bisect
import GaussianMixtureClassifier
import CrossCorrelation
from xlwt import Workbook
class Localize:
def __init__(self):
self.CorrelationValues = []
def __init__(self,... |
#!/usr/bin/env python3
/*
* Copyright (c) 2015 Alex Richardson
* All rights reserved.
*
* This software was developed by SRI International and the University of
* Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
* ("CTSRD"), as part of the DARPA CRASH research programme.
*
* This softwa... |
# Generated by Django 2.2.5 on 2019-11-12 04:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cuestionario', '0003_auto_20191028_2010'),
]
operations = [
migrations.CreateModel(
name='Vacuna',
fields=[
... |
#!/usr/bin/env python
import os
import path
import platform
import subprocess
import sys
nuget_base = None
def find_tool(package, path='tools', platform_path=None):
global nuget_base
if nuget_base is None:
if 'NUGET_PACKAGES_BASE' in os.environ:
nuget_base = os.environ['NUGET_PACKAGES_BASE']
if n... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys
import PartituraToROM
import ROMtoVHDL
import ReadWriteFiles
def getVhdl():
"""
S'encarrega de crear un directori amb els fitxers necessàris a dins. Si ja hi és fa les conversions Partitura-ROM-VHDL
"""
fol= ReadWriteFiles.createUseFolder()
... |
# mnist.py
#
# Author : James Mnatzaganian
# Contact : http://techtorials.me
# Organization : NanoComputing Research Lab - Rochester Institute of
# Technology
# Website : https://www.rit.edu/kgcoe/nanolab/
# Date Created : 10/13/15
#
# Description : Testing SP with MNIST.
# Python Version... |
key = [[0, 0, 0], [1, 0, 0], [0, 1, 1]]
lock = [[1, 1, 1], [1, 1, 0], [1, 0, 1]]
M = 3
check = []
check_rot = []
for y in range(M):
for x in range(M):
if key[y][x] == 1:
check.append((y, x))
N = 3
target = []
for y in range(N):
for x in range(N):
if lock[y][x] == 0:
t... |
escala = input("qual escala? (C/F) ")
vt = float(input("valor da temperatura: "))
if (escala.upper() == "F" ):
c = (5*(vt-32)) / 9
print(round(c, 2))
else:
f = (vt*9/5) + 32
print(round(f, 2)) |
#!/usr/bin/env python
import numpy as np
from rosplane_msgs.msg import State
from rosplane_msgs.msg import Controller_Commands
from rosflight_msgs.msg import Command
from pdb import set_trace as pause
import yaml
import rospy
class autopilot():
def __init__(self):
# set up timing variables
self.... |
#!/usr/bin/env python
# coding: utf-8
# In[11]:
import matplotlib.pyplot as plt
import numpy as np
import re
if __name__=="__main__":
address = input('address: ')
filename = input('txt file name: ')
k = input('K:')
data = input('Test data:')
d = np.loadtxt(address+filename)
X = d[:,0... |
from ..models import Spell
from ..serializers import SpellSerializer, SpellLocalSerializer
from ._dofus_viewset import DofusViewSet
class SpellViewSet(DofusViewSet):
model_class = Spell
default_serializer = SpellSerializer
local_serializer = SpellLocalSerializer
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author = 'wyx'
@time = 2019-04-08 21:28
@annotation = ''
"""
import cv2 as cv
import numpy as np
import util
"""
BGR和灰度图的转换使用 cv.COLOR_BGR2GRAY
BGR和HSV的转换使用 cv.COLOR_BGR2HSV
H表示色彩/色度,取值范围 [0,179]
S表示饱和度,取值范围 [0,255]
V表示亮度,取值范围 [0,255]
"""
img = util.load_img('img/... |
def rmv_b(country): # Permet de supprimer le b' qui ce met souvent en general avant le nom du pays, ceci a un rapport avec le type de la variables qui serait un byte ?
return country.replace("b'", "")
def print_result():
f = open("result_per_years.txt", "w")
f.write("country, population, percent, suic... |
# clize -- A command-line argument parser for Python
# Copyright (C) 2011-2015 by Yann Kaiser <kaiser.yann@gmail.com>
# See COPYING for details.
from sigtools import support
from clize import parser, errors, Parameter
from clize.extra import parameters
from clize.tests import util
@util.testfunc
def check_repr(self... |
##################################################
# Import modules
import random
import torch.optim.lr_scheduler
import matplotlib.pyplot as plt
import data
import metrics
import seq2seq
import train
##################################################
# Functions
def print_raw_sentences(name_list, raw_sentences_l... |
import random
from CybORG.Shared.Actions import DiscoverRemoteSystems, DiscoverNetworkServices, ExploitRemoteService, PrivilegeEscalate, Impact
class HeuristicRed():
def __init__(self, session=0):
self.parameters = {
'session':session,
'agent':'Red',
}
... |
"""Testing the diverses algorithms to shuffler."""
from collections import defaultdict
from random import randrange
def test_shuffler(shuffler, deck='abcd', n=10000):
counts = defaultdict(int)
for _ in xrange(n):
input = list(deck)
shuffler(input)
counts["".join(input)] += 1
e = n ... |
import pandas as pd
import numpy as np
from sklearn.metrics import precision_score
from BAYES import GAUSSIAN,N_GAUSSIAN
import matplotlib.pyplot as plt
from MySelect import SelectByChi2
n=3000
p=0.7
R=np.zeros(20)
for i in range(100):
read_data = pd.read_csv('E:/PY/voice/voice.csv')
data =... |
def main():
''' Evaluate the Laplace equation finite sum solution '''
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
n_tot = 51 # Number of terms to use in sum
n = np.arange(1, n_tot+1, 2) # Odd-term... |
from j.osh import *
import pandas as pd
from PIL import Image
from random import shuffle
from random import randint
import numpy
import uuid
def load_csv():
"""
Loads the CSV file for reading coordinates.
"""
return pd.read_csv('coords.csv')
def load_img(filename):
"""
Loads an Image with PIL for a given filena... |
import DataBaseHandler
import ModelHandler
import time
from sklearn.linear_model import LinearRegression
model = LinearRegression()
sys_samples = DataBaseHandler.get_samples(type="systolicBloodPressure")
x_train, y_train = ModelHandler.get_samples_to_nparray(sys_samples)
ModelHandler.train_model(model, x_train, y_tr... |
#!/usr/bin/env python2
# coding=utf-8
from __future__ import print_function
import json
import requests
from config import global_config
from bddown_core import Pan, GetFilenameError
from util import logger
def export(links):
for link in links:
pan = Pan(link)
count = 1
while count != 0:... |
import unittest
from simplecache import SimpleCache
from unittest import TestCase
class BasicTests(TestCase):
def test_basic_functionality(self):
sc = SimpleCache(max_items=3)
sc[1] = 'a'
sc[2] = 'b'
sc[3] = 'c'
self.assertEqual(sc[1], 'a')
self.assertEqual(sc[2],... |
# coding=utf-8
'''
Basic Network Library.
'''
import logging
import os.path
import sys
import urllib
import urllib2
import StringIO
import gzip
logger = logging.getLogger('listenone.' + __name__)
########################################
# network
########################################
def chunk_report(bytes_so_f... |
# This is a sample Python script.
# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
from mechdatas import resources, MENU, coins, commands
alive = True
credit = 0.0
def print_report():
print(f"Water: {resources[... |
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'androidforensics.views.home', name='home'),
#url(r'^apk/', include('apk.urls')),
url(r'^$'... |
"""
利用Grabcut图像分割进行背景替换
"""
import cv2 as cv
import numpy as np
src = cv.imread("../images/master.jpg")
h, w = src.shape[:2]
background = cv.imread("images/land.jpg")
background = cv.resize(background, (w, h))
cv.imshow("input", src)
cv.imshow("background", background)
# 分割,得到mask区域
h, w, ch = src.sha... |
#!/usr/bin/env python3
from collections import namedtuple
Instruction = namedtuple("Instruction", ["opcode", "value"])
OPCODES = {
"acc": lambda pc, acc, value: (pc + 1, acc + value),
"jmp": lambda pc, acc, value: (pc + value, acc),
"nop": lambda pc, acc, value: (pc + 1, acc)
}
def parse_instructions(ra... |
import PIL
from PIL import Image
import os
mywidth = 2000
source_dir ='C:/Users/admin/Desktop/image'
destination_dir ='C:/Users/admin/Desktop/image1'
def resize_pic(old_pic,new_pic):
img=Image.open(old_pic)
wpercent = (mywidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent))... |
import ctypes
import unittest
lib = ctypes.CDLL(".libs/topology_cyclecloud.so")
class Test(unittest.TestCase):
def test_basic(self):
with open("test.csv", "w") as fw:
fw.write("execute,pg1,ip-0A000000\r\n")
fw.write("execute,pg0,ip-0A000001\n")
fw.write("execute,pg0,i... |
class Theater:
"""Holds all the information about a specific theater."""
def __init__(self, name):
self.name = name
self.movietimes = [] # <-- Now this is MovieTime objects
class Movie:
"""Holds all the information about a specific movie."""
def __init__(self, name, duration, genre):
... |
"""
============================
Author:柠檬班-木森
Time:2020/3/4 15:13
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
# 作业参考答案
"""
1、完成上课手机类继承的代码
2、有一组数据,如下格式:
{'case_id': 1, 'method': 'post', 'url': '/member/login', 'data': '123', 'actual': '不通过','excepted': '通过'},
定义一个如下的类,请通过setatt... |
import json
from predict import get_result, get_model
from flask import request, Response
class Server:
model = None
def set_model(self):
self.model = get_model()
def server_running(self):
return 'Server is running...'
def predict(self):
incoming = request.get_json()
filename = incoming['fi... |
from song_etl import song_etl
from log_etl import log_etl
def main():
song_etl()
log_etl()
if __name__ == '__main__':
main()
|
# Generated by Django 3.0.3 on 2020-03-13 07:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('eadmin', '0003_auto_20200225_0400'),
]
operations = [
migrations.AlterField(
model_name='user',
name='role',
... |
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.contrib.auth.models import User, Group
from .models import Project
from .models import Document
from .models import Sheet
from .models import Style
from .models import Task
from .models import Member
from .models import S... |
#!/usr/bin/env python
import sys
import base64
import time
import hashlib
import binascii
import re
class Authenticator(object):
"""Authenticator class which generates unique one time use password."""
def __init__(self, secret: str):
"""Creates a new Authenticator instance.
Args:
s... |
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
import seaborn as sns; sns.set()
from sklearn.datasets.samples_generator import make_blobs
X,y = make_blobs(n_samples=100, centers =2, random_state=0, cluster_std=0.50)
plt.scatter(X[:,0], X[:,1], c=y, s=50, cmap='summer');
#plt.show()
xfit... |
"""
Interactive simulation for Monte Hall problem
"""
import random
import simplegui
# global constants
CANVAS_WIDTH = 540
CANVAS_HEIGHT = 180
CONTROL_WIDTH = 100
CENTER_VERT = 0.3
CENTER_HORIZ = 0.8
MIN_DOORS = 3
MAX_DOORS = 10
SELECT = 0
CHOOSE = 1
SHOW = 2
class MontyHallGUI:
"""
... |
from selenium import webdriver
browser = webdriver.Chrome('./chromedriver')
browser.get('http://www.google.com')
searchBar = browser.find_element_by_xpath(
'//*[@id="tsf"]/div[2]/div/div[1]/div/div[1]/input')
searchBar.send_keys('weather')
|
from .card import Card
from .cardset import CardSet, Hand, Trick
from .deck import CardStack, Deck
from .trump import NonTrump, Trump |
import yaml
import os
### update apikey value
with open('scrapinghub.yml', 'r') as f:
d = yaml.load(f.read(), Loader=yaml.FullLoader)
d['apikey'] = os.environ['APIKEY']
### update config to file
with open('scrapinghub.yml', 'w') as f:
yaml.dump(d, f, default_flow_style=False)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... |
import yaml
from pathlib import Path
path = Path('.')
for userDataPath in path.iterdir():
if (userDataPath.suffix == '.yml'):
with userDataPath.open() as oldData:
dataMap = yaml.load(oldData)
dataMap.pop('lastlocation', None)
dataMap.pop('uuid', None)
newData = open(user... |
import urllib.request
import hashlib
import random
PREFIX_LIST = [
186, 158, 135, 159,
136, 150, 137, 138,
187, 151, 182, 152,
139, 183, 188, 134,
185, 189, 180, 157,
155, 156, 131, 132,
133, 130, 181, 176,
177, 153, 184, 178,
173, 147, 175, 199,
166, 170, 198, 171,
191, 145... |
#
# Kirk Fay
# Artificial Intelligence
#
import numpy as np
import matplotlib.pyplot as plt
import neurolab as nl
text = np.loadtxt('perceptron_data.txt')
# Separate datapoints and labels
data = text[:, :2]
labels = text[:, 2].reshape((text.shape[0], 1))
print(data)
print(labels)
plt.figure()
plt.scatter(data[:... |
import numpy as np
import random
from csv import reader
import math
import copy
from scipy.optimize import minimize
# Load a CSV file
def loadCSV(filename):
file = open(filename, "rt")
lines = reader(file)
dataset = list(lines)
return dataset
# Stochastic gradient descent (SGD)
def ... |
from numpy import zeros, array_equal
from ubcs_auxiliary import precision_sleep, interupt_sleep
from time import time
import random
# def test_precision_sleep():
# """ runs multiple tests with fixed maximum allowed error (1 ms) """
# precision = 10.0e-4
# for i in range(100):
# sleep_t = random.ra... |
class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
stack = []
m = 0
curr = head
while curr:
stack.append(curr.val)
curr = curr.next
full = len(stack)
half = full // 2
curr = head
f... |
# https://codeforces.com/contest/63/problem/A
def single_integer():
return int(input())
def multi_integer():
return map(int, input().split())
def string():
return input()
def multi_string():
return input().split()
n = single_integer()
row = dict()
status_dict = {
"rat": 1,
"woman": 2,... |
import click
import easy_workflow_manager as ewm
@click.command()
@click.option(
'--pop-stash', '-p', 'pop_stash', is_flag=True, default=False,
help='Do a `git stash pop` at the end if a stash was made'
)
@click.argument('branch', nargs=1, default='')
def main(branch, pop_stash):
"""Get latest changes fro... |
# Generated by Django 3.1 on 2020-08-25 14:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('colony', '0004_auto_20200822_1611'),
]
operations = [
migrations.AlterField(
model_name='hive',
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-12-29 12:01
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django_mysql.models
class Migration(migrations.Migration):
dependencies = [
m... |
a=int(input("valor"))
b=int(input("valor"))
c=int(input("valor"))
print (min(a,b,c))
print ((a+b+c)-min(a,b,c)-max(a,b,c))
print(max(a,b,c)) |
"""test.py - integrating xinput.XInputJoystick with pygame for Windows + Xbox 360 controller
Windows Xbox 360 cannot use pygame events for the left and right trigger. The axis doesn't come through distinctly.
This alternative corrects that issue, and adds functions unique to the Xbox controller.
General approach:
1.... |
# Generated by Django 3.2.7 on 2021-09-04 19:36
from django.db import migrations, models, transaction
import django.db.models.deletion
from django.contrib.auth.models import User
import random
def create_users(apps, schema_editor):
with transaction.atomic():
users = [
{
'first_... |
import simplejson as json
import yaml
with open('overpass\syntaxes\overpassQL.yaml', 'r') as origin:
data = yaml.load(origin)
with open("overpass\syntaxes\overpassQL.json", "w") as target:
target.write(json.dumps(data, indent=3 * ' '))
|
#!/usr/bin/env python3
# Copyright 2021 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
# -*- coding: utf-8 -*-
"""
admin page schema module.
"""
from pyrin.api.schema.structs import ResultSchema
from pyrin.admin.interface import AbstractAdminPage
from pyrin.admin.exceptions import InvalidAdminPageTypeError
class AdminSchema(ResultSchema):
"""
admin schema class.
"""
def __init__(self,... |
import numpy as np
def quantizeMatrix(original_values, scale, zero_point):
transformed_val = zero_point + original_values / scale
clamped_val = np.maximum(0, np.minimum(255, transformed_val))
return(np.around(clamped_val))
def getFinalScale(real_multiplier):
if(real_multiplier > 1 or real_multipli... |
# -*- coding: utf-8 -*-
##############################################################################
#Author:QQ173782910
##############################################################################
CLIENT_NAME = 'wrobot'#注意:这个是项目名
DEBUG='1'
L_no=['newscontent','text_contents']#不判断副文本
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Création jeu bataille
import random
#préparation de la variable carte pour le traitement
cartes = [
[
"trefle", "pique", "coeur", "carreau"
],
[
"7", "8", "9", "10", "valet", "reine", "roi", "as"
]]
def tirerCarte(cartesDictionnaire):
... |
#player number two
from rtcmix import *
import random
import math
from stereoInsurance import stereoInsurance
#stereoInsurance(left, right, minPan, maxPan) where left and right are values 0-7
from glassesGran import granularGlasses
# granularGlasses(start, dur, grainTrans, chanX, chanY, searchTuple)
# comment/uncomm... |
# Generated by Django 3.2.5 on 2021-08-05 16:09
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Deposition_RF',
fields=[
('... |
# Test script for CounterACT
import urllib.request
import json
import logging
logging.info('===>Starting m3sp Test Script')
# Server configuration fields will be available in the 'params' dictionary.
base_url = params['connect_m3sp_url']
headers = {
'Content-Type': "application/json",
'charset': 'utf-8',
... |
import torch
import torch.nn as nn
#from utils import ExitBlock
from pthflops import count_ops
import torchvision.models as models
import numpy as np
#import config
class ConvBasic(nn.Module):
def __init__(self, nIn, nOut, kernel=3, stride=1,
padding=1):
super(ConvBasic, self).__init__()
... |
string_1 = "Терпение и труд - все перетрут!"
sub_string_1 = "труд"
string_2 = "Bema"
sep_string_2 = "B,e,m,a"
numlist = ['1', '2', '3']
separator = ', '
character = 'p'
unicode_char = ord(character)
string = "Python is awesome"
new_string = string.center(24)
str = 'xyz\t12345\tabc'
result = str.expandtabs()
random_stri... |
from setuptools import setup
def readme():
with open("README.rst") as f:
return f.read()
setup(name='k_index_calculator',
version='0.2.3',
description='Python module which calculates the K-Index of a geomagnetic time series.',
long_description='Calculates the K-Index of geomagnetic time series us... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.