text stringlengths 8 6.05M |
|---|
# Generated by Django 2.0.5 on 2018-06-25 18:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('calculation', '0029_auto_20180621_1142'),
]
operations = [
migrations.AddField(
model_name='product',
name='weight',... |
from django.shortcuts import render,redirect
from owner import forms
from owner.models import owner
def Num_to_str(request):
if request.method=="GET":
form =forms.NumtostringForm(initial={})
# form=BookForm()
context={}
context["form"]=form
return render (request,"num_to_s... |
from flask import Flask, request
from flask_restful import Resource, Api
from captura_de_informacoes import getTitulos
app = Flask(__name__)
api = Api(app)
class G1Titulos(Resource):
def get(self):
url= "https://g1.globo.com/"
titulos = getTitulos(url)
return geraResponse("Busca bem su... |
'''
This is just a SampleServer that we used for testing purposes
while writing the client script.
This version only prints the incomming data for debugging purposes and doesn't do anything 'real' with it.
A version, similar to this, is implemented on our django server
that constantly runs in the background, listening ... |
# Generated by Django 3.0.3 on 2020-03-03 08:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0003_lesson_teacher'),
]
operations = [
migrations.AddField(
model_name='student',
name='interests',
... |
import ccxt
import ta
import config
import schedule
from ta.volatility import BollingerBands, AverageTrueRange
import pandas as pd
exchange = ccxt.binance({
'apiKey':config.API_KEY,
'secret':config.API_SECRET
})
# markets = exchange.load_markets()
bars = exchange.fetch_ohlcv('BTC/USDT',limit=100)
df = pd.Dat... |
from numpy import genfromtxt
import numpy as np
from PIL import Image
weight,height = 960,540
canvas = np.zeros((height,weight,3), dtype=np.uint8)
image = genfromtxt('DS2.txt',dtype='int')
for i in range(540):
for j in range(960):
canvas[i][j] = [255,255,255]
for i in range(34096):
for j in ra... |
from . import views
from django.conf.urls import url
from .views import userprofile,taskstatus
urlpatterns=[
url(r'^profile', userprofile,name='profile'),
url(r'^statuschanger/(.*)$', taskstatus,name='statuschanger'),
url(r'^$',views.homepage,name='homepage'),]
|
def filter_lucky(lst):
return [i for i in lst if '7' in str(i)]
'''
Write a function filterLucky/filter_lucky() that accepts a list of integers and
filters the list to only include the elements that contain the digit 7.
For example,
ghci> filterLucky [1,2,3,4,5,6,7,68,69,70,15,17]
[7,70,17]
Don't worry about ba... |
#!/usr/bin/python
import sys
from bot_trust import *
if len(sys.argv) == 1:
filename = "sample.txt"
else:
filename = sys.argv[1]
case_list = get_data(filename)
i = 0
for case in case_list:
i += 1
step_count = process_case(case)
print('Case #{0}: {1}'.format(i, step_count)) |
apple num = 1
print(apple num)
# 檔名: exercise0402.py
# 作者: Kaiching Chang
# 時間: July, 2014
|
rule count_matrix:
input:
expand("outData/htseq/{sample}_CountNum.txt",sample=SAMPLES)
output:
"outData/counts/all.csv"
params:
units=units
script:
"../scripts/count-matrix.py"
def get_deseq2_threads(wildcards=None):
# https://twitter.com/mikelove/status/918770188568... |
import os
import random
import time
# default seed, wait in between for different seed
os.system('g++ -g -O2 -std=gnu++17 -static simple.cpp -o output/random1.exe')
time.sleep(1)
os.system('g++ -g -O2 -std=gnu++17 -static simple.cpp -o output/random2.exe')
time.sleep(1)
os.system('g++ -g -O2 -std=gnu++17 -static simpl... |
# -*- coding: utf-8 -*-
class Solution:
def repeatedSubstringPattern(self, s):
length = len(s)
for i in range(1, length // 2 + 1):
if length % i == 0 and s[:i] * (length // i) == s:
return True
return False
if __name__ == "__main__":
solution = Solution()
... |
from appium.webdriver.common.touch_action import TouchAction
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from tools.get_driver import GetDriver
from tools.get_log import GetLog
import allure
log = GetLog.get_log()
class Base:
# 初始化driver
@allure.step(... |
# Twitter
CONSUMER_KEY = 'consumer_key'
CONSUMER_SECRET = 'consumer_secret'
ACCESS_TOKEN = 'access_token'
ACCESS_TOKEN_SECRET = 'access_token_secret'
MAX_TWI_CHARACTERS = 280
MAX_TWI_PHOTOS = 4
TWI_URL = 'twitter.com/SOME_TWITTER_ACCOUNT'
# RabbitMQ
RABBIT_HOST = 'localhost'
RABBIT_AMQP_PORT = '5672'
RABBIT_LOGIN = '... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import os
from bibpdf import database
from bibpdf.file_object import PdfFile, CommentFile, PdfTempFile, BibTempFile
from bibpdf.formatters import simple_format, misc, bibtex_format, file_name_format
path = os.path
class Action(object):
def __init__... |
import numpy as np
def onehot(labels):
n_sample = len(labels)
n_calss = max(labels)+1
onehot_labels = np.zeros((n_sample, n_calss))
onehot_labels[np.arange(n_sample), labels] = 1
return onehot_labels
if __name__ == '__main__':
labels = [1, 3, 2, 0, 6, 4]
print(onehot(labels)) |
import numpy as np
import pandas as pd
import neworder as no
from math import sqrt
import pytest
def test_errors() -> None:
df = pd.read_csv("./test/df.csv")
# base model for MC engine
model = no.Model(no.NoTimeline(), no.MonteCarlo.deterministic_identical_stream)
cats = np.array(range(4))
# identity mat... |
import numpy
from DiscreteEnvironment import DiscreteEnvironment
class HerbEnvironment(object):
def __init__(self, herb, resolution):
self.robot = herb.robot
self.lower_limits, self.upper_limits = self.robot.GetActiveDOFLimits()
self.discrete_env = DiscreteEnvironment(resoluti... |
import numpy
import pandas as pd
import pickle
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import normalize, StandardScaler, LabelEncoder
import keras
import sys
import numpy as np
import scipy
import scipy.io
from keras.utils import to_categorical
import yaml
def read_data(filenam... |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
import os
import sys
#spark_home = os.environ.get('SPARK_HOME', None)
#if not spark_home:
# raise ValueError('SPARK_HOME environment variable is not set')
#sys.path.insert(0, os.path.join(spark_home, 'python'))
#sys.path.insert(0, os.path.join(spar... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
delete_nvl_polygon_element_query = """
UPDATE public.nvl_polygon AS npg SET deleted = TRUE,
active = FALSE WHERE ($1::BIGINT = 0 OR npg.user_id = $1::BIGINT) AND npg.id = $2::BIGINT RETURNING *;
"""
# delete_nvl_polygon_element_by_location_id_... |
#!usr/bin/env python3
import os
import random as rd
import numpy as np
import gdal
import matplotlib.pyplot as plt
def random_npp():
"""CREATE A RANDOM NPP GLOBAL MAP... AS AN np.array - 0.5°resolution """
mask = np.load('mask3.npy')[0]
rnpp = np.zeros(shape=(360,720),dtype=np.float32)
for j in ... |
/Users/samnayrouz/anaconda3/lib/python3.6/_dummy_thread.py |
import os
import sys
import tmdbsimple as tmdb
import urllib.request
def get_image(moviePoster, movieTitle):
if (moviePoster != 'N/A'):
# Create imagePosters directory if not present
os.makedirs("./imagePosters", exist_ok=True)
baseURL = 'https://image.tmdb.org/t/p/'
posters = ['w92', 'w154', 'w185', 'w300_a... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def get_nodules_pixel_coords(batch):
""" get numpy array of nodules-locations and diameter in relative coords
"""
nodules_dict = dict()
nodules_dict.update(numeric_ix=batch.nodules.patient_pos)
pixel_zyx = np.rint((batch.nodules... |
from battle.battleeffect.RegularAttack import RegularAttack
from battle.battleeffect.EffectType import EffectType
from battle.round.RoundAction import RoundAction
from ui.UI import UI
import random
# this represents a generic fighter of any kind.
class Fighter:
def __init__(self, name, hp, strength, defense, a... |
from multiprocessing import cpu_count
from os.path import isfile
import shutil
import itertools
from unittest import mock
import distributed
import pytest
from aospy import Var, Proj
from aospy.automate import (
_user_verify,
_MODELS_STR,
_RUNS_STR,
_VARIABLES_STR,
_REGIONS_STR,
_compute_or_sk... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
fil ="test_p\wildlife.csv"
#col_list=["Precipitation","IndicatedDamage","PilotWarned","CostTotal"]
#col_list=["TimeOfDay", "SpeedKnots","AltitudeFeet", "Sky","PhaseOfFlight","MilesFromAirport", "IndicatedDamage","CostTotal", ... |
# https://www.roblox.com/?v=rc&rbx_source=3&rbx_medium=cpa&rbx_campaign=1820
# roblox
'''
Adsmain
roblox
Auto
'''
from selenium import webdriver
from time import sleep
# import xlrd
import random
import os
import time
import sys
sys.path.append("..")
# import email_imap as imap
# import json
import re
# from urllib im... |
"""
Removes silent parts from songs.
"""
__author__ = 'David Flury'
__email__ = "david@flury.email"
import os
import glob
import argparse
import multiprocessing
from pydub import AudioSegment
from joblib import Parallel, delayed
from pydub.silence import split_on_silence
audio_extensions = ['.wav']
suffix = 'unsilen... |
class Node(object):
"""Node of double link list.
"""
def __init__(self, ele):
self.ele = ele
self.next = None
self.prev = None
class DoubleLinkList(object):
"""Double link list.
"""
def __init__(self, node=None):
self.__head = node
def is_empty(self):
... |
# Distributed with a free-will license.
# Use it any way you want, profit or free, provided it fits in the licenses of its associated works.
# ADC121C_MQ2
# This code is designed to work with the ADC121C_I2CGAS_MQ2 I2C Mini Module available from ControlEverything.com.
# https://shop.controleverything.com/products/propa... |
from eda import Eda
|
from __future__ import absolute_import
import os
from .version import __VERSION__ as __version__
#from .marshaltools import *
from .surveyfields import SurveyFields, ZTFFields
from .BaseTable import BaseTable
from .MarshalLightcurve import MarshalLightcurve
from .ProgramList import ProgramList
from .filters import lo... |
import os
import numpy as np
import torch
import torch.utils.data
from PIL import Image, ImageOps
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor
from engine import train_one_epoch, evaluate
import utils
impor... |
import datetime as dt
import numpy as np
import pandas as pd
from scipy.interpolate import CubicSpline
### cubic spline
# x : pd.Series
# -> pd.Series
def spline(x):
tv = np.array([t.replace(tzinfo=dt.timezone.utc).timestamp() for t in x.index.to_pydatetime()])
p = CubicSpline(tv, x)
tq = np.arange(int(np.floor(... |
import unittest
import teradata
import pyodbc
from config.db import (
db_teradata_prod,
db_teradata_prod_1
)
from .db import session_scope
from mmvizutil.db.query import (
Query,
db_query_df,
db_query_list
)
from mmvizutil.df.chart import (
df_box_melt
)
from mmvizutil.db.teradata import (
... |
import numpy as np
import scipy.io
import tensorflow as tf
from logger import logger
from constants import VGG19_LAYERS
class VGG(object):
"""VGG provides an interface to extract parameter from pre-trained neural network
and formulate Tensorflow layers"""
def __init__(self, trained, pooling):
log... |
# Day 15: Linked List - https://www.hackerrank.com/challenges/30-linked-list
class Node:
'''Create a node'''
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def display(self, head):
current = head
while current:
print(current.data... |
from django.db import models
class Product(models.Model):
title = models.CharField(max_length=128)
description = models.TextField(null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
publish = models.DateTimeField(
auto_now_add=False,
auto_now=False,
null=... |
# coding:utf-8
# Test Intersection Manager with UDP
# Get vehicle proposal, return the result
# Starting of installing the collision detect algorithm
import sys
from datetime import datetime
import socket
import struct
import json
sys.path.append('Users/better/PycharmProjects/GUI_Qt5/Intersection')
import funcs
import... |
import math
print ("x=")
x=int(input())
z=math.sqrt((3*x+2)*(3*x+2)-24*x)/(3*math.sqrt(x)-2/math.sqrt(x))
print("z=", z)
|
A=int(input("A= "))
hundred=int(A/100)
tens=int(A/10%10)
ones=int(A%10)
print(tens)
print(ones)
|
from Pyskell.Language.PyskellTypeSystem import *
from inspect import isclass
from collections import defaultdict
def ct(obj):
return str(type_of(obj))
__magic_methods__ = ["__{}__".format(s) for s in {
"len", "getitem", "setitem", "delitem", "iter", "reversed", "contains",
"missing", "delattr", "call", ... |
class Client:
def __init__(self, _id, name, phone, isCompany):
self.id = _id
self.name = name
self.phone = phone
self.isCompany = isCompany
class DiscountThreshold:
def __init__(self, _id, confID, startDate, endDate, discount):
self.id = _id
self.confID = confID... |
l=['k','a','b','a','l','i']
def check(st):
lis=list(st)
for i in lis:
if(i in l):
if(l.count(i)<=lis.count(i)):
continue
else:
return 0
break
else:
return 0
break
else:
return 1
n=int(inpu... |
from rest_framework import permissions
class UserPermissions(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS or request.method == 'CREATE':
return True
return obj == request.user |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 18 15:52:56 2021
@author: ftan1
"""
import numpy as np
import pydicom as pyd
import datetime
import os
import glob
import sys
import sigpy_e.cfl as cfl
if __name__ == '__main__':
# set image dir
image_dir = sys.argv[1]
image_file = imag... |
import numpy as np
import matplotlib.pyplot as plt
# dibujamos una funcion cualquiera en un grafico por ejemplo f(x)= cos(x) + cos(2x)
resol=1000
x=np.linspace(-5,5,resol)
f=lambda _x: np.cos(_x)+np.cos(_x*2)
plt.plot(x,f(x))
#-----------------------------------------------
# "Tiramos" una bolita en algun pun... |
import turtle
canvas = turtle.Screen()
canvas.bgcolor("lightgreen")
leo = turtle.Turtle()
leo.shape("arrow")
leo.color("pink")
leo.pensize(5)
def draw_square (size):
for i in range (4):
leo.forward(size)
leo.left(90)
def draw_squares (number, size):
"""
Draw squares
:param number: num... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 27 09:18:57 2018
@author: Administrator
"""
'''
rf:0.12836
lasso:
adboost: 0.41471
gbdt:0.13519
'''
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#加载数据
train = pd.read_csv('./input/train.csv',index_col=0)
test = pd.read_csv('./input/test.csv'... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
'''
ds9.py
Created by Carlos J. Diaz on 2013-12.
Busco las estrellas; alineo las imagenes y las combino
'''
#Importo lo necesario para el desarrollo del programa
from pyraf import iraf
import os, string, sys
from function2 import sex,sex2cat,sex2catb
#Y las funciones d... |
from django.contrib import admin
import messaging.models
admin.site.register(messaging.models.MessageTemplate)
admin.site.register(messaging.models.Event)
admin.site.register(messaging.models.Message)
|
#
# Copyright © 2021 Uncharted Software 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 l... |
#!/usr/bin/python
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
import cv2
from sklearn.cluster import DBSCAN
from extra_functions import cluster_gen
import pcl
import numpy as np
import matplotlib.cm as cm
import data_image_2
import itertools
from sklearn.cluster import Mea... |
import os
import cv2
import numpy as np
def bigavif(p):
if not os.path.isfile('0/af/'+p):
return False
if(os.path.getsize('0/af/'+p) - os.path.getsize('0/pq/'+p))< 100:
return True
return False
fyo=os.listdir('alph')
fyo.sort()
fyo=fyo[:-1]
for alphna in fyo:
zet = alphna.split('.')
if len(... |
from string import Template
# 1
#saves time typing and reduces code length
#2
# like if u wbant to use the delimeter $ in the template
# declaration then u can use double $$
#3
'''to attach a string at the end od the $item u'll have to use {}
like "the ${place}yard is far away from here"
its output will be "the shipy... |
#testing of the simulated annealing approach to the problem
import copy
import random
import math
import numpy as np
class Node:
def __init__(self, name):
self.name = name
self.edges = set()
def addEdge(self, toNode, cost):
self.edges.add((toNode, cost))
class GraphPartition:
... |
from typing import Mapping
from .base import api_function, BaseFunction
from ..request import Request
__all__ = (
'System',
)
class System(BaseFunction):
"""
Provides the function interface for the API endpoint's system information.
"""
@api_function
@classmethod
async def get_versions(... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import torch_geometric as pyg
import os.path as osp
import torch
import torch.nn.functional as F
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from pandas import DataFrame
from torch_geometric.data import DataLoader
from torch... |
# Author:ambiguoustexture
# Date: 2020-02-05
file = 'hightemp.txt'
n = int(input('N: '))
with open(file) as text:
lines = text.readlines()
lines_count = len(lines)
for index, flag in enumerate(range(0, lines_count, n), 1):
with open('hightemp_split_{:02d}.txt'.format(index), 'w') as split_file:
for ... |
from graph_db.access.cursor import Cursor
from graph_db.engine.api import EngineAPI
from graph_db.engine.graph_engine import GraphEngine
class GraphDB:
def __init__(self, config_path: str):
self.config_path = config_path
self.graph_engine: EngineAPI = GraphEngine(config_path)
def cursor(self)... |
trp_player = 0
trp_multiplayer_profile_troop_male = 1
trp_multiplayer_profile_troop_female = 2
trp_temp_troop = 3
trp_find_item_cheat = 4
trp_random_town_sequence = 5
trp_tournament_participants = 6
trp_tutorial_maceman = 7
trp_tutorial_archer = 8
trp_tutorial_swordsman = 9
trp_novice_fighter = 10
trp_regular_fighter =... |
from BowlingGame import BowlingGame
def main():
"""
Hi CardFlight devs! Thanks for reviewing my code. I didn't want to go over the 6 hour mark too much,
so I stopped before implementing much of the scoring system, but the input logic and display is here
I tried to cover as many cases as I could wi... |
import discord
from random import randint
bot = discord.Client()
prefix = "l?"
@bot.event
async def on_connect():
print(f"Connected. Logged in as {bot.user}")
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Game(name=prefix+"help"))
print("Ready")
@bot.event
async def on_message(mess... |
import os
import pandas as pd
from osmo_camera.calibration.temperature import (
temperature_given_digital_count_calibrated,
)
def process_temperature_log(
experiment_dir,
local_sync_directory_path,
temperature_log_filename="temperature.csv",
):
temperature_log_filepath = os.path.join(
lo... |
from django.views.generic import CreateView, UpdateView, DetailView
from django.urls import reverse
from examples.forms import ExampleForm
from examples.models import Example
class ExampleFormViewMixin(object):
form_class = ExampleForm
template_name = 'form.html'
def get_success_url(self):
retu... |
import numpy as np
from numba import njit
from game.othello import Othello, array_to_bits
import game.bitboard as bitop
import random
@njit
def simulate(o: Othello):
turn = 0
while not o.terminated():
moves = bitop.pack(o.my_moves())
if moves == 0:
o = o.make_move_pass()
e... |
from unittest.mock import Mock
import pytest
from game import Game
from model.components.skill import SkillComponent
from model.config import config
from model.helper_functions.item_callbacks import restore_skill_points
class TestRestoreSkillPoints:
@pytest.fixture()
def skill_component(self):
skill... |
from flask_login import LoginManager, AnonymousUserMixin
class MyAnonymousUser(AnonymousUserMixin):
def get_role(self):
return 'AnonymousRole'
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
login_manager.anonymous_user = MyAnonymousUser
|
from typing import Dict, List, Any
import torch
import numpy as np
from torch.nn import Linear, Dropout, functional as F
from torch.nn import CrossEntropyLoss
from pytorch_pretrained_bert.modeling import BertModel, BertOnlyMLMHead
from allennlp.nn.util import get_text_field_mask
from allennlp.nn.util import sequence_c... |
#this program is used to find the number
from util import utility
import math
try:
noOfTimes = int(input("How much time you want to ask the question:"))
low = 0
high = int(math.pow(2, noOfTimes))
print("Think a number between(", low+1, ")to(", high, ")in range")
print(utility.question(low,... |
# 10/30/17
# Number Cycler 1-100
x = 1
while True:
for counter in range(1, 101):
print(counter)
x += 1
# Done
|
from django.db import models
from residents.models import Community, Area
from smart_selects.db_fields import ChainedForeignKey
class IPCamera(models.Model):
class Meta:
verbose_name_plural = "IP Camera Settings"
STATUS = (
('EF', 'Entry Front Camera'),
('EB', 'Entry Back Camera'),
... |
from os import error, path
import sys
from typing import Set
sys.path.append(path.dirname(path.abspath(path.dirname(__file__))))
sys.path.append(path.dirname(path.dirname(
path.abspath(path.dirname(__file__)))))
from cctpy import *
from work.draw和cuda对比.A04run import create_gantry_beamline,run
def beamline_phase... |
from datetime import datetime
from django.db import models
from rest_hooks.models import Hook
class Note(models.Model):
title = models.CharField(max_length=140)
updated_at = models.DateTimeField(default=datetime.now())
content = models.TextField()
def __unicode__(self):
return self.title
... |
from django.db import models
class Collection(models.Model):
colID = models.CharField(max_length = 100, primary_key=True)
colName = models.CharField(max_length = 100)
colExh = models.TextField(blank = True)
colMods = models.TextField(blank = True)
class Exhibit(models.Model):
exhID = models.CharFi... |
import sys
import io
from pathlib import Path
import requests
import numpy as np
from astropy.table import Table, join
from astropy.io import fits
import astropy.units as u
import astropy.coordinates as coord
from astroquery.vizier import Vizier
SIA_URL = 'https://irsa.ipac.caltech.edu/SIA'
sia_params = {
'COLLEC... |
"""Module for Loading and Transformation of the given data file
Owner: Venkateshwaran Loganathan
Created: 19 July 2018"""
#import necessary modules
import sys
import os
import locale
import json
class Auto1ETL:
""" Class used for the loading and transformation of the given data set"""
def __init__(self, file... |
#!/usr/bin/env python3
__all__ = ["expand"]
from typing import List, Tuple
from functools import wraps
def find_braces(s: str) -> Tuple:
return (s.index("{"), s.index("}"))
def string_contains_set_of_braces(s: str) -> bool:
return s.find("}") > s.find("{") >= 0
def split_brace_contents(s: str) -> List[str]:... |
"""
Python exposes a terse and intuitive syntax for performing
slicing on lists and strings. This makes it easy to reference
only a portion of a list or string.
This Stack Overflow answer provides a brief but thorough
overview: https://stackoverflow.com/a/509295
Use Python's slice syntax to achieve the following:
C... |
# Generated by Django 2.1.2 on 2018-11-08 19:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0020_auto_20181005_1301'),
]
operations = [
migrations.AlterField(
model_name='category',
name='disclaim... |
# Python language basics 4
# control flow
# if statements
is_game_over = False
p_0_x_pos = 0
e_0_x_pos = 3
e_1_x_pos = 5
p_0_x_pos += 2 # p_0_x_pos = 2
if p_0_x_pos == e_0_x_pos: # False so skip code below
is_game_over = True
elif p_0_x_pos == e_1_x_pos: # False so skip code below
is_game_over... |
# -*- coding: utf-8 -*-
#1
total=0.0
a=eval(input())
if a >= 38000.0:
total = a * 0.7
elif a >= 28000.0:
total = a * 0.8
elif a >= 18000.0:
total = a * 0.9
elif a >= 8000.0:
total = a * 0.95
print(total)
input() |
import os
from random import randrange
import time
from novaclient.client import Client
import swiftclient.client
config = {'user':os.environ['OS_USERNAME'],
'key':os.environ['OS_PASSWORD'],
'tenant_name':os.environ['OS_TENANT_NAME'],
'authurl':os.environ['OS_AUTH_URL']}
conn = swiftcli... |
#
#
# This code is not well maintained, mostly for reference if we revisit the
# deep particle simulation/ related experiments.
#
#
import numpy as np
import cv2
from fauxtograph import VAE, GAN, VAEGAN, get_paths, image_resize
import matplotlib.pyplot as plt
%matplotlib tk
loader ={}
loader['enc'] = 'VAEGAN/new_ar... |
# -*- coding: utf-8 -*-
import string
import sys
from avro import datafile, io, schema
from avro.datafile import DataFileWriter
from avro.io import DatumWriter
__author__ = 'yd'
import avro.ipc as ipc
import avro.protocol as protocol
PROTOCOL = protocol.parse(open("../../../avro/herring-box.avpr").read())
server_add... |
import sys
import tkinter as tk
import os
import matplotlib
import tensorflow as tf
import numpy as np
import pyaudio
import wave
import subprocess
from PIL import ImageTk, Image
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure impo... |
# Числа Фибоначи
# Выведите n-ое число Фибоначчи, используя только временные переменные,
# циклические операторы и условные операторы. n - вводится
num = int(input('Введите число '))
num_1 = 0
num_2 = 0
for i in range(num + 1):
if i == 0 or i == 1:
num_1 = i
num_2 = num_2 + num_1
print(1, en... |
# for loops in python
magicians = ['candice', 'duque', 'jess', 'ali']
for magician in magicians:
print(magician.title())
revelers = ['candice', 'duque', 'jess', 'ali']
costumes = ['wayne', 'garth', 'clown', 'edie gray']
#this doesn't work the way I want it to
for reveler in revelers:
print(reveler.title() + ", yo... |
# -*- coding=utf8 -*-
from numpy import *
import matplotlib.pyplot as plt
import math
def loadDataSet(fileName):
cnt = len(open(fileName).readline().split()) - 1
print cnt
dataMat = []
labelMat = []
fr = open(fileName)
for line in fr.readlines():
lineArr = line.strip().spl... |
import unittest
from Calculator import Calculator
class MyTestCase(unittest.TestCase):
stub = Calculator()
def test_empty(self):
self.assertEqual(self.stub.add(""), 0)
def test_single(self):
self.assertEqual(self.stub.add("1"), 1)
def test_two(self):
self.assertEqual(self.s... |
# Generated by Django 2.2.6 on 2019-12-18 07:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('consumers', '0008_consumer_hab_id'),
]
operations = [
migrations.AddField(
model_name='consumer',
name='district',
... |
import sys
class p1(dict):
def __del__(self):
print("删除1")
class p2(dict):
def __del__(self):
print("删除2")
a = p1()
b = p2()
a["aa"] = b
b["aa"] = a
print("OK")
|
import sys
import urllib
import json
import argparse
import urllib.request
import unicodedata
import collections
import os
import xml.etree.ElementTree as ET
import csv
import glob
import urllib.parse
csv_file = open("data/genjitext.csv")
f = csv.reader(csv_file, delimiter=",")
header = next(f)
print(header)
map = {... |
from rest_framework import routers
from .api import LocationViewSet, UserViewSet, DeliverymanViewSet, DeliveryViewSet
from Car.api import Car_modelViewSet, CarViewSet, Car_rentViewSet
from Bike.api import Bike_modelViewSet, BikeViewSet, Bike_rentViewSet
router = routers.DefaultRouter()
router.register('users', UserVie... |
from collections import Counter
from functools import reduce
def solution_my(clothes):
items = {}
for cloth in clothes:
if cloth[1] in items:
items[cloth[1]].append(cloth[0])
else:
items[cloth[1]] = [cloth[0]]
answer = len(clothes)
temp = 1
if len(items) > 1:... |
import speech_recognition as sr
AUDIO_FILE=("calimp3.wav") #import the audio file
r=sr.Recognizer() #initialize the recognizer
with sr.AudioFile(AUDIO_FILE) as source:
audio=r.record(source)
try:
s=r.recognize_google(audio) #store the audio as text in s
except sr.UnknownValueError:
print("Could't understan... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.