text stringlengths 8 6.05M |
|---|
from pathlib import Path
from logging import getLogger, Formatter, FileHandler, StreamHandler, INFO, DEBUG
def create_logger(exp_version, base_path="./logs"):
log_file = (base_path + "/{}.log".format(exp_version))
# logger
logger_ = getLogger(exp_version)
logger_.setLevel(DEBUG)
# formatter
... |
import poplib
M = poplib.POP3('127.0.0.1')
M.user('victim')
M.pass_('hunter2')
numMessages = len(M.list()[1])
for i in range(numMessages):
for j in M.retr(i+1)[1]:
print(j)# smtpd_senddata.py
|
#!/usr/bin/env python
import argparse
import functools
import matplotlib
matplotlib.rcParams['backend'] = 'Agg'
import boomslang
import numpy
import os
import sys
from expsiftUtils import *
from plotMcperfLatencyCompare import plotMcperfLatencyComparisonDirsWrapper
import plotMcperfLatencyCompare
parser = argparse.... |
#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
#@
#@ Converts single the single solid, containting all the silicon detectors [output_file_name],
#@ into the true array of silicon detectors [output_file_name]
#@ Usage:
#@ python conver_silicon.py
#@
#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^cart/(?P<pk>[0-9]+)/add/$', views.add_cart, name='add_cart'),
url(r'^cart/(?P<pk>[0-9]+)/remove/$', views.remove_cart, name='remove_cart'),
url(r'^cart/checkout$', views.checkout, name='checkout'),
]
|
from __future__ import (absolute_import, division, print_function, unicode_literals)
from flask import Flask, request, jsonify, abort
from dotenv import load_dotenv, find_dotenv
from datetime import datetime
from reviewgramdb import *
from reviewgramlog import *
from repoutils import *
from languagefactory import Langu... |
from sqlalchemy import MetaData, Table, Column, Integer, String, DateTime, FLOAT
from gerenciador.utils.conector.mysql import mysql_engine
engine = mysql_engine('pessoal')
meta = MetaData()
gerenciador = Table(
'gerenciador', meta,
Column('id', Integer, primary_key=True),
Column('descricao', String(100)),... |
# -*- coding: UTF-8 -*-
from zope.interface import implements
from zope.interface import Interface
import persistent
from google.interfaces import IProject
class Project(persistent.Persistent):
"""A simple implementation of a Project .
Make sure that the ``Project`` implements the ``IProject`` interface:
... |
from django.contrib import admin
from lhcbpr_api import models
class ApplicationAdmin(admin.ModelAdmin):
pass
class OptionAdmin(admin.ModelAdmin):
pass
class ExecutableAdmin(admin.ModelAdmin):
pass
# class ApplicationVersionAdmin(admin.ModelAdmin):
# pass
admin.site.register(models.Application, Ap... |
from settings import MAX_ITENS, ITENS, BAG_SIZE
class Chromosome():
def __init__(self, gene):
self.gene = gene
self.total_benefit = 0
self.total_size = 0
for i in range(MAX_ITENS):
if self.gene[i]:
self.total_size += ITENS[i][0]
self.to... |
# -*- coding: utf-8 -*-
"""
@author: xiaoke
@file: img_sim.py
@time:2020-04-22 15:46
@file_desc:
"""
import logging as log
import sys
log.basicConfig(level=log.DEBUG)
_logger = log.getLogger(__name__)
from skimage.measure import compare_ssim
import cv2
import os
import voc
import numpy as np
|
from typing import List
from common import *
def busca_gulosa(map):
print('- Realizando Busca Gulosa:')
success = False
path_string = ''
path_list = [NodePath(map.start_node, None, None, [], map.relations)]
while len(path_list) and not success:
path = find_lower_path(path_list, 'gulosa')
... |
# Generated by Django 2.0 on 2018-01-30 16:15
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('madadju', '0002_letter_message_need_report_urgentneed'),
]
operations = [
migrations.RemoveField(
model_name='letter',
name='h... |
from django.shortcuts import render
# Create your views here.
from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
from django.contrib.auth.models import User
from rest_framework.authtoken.views... |
import cv2
import sys
from PyQt5.QtWidgets import QWidget, QLabel, QRadioButton, QPushButton, QApplication
from PyQt5.QtCore import QThread, Qt, pyqtSignal, pyqtSlot, QRect
from PyQt5.QtGui import QImage, QPixmap
from simplesaad_model import SimpleSaad
from hedia_keras import HediaKeras
from maarten_torch import Maarte... |
final = 347991
square = int(final ** 0.5)
if square % 2 == 0:
square -= 1
halfdown = square // 2
halfup = halfdown + 1
x = square**2 + halfup
for y in range(4):
if final <= x:
steps = halfup + x - final
break
if final <= x + halfup:
steps = halfup + final - x
break
x +... |
import threading
import time
def f():
for i in range(5):
print(f"f {i}")
time.sleep(1)
def g():
for i in range(5):
print(f"g {i}")
time.sleep(1)
print("creating threads")
tf = threading.Thread(target=f)
tg = threading.Thread(target=g)
print("starting threads")
tf.start()
tg... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-01-13 10:53
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependenc... |
if __name__ == "__main__":
import os
import sys
import argparse
try:
p = os.path.dirname(__file__)
if p not in sys.path:
sys.path.append(p)
except NameError:
pass
try:
pylo = sys.modules["pylo"]
except KeyError as e:
raise RuntimeErro... |
a=int(input())
b=list(map(int,input().split()))
r=[1]*a
for pa in range(a):
if pa==0:
if b[pa]>b[pa+1]:
r[pa]=r[pa]+r[pa+1]
elif pa>0:
if b[pa]>b[pa-1]:
r[pa]=r[pa]+r[pa-1]
print(sum(r))
|
class className:
def __init__(self, someProp):
self.someProp = someProp
def someFtn(self):
print(self.someProp)
def otherFtn()
print("Hello World!")
x = className("Voila!")
x.someFtn()
x.otherFtn()
|
primary=input("Enter primary color:").lower()
secondary=input("Enter primary color:").lower()
if(primary=="red"):
if(secondary=="yellow"):
print("When you mix red and yellow, you get orange.")
elif(secondary=="blue"):
print("When you mix red and blue, you get purple.")
else:
print("Y... |
class rental_info:
def __init__(self,vehicle_id,vehicle_name,customer_id,rental_date,rental_price,is_active):
self.vehicle_id = vehicle_id
self.vehicle_name = vehicle_name
self.customer_id = customer_id
self.rental_date = rental_date
self.rental_price = rental_price
... |
x = float(raw_input("number a: "))
y = float(raw_input("number b: "))
print "sum is: " + str(x + y)
print "subtracts is: " + str(x - y)
print "multiplies is: " + str(x * y)
print "divides is: " + str(x / y)
print "remainder is: " + str(x % y)
print "integer divides is: " + str(x // y)
print "Performs ex... |
from google.appengine.ext import ndb
class BYOusers(ndb.Model):
first_name = ndb.StringProperty()
last_name= ndb.StringProperty()
email = ndb.StringProperty()
class Story(ndb.Model):
title = ndb.StringProperty(required=True)
first_story_point_key = ndb.KeyProperty(required = False)
author = nd... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# main executable script
# stdlib
import argparse
import sys
import json
import time
from copy import deepcopy
# project
from controlflow.ControlFlowGraph import ControlFlowGraph
from test import *
def main():
parser = argparse.ArgumentParser(description="IMP langu... |
#Task
#Read a given string, change the character at a given index and then print the modified string.
#Input Format
#The first line contains a string, S.
#The next line contains an integer i, denoting the index location and a character c separated by a space.
#Output Format
#Using any of the methods explained abov... |
s,v=(input().split())
print(s+v)
|
word="banana"
count=0
for i in word:
if i == "a":
count=count+1
print(count)
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui/UIWarning.ui'
#
# Created by: PyQt5 UI code generator 5.15.1
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore,... |
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from django.db.models import F
from .models import Post, Category, Tag, SitePage
def about(request):
page = get_object_or_404(SitePage, url='about')
SitePage.objects.filter(url='about').update(number_views=F("number_view... |
#!/usr/bin/python
# Copyright 2014 Google.
#
# 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... |
from django.db import models
from django.contrib.auth.models import User
class List(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return '{} - {}'.format(self.pk, self.owner)
class Record(models.Model):
record = models.TextField()
list = models... |
class Solution:
# @param A : string
# @return a list of strings
def prettyJSON(self, A):
indent = ""
o =[]
curr = ""
for index, c in enumerate(A):
if(c == "[" or c == "{"):
#if the case is :
#{
... |
from io import open
import os
import matplotlib.pyplot as mpl
def transposition_encryption():
os.system('clear')
# Read file
txtFile = open('plain text.txt','r', encoding="utf8")
fileContent = txtFile.readlines()
txtFile.close()
# Replace returns by spaces
plain_text = ""
for fc in fil... |
#!/usr/bin/python3
'''
Defines the trip class
'''
from models.base_model import BaseModel
class Trip(BaseModel):
'''
Defines the trip class which inherits from BaseModel
'''
collection = "trips"
def __init__(self, *args, **kwargs):
if kwargs:
super().__init__(**kwargs)
... |
"""6.009 Lab 8A: carlae Interpreter"""
import sys
class EvaluationError(Exception):
"""Exception to be raised if there is an error during evaluation."""
def __str__(self):
return "EvaluationError"
def mult(args):
prod = 1
for elem in args:
prod *= elem
return prod
class Enviro... |
from flask import Flask
from flask import url_for
from flask import render_template
app = Flask(__name__)
@app.route("/")
@app.route("/index.html")
def index():
return render_template("index.html")
@app.route("/dashboard2.html")
def dashboard2():
return render_template("dashboard2.html")
@app.route("/d... |
import os
import numpy as np
import cv2 as cv
#resized_hsv_fisheye_1414593023678_1403623027411_00013_20140624_171851_jp.png
# /home/juraj/Desktop/juro/programovanie/dipl/dipl/init_work2
def open_img(fname):
path = '/home/juraj/Desktop/juro/programovanie/dipl/dipl/init_work2/fisheyes/2014/06/24/' + fname
img_read = ... |
# JTSK-350112
# robustness.py
# Taiyr Begeyev
# t.begeyev@jacobs-university.de
def example1():
# consider the case when denominator is 0
for _ in range(3):
x = int(input("enter a number: "))
y = int(input("enter another number: "))
print(x, '/', y, '=', x / y)
def example2(L):
# Wh... |
def tempAposentadoria(idade, tempoTrabalho):
if idade >= 65 and tempoTrabalho >= 30:
return True
else:
return False
idade = int(input())
tempoTrabalho = int(input())
print(tempAposentadoria(idade,tempoTrabalho)) |
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sen... |
from django.conf import settings
from Pbas import views
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^index$', views.login, name='pbas_index'),
url(r'^Home$', views.home_page, name='home_page'),
url(r'^signup_action/$', views.signup_a... |
from django import forms
from main_clothesmarket.models import Category, Kind, Product
# creation form of category
class CategoryForm(forms.ModelForm):
title = forms.CharField(max_length=16,
widget=forms.TextInput(attrs={'placeholder': 'Название', 'required': 'required'}))
catego... |
import numpy as np
import cv2
from keras.optimizers import Adam
from keras.models import Model, Sequential
from keras.callbacks import ModelCheckpoint
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.image import load_img, img_to_array
from keras.layers import Dense, Input, Dropout, Glo... |
import subprocess
import os
import sys
import re
sys.path.insert(0, os.path.join("tools", "families"))
import fam
import run_all_species
from run_all_species import SpeciesRunFilter
import plot_speciesrax
import simulations_common
import plot_simulations
do_run = True
do_plot = not do_run
datasets = []
cores = 40
sub... |
class Solution:
#贪心
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
index_g=0
index_s=0
while(index_g<len(g) and index_s<len(s)):
if(g[index_g] <= s[index_s]):
index_g +=1
index_s +=1... |
from radiopie import *
import logging
def main():
lcd = LCDController()
menu = MenuController(lcd)
menu.start()
def setupLogger():
logging.basicConfig()
log = logging.getLogger("radiopie")
log.setLevel(logging.DEBUG)
if __name__ == "__main__":
setupLogger()
main()
|
num = int(input("enter a number"))
nums = [i for i in range(2, num//2+1) if num % i != 0]
print(nums) |
import sys
import clean_taffy
import make_pool
import preprocess_data
import train_recommend
import train_recommend_selected
import glob
directory = "/var/www/html/users/"+str(sys.argv[1])
province = sys.argv[2]
root_dir = "/var/www/html/"
train_recommend_selected.train_and_recommend_selected(root_dir, directory, pro... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 9 11:27:21 2020
@author: adonay
"""
import numpy as np
import matplotlib.pyplot as plt
import utils_io as uio
## Plotting functions
def plot_per_axis(ts, time, color, fig_axes, **kwargs):
"For each axes subplot plots ts and time"
for i, a... |
# Copyright 2022 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
import json
from constants import *
import matplotlib.pyplot as plt
import numpy as np
DEFAULT_LINKS_FILE = "paper_links.txt"
DEFAULT_OUTPUT_FILE = "json_data.json"
def plot_paper_ranks(papers, ticks=False):
x = np.array(range(len(papers)))
if ticks:
y = np.array([paper[1] for paper in papers])
... |
from django.test import TestCase
from .models import *
from django.contrib.auth import get_user_model
User = get_user_model()
from rest_framework.test import APIClient
# Create your tests here.
class TweetTestCase(TestCase):
def setUp(self):
self.user = User.objects.create_user(username="abc", password="pa... |
def CountVowel(word):
print ("Given String {0}".format(word))
word = word.lower()
return {
v:word.count(v) for v in 'aeiou'
}
if __name__ == '__main__':
CountVowel("I Love Python Programming")
|
# -*- coding: utf-8 -*-
"""
linalg.py
Functions implementing maths in linear algebra.
Function list:
dot_mod
dot_mod_as_list
mat_pow_mod
mat_pow_mod_as_list
mat_pow_sum_mod
gauss_jordan_elimination
gauss_jordan_modular_elimination
gauss_jordan_modular_elimination_as_list
gauss_jord... |
from functions import *
from whatssApp import *
if __name__ == "__main__":
wish()
#speak(takecommand())
while 1 :
query = takecommand().lower()
#logic building
############# Open Notepad
if "open notepad" in query:
npath = "C:\\WINDOWS\\system32\\notepad.exe"
... |
import csv
import numpy as np
import tensorflow as tf
import pandas as pd
def test0():
x = tf.Variable(initial_value=1, dtype=tf.int32)
print(x) # x is a Variable
x = x.assign(1)
print(x) # x becomes a Tensor with less capacity
def test1():
a = tf.placeholder(dtype=tf.float32, shape=(3,))
... |
from flask import Flask,request, url_for, redirect, render_template, jsonify
import pandas as pd
import pickle
import numpy as np
app = Flask(__name__)
model = pickle.load(open('Module 2/flaskapp/model.pkl', 'rb'))
day_dict = {'Fri':[1,0,0,0,0,0,0], 'Mon':[0,1,0,0,0,0,0],
'Sat': [0,0,1,0,0,0,0]... |
from rest_framework import generics, permissions
from .serializers import CompanySerializer, ContactSerializer, ProjectSerializer, TaskSerializer
from .models import Company, Contact, Project, Task
class CompanyDetail(generics.RetrieveUpdateDestroyAPIView):
model = Company
queryset = Company.objects.all()
... |
# Licensed to Tomaz Muraus under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# Tomaz muraus licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in... |
__author__ = 'lish'
from numpy import *
from scipy.cluster.vq import vq, kmeans, whiten
dataSet = []
fileIn = open('test2.txt')
for line in fileIn.readlines():
# print line.replace('\n','')
# lineArr = line.strip().split(',')
# dataSet.append([int(lineArr[0]), int(lineArr[1])])
dataSet.append([int(lin... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import jsonify, request
from flask_restful import Resource
from flask_api import status
import requests,json
import re
"""
Class Validation for checking input fields sent through UI
SMTP class - Endpoint for retreiving and setting SMTP configuration parame... |
"""fn
Description:
`zet` is a mess
use `fn` to generate a file name.
use `fn -r [dir]` to get the most recent file (in dir).
more options listed below.
Usage:
zet hen list <adr>
Options:
-h --help show this screen.
--version show version.
"""
from sys import exit as pexit
from sys import stde... |
from flask import Flask
from flask.ext.restplus import Api
from flask.ext.restplus import fields
#from International_Cuisine_Clustering.ipynb import similar_cuisines
app = Flask(__name__)
api = Api(
app,
version='1.0',
title='Cuisine Predictor',
description='Recommend similar cuisines')
ns = api.namesp... |
# -*- coding:utf-8 -*-
import logging
import os
import zipfile
from urllib.parse import urlparse
import numpy as np
import tensorflow as tf
from pai_tf_predict_proto import tf_predict_pb2
from com.aliyun.api.gateway.sdk import client
from com.aliyun.api.gateway.sdk.common import constant
from com.aliyun.api.gateway.s... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 读取mnist数据集
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# 学习速率
learning_rate = 0.001
# 训练步长
train_step = 10000
# 每次训练放入的样本数量
batch_size = 100
# 打印间隔
displayer_step = 100
# 一个向量有多少元素
frame_size = 28
# 一共有多少向量
sequence... |
a=0
frase = input("Ingrese una frase: ")
letrita= input("\nIngrese letra a buscar: ")
print (frase.replace(' ', '')) #Reemplaza los espacios en blanco
for letra in frase:
if letra == letrita:
a+=1
#print(letra)
if a == 0:
print("No aparece en la frase la letra ", letrita)
elif a ==1:
print(a,... |
#C언어는 {}로 종속문장을 구분
#파이썬은 공백으로 구분 => 스페이스바 4번
# time = float(input("현재 시간 : "))
# if time >= 18.5:
# print("집에가자~")
# else:
# print("공부합시다.^^")
#print()내부에 end공간에 "\n"를 넣어놓은거에요
age = int(input("당신의 나이를 입력 : "))
if age > 19:
print("당신은 성인",end="☆")
else:
print("당신은 미성년자",end="☆")
print("입니다... |
# flake8: noqa
import os
import django_heroku
import requests
from .base import *
SECRET_KEY = os.environ.get("SECRET_KEY")
DEBUG = bool(os.environ.get("DEBUG", False))
ALLOWED_HOSTS = [
# Change me!
"ocloud-backend.herokuapp.com",
"o-cloud.com",
]
if "ALLOWED_HOST" in os.environ:
ALLOWED_HOSTS.app... |
n = input("Please enter a positive integer : ")
n = int(n)
m = 1
while m <=10:
print(n,"x",m,"=",n*m)
m += 1 |
# -*- coding: utf-8 -*-
import codecs
import os
topics = {}
with codecs.open('test_predict_new.csv', 'w', 'utf8') as writer:
with codecs.open('test_predict.csv', 'r', 'utf8') as predict_reader:
with codecs.open('test_pair', 'r', 'utf8') as pair_reader:
predict_reader.readline()
for... |
# -*- coding: utf-8 -*-
class Solution:
def interpret(self, command: str) -> str:
return command.replace("()", "o").replace("(al)", "al")
if __name__ == "__main__":
solution = Solution()
assert "Goal" == solution.interpret("G()(al)")
assert "Gooooal" == solution.interpret("G()()()()(al)")
... |
import os
from .ImageCaptionsDataset import ImageCaptionsDataset
def Sydney(data_dir: str, transform=None):
file_name = 'dataset_sydney_modified.json'
file_path = os.path.join(data_dir, file_name)
# f'{data_path}/{file_name}'
return ImageCaptionsDataset(file_path=file_path, transform=transform)
|
a=input().split(" ")
for i in range(len(a)):
a[i]=int(a[i])
small=min(a)
big=max(a)
a.remove(small)
a.remove(big)
small=min(a)
big=max(a)
print(big,small)
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, with_statement
from revolver import command, package
from revolver import contextmanager as ctx
from revolver import directory as dir
from revolver.core import sudo, run
_VERSION = '2.4'
_OPTIONS = ''
def install(version=_VERSION, options=_O... |
#1.jointplot, 2.pairsplots, 3.heatmaps
#jointplot
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
tips = sns.load_dataset('tips')
sns.jointplot(x='total_bill', y='tip', data=tips)
plt.show()
sns.jointplot(x='total_bill', y='tip', data=tips, kind='kde')
plt.show()
#pairplot
sns.pa... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name = 'index'),
path('performance/', views.performance, name='performance'),
path('contact/', views.contact, name='contact'),
path('buySeasonTickets/', views.buySeasonTicket, name='buySeasonTickets'),
path('paym... |
a = 0
if not a:
print("gagné")
elif a:
print("perdu")
|
# coding=utf-8
import requests
from lxml import html
from .config import LOGIN_URL,data,headers
def login():
s = requests.session()
r = s.get(LOGIN_URL)
tree = html.fromstring(r.text)
el1 = tree.xpath('//input[@name="post_key"]')[0]
post_key = el1.value
id = input('Please input your pivix id:'... |
#!/usr/bin/python
import os
import sys
import subprocess, re, shutil, glob
import gettext
_ = gettext.lgettext
COLOR_BLACK = "\033[00m"
COLOR_RED = "\033[1;31m"
PRESCRIPTS = """
patch -s < ks.p
patch -s < conf.p
sudo mv /etc/mic/mic.conf /etc/mic/orig.conf
sudo mv test.conf /etc/mic/mic.conf
"""
POSTSCRIPTS = """
su... |
import os
import sys
sys.path.insert(0, 'scripts')
import experiments as exp
import run_ALE
def launch(datadir, cluster, cores):
dataset = os.path.basename(os.path.normpath(datadir))
command = ["python"]
command.extend(sys.argv)
command.append("--exprun")
resultsdir = os.path.join("RestartAle", dataset)
... |
# -*- encoding: utf-8 -*-
class Retorno:
''' Retorno Débito Automático '''
def __init__(self, arquivo):
pass
|
import turtle as t
def write_xy(x,y):
t.goto(x,y)
t.stamp()
t.write("x:%d, y:%d"%(x,y))
def screen_clear(x,y):
t.goto(x,y)
t.clear()
t.setup(600,600)
s=t.Screen()
t.penup()
s.onscreenclick(write_xy,1)
s.onscreenclick(screen_clear,3)
s.listen()
|
#list
list = ['one','two','three','four','five','six']
list[2] = '2' #index is start from zero
print list
#append & remove
list.append('qqzezr')
if 'one' in list:
list.remove('one')
list.sort()
print list
#tuple
tuple = ('a','b','c') #can't change the value in tuple
print tuple
#dict
dic = {'1':'one','2':'two',... |
# Generated by Django 2.2.2 on 2019-08-28 09:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0002_usertoken'),
]
operations = [
migrations.AlterField(
model_name='client',
name='token',
fie... |
# insertion_sort.py
class Solution():
def insertion_sort(input):
result = []
for i in range(0, len(input)):
j = i
while j > 0 and input[i] < result[j-1]:
j -= 1
result.insert(j, input[i])
return result
def main():
pass
if _... |
import gevent
from uc.itm import ITM, UCWrapper
from collections import defaultdict
from numpy.polynomial.polynomial import Polynomial
import logging
log = logging.getLogger(__name__)
'''
This wrapper exists in the UC execution in both the real and ideal worlds
as a standalone ITM. In a way this can be seen as a func... |
import numpy as np
from scipy.io import loadmat
import pickle
import random
window_len = 30*256
pid = 1
file_x = r'\Users\Owner\Desktop\chb-mit\data\patient{0}\features_se.mat'.format(pid)
file_y = r'\Users\Owner\Desktop\chb-mit\data\patient{0}\y_data{0}.npy'.format(pid)
interval_file = r'\Users\Owner\Desktop\chb-mi... |
#read the file which contains the pairs
f=open("C:\\Users\\HoratiuC\\Documents\\numbers.txt","r")
nums = f.read().split('\n')
#read the first element of the list, showing the number of pairs
print ("This program sums {} pairs of numbers".format(int(nums[0])))
#remove first element, only pairs remain
l = nums[... |
"""
Given a binary array, find the maximum length of a contiguous subarray with
equal number of 0 and 1.
Example 1:
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0
and 1.
Example 2:
Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous sub... |
from neo.io.basefromrawio import BaseFromRaw
from neo.rawio.nixrawio import NIXRawIO
# This class subjects to limitations when there are multiple asymmetric blocks
class NixIO(NIXRawIO, BaseFromRaw):
name = 'NIX IO'
_prefered_signal_group_mode = 'group-by-same-units'
_prefered_units_group_mode = 'split... |
import os
import sys
from unittest.mock import Mock
from sc2 import Race, race_worker
from sc2.units import Units
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from wombots.zerg_bot import *
# noinspection PyUnresolvedReferences
from wombots.composed_bot import *
async def asyn... |
import sys
from utils import Utils
from utils import APIs
def lcodeViewer(utils):
utils.codeLoad()
codes = utils.lcode
msg = ''
idx = 0
for code in codes:
idx +=1
if msg == "":
msg = "[%s](%s)"%(code, codes[code])
else:
msg += "\t\t" + "[%s] %s"%(cod... |
#!/usr/bin/python
# -*- coding:utf8 -*-
"""
@author:xiaotian zhao
@time:12/24/18
"""
from __future__ import print_function
import scrapy
import re
import time
import random
import BeautifulSoup
from urllib import quote
class ProxyCrawler(scrapy.Spider):
name = "proxy_crawler"
allowed_domains = ['zh... |
from __future__ import absolute_import
import numpy as np
import mimpy.mesh.mesh as mesh
import mimpy.mesh.hexmesh_cython as hexmesh_cython
from six.moves import range
class HexMesh(mesh.Mesh):
""" Class for constructing structured hexahedral meshes.
"""
def _nonplanar_face_normal(self, face_index):
... |
from rest_framework import serializers
from .models import Hunter, JobArea, Company, Internship, Stack, Roadmap, PlanItem, Test, Vacancy
from myauth.serializers import UserSerializer
class JobAreaSerializer(serializers.ModelSerializer):
class Meta:
model = JobArea
fields = ('id', 'title', 'related_... |
from django.db import models
from reddituser.models import RedditUser
from subreddit.models import Subreddit
from django.utils import timezone
class PostComment(models.Model):
def getPopularity(self):
return self.up_vote.count() - self.down_vote.count()
user = models.ForeignKey(RedditUser, on_delete=m... |
import tensorflow as tf
import cv2
import facenet.src.align.detect_face as detect_face
def test():
video = cv2.VideoCapture(0)
print('Creating networks and loading parameters')
with tf.Graph().as_default():
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=1.0)
sess =... |
from django.conf.urls import url, include
from django.contrib import admin
from accounts.views import (login_view, logout_view, register_view)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^register/', register_view, name='register'),
url(r'^login/', login_view, name='login'),
url(r'^logout/'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.