text stringlengths 38 1.54M |
|---|
from websocket_server import WebsocketServer
from lib.message import MessageDecoder
import configparser
# Called for every client connecting (after handshake)
def new_client(client, server):
print("New client connected and was given id %d" % client['id'])
# Called for every client disconnecting
def client_left(... |
# part 1
def draw_stars(list):
for num in list:
print(num*"*")
draw_stars([1,2,3,4,5])
#part 2
def draw_stars2(list):
for thing in list:
if type(thing) is int:
print(thing * "*")
else:
print(len(thing) * thing[:1])
draw_stars2([1,2,3,4,5,"thing"])
|
# Copyright The OpenTelemetry Authors
#
# 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 ... |
#!/usr/bin/python
import iplanet_5_2
import iplanet_5_2hf0_8
import iplanet_5_2p1
import iplanet_5_2hf1_02
import iplanet_5_2hf1_16
import iplanet_5_2hf1_21
import iplanet_5_2hf1_25
import iplanet_5_2p2
targets = \
[iplanet_5_2.iplanet_5_2,
iplanet_5_2hf0_8.iplanet_5_2hf0_8,
iplanet_5_2p1.iplanet_5_2p1,
... |
from typing import (
Union,
)
from wasm.datatypes import (
ValType,
)
from .unknown import (
Unknown,
)
Operand = Union[ValType, Unknown]
|
#!/usr/bin/env python3
height, width, num_bricks = map(int, input().split())
bricks = [int(x) for x in input().split()]
c_h = 0 # current height
c_w = 0 # ... width
i = 0
while i < len(bricks) and (bricks[i] + c_w) <= width and c_h != height:
if c_w + bricks[i] == width:
c_w = 0
c_h += 1
... |
from coffer.utils import getRootDir, text, isRoot, getArg
from coffer import remove
import shutil
import sys
import os
def createArchive(path, name):
print (text.creatingPackage)
shutil.make_archive(name, "tar", path)
def compress(path, name):
createArchive(path, name)
os.rename(name + ".tar", name + ... |
import sys
import numpy as np
'''
习得:
1、矩阵比对字符串
2、创建矩阵数组-----None
n = np.arange(0, 30, 2)# start 0 step 2, stop before 30
n = n.reshape(3, 5) # reshape array to be 3x5
算方思想,利用伪矩阵比对两个字符串
'''
def getmaxStr(str1,str2):
len1=len(str1)
len2=len(str2)
sb=''
maxs=0 #最长公共字串的长度
maxI=0 #记录公共字串... |
def fact():
c = 1
n = int(input("Enter the number to find factorial...!"))
if (n == 0):
print("The factorial is 1)")
elif (n < 0):
print("Enter a positive integer")
else:
for a in range(n):
a = a + 1
c = c*a
prin... |
import smtplib
from email.mime.text import MIMEText
# 1建立连接
smtp = smtplib.SMTP("smtp.163.com")
# 2 登录
smtp.login("18137128152@163.com","******")
# 3 发送邮件
sender = "18137128152@163.com"
recever = "zhangzhaoyu@qikux.com"
message = MIMEText("这是一封使用<h1>Python</h1>写的邮件",_subtype="html")
message["from"] = sender
message["to... |
from TwitterSearch import *
# User credentials to access Twitter API
ACCESS_TOKEN = '4364945415-Ez38de5EYcRmEYIbtUsS8LDy0LhZwypoogypXjD'
ACCESS_TOKEN_SECRET = 'mCM3IF1Aele7WogZqmLWxEOaU9G1sV6s1MHIPxHlUKyXr'
CONSUMER_KEY = '5JoigYcA2Mzb9tA1DGQPAQroi'
CONSUMER_SECRET = 'ZDTJ14yIKHyDLeLlWXDNNAEDzOCg6nHz8z9c6eISFHLZ2oDB... |
# -*- coding: utf-8 -*-
import xmpp, inspect, re
import ConfigParser
class bot:
def DEBUG(self, text=None):
'''Режим отладки и тестирования'''
if self.debug:
self.config_file = 'nia_test.cfg'
print unicode(text)
comm_pref = 'nia_'
admin_comm_pref = 'admin_'
def ... |
import boto3
from pprint import pprint
import pathlib
def upload_file_using_client():
"""
Uploads file to S3 bucket using S3 client object
:return: None
"""
s3 = boto3.client("s3")
bucket_name = "binary-guy-frompython-1"
object_name = "sample1.txt"
file_name = f"{pathlib.Path(__file__)... |
from hashmap_repeated_word.hashmap_repeated_word import *
def test_happy_path():
words = "Once upon a time, there was a brave princess who..."
assert repeated_word(words) == 'a'
def test_happy_path_v2():
words = "It was a queer, sultry summer, the summer they electrocuted the Rosenbergs, and I didn’t know... |
import pygame
from image_rect import ImageRect
from pygame.sprite import Group
from point import Point
class Maze:
RED = (255, 0, 0)
BRICK_SIZE = 3
def __init__(self, screen, mazefile, brickfile, orangeportalfile, blueportalfile, shieldfile, pointfile):
self.screen = screen
self.filename ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/1/27 16:25
# @File : 1.二叉树遍历.py
# ----------------------------------------------
# ☆ ☆ ☆ ☆ ☆ ☆ ☆
# >>> Author : Alex
# >>> QQ : 2426671397
# >>> Mail : alex18812649207@gmail.com
# >>> Github : https://github.com/koking0
# ☆ ☆ ☆ ☆ ☆ ... |
def f(a):
return [a[i:i+3] for i in range(0,len(a),3)] #сделал функцию, дробящую значения в списке на вложенные списки
#функция работает на срезах списка. каждый раз в наш список на вывод добавляется вложенный список, состоящий
#из трех элементов основного списка. если не будет хватать элементов... |
# Generated by Django 2.2.1 on 2019-05-12 09:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0006_auto_20190508_0758'),
]
operations = [
migrations.CreateModel(
name='Contact',
fields=[
... |
# Generated by Django 2.2.5 on 2019-10-14 18:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0008_report'),
]
operations = [
migrations.AddField(
model_name='report',
name='cmnt',
field=mod... |
# -*- coding: utf-8 -*-
from pytest_solr.factories import solr_core
from pytest_solr.factories import solr
import pytest
substring_match = solr_core('solr_process', 'substring_match')
solr = solr('substring_match')
def test_exact_term_match(solr):
solr.add([{'id': '1', 'title': 'bananas'}])
assert 1 == solr.... |
def is_prime(a: int) -> bool:
if a == 1:
return False
for i in range(2, a):
if a % i == 0:
return False
return True
def is_very_prime(a: int) -> bool:
if 0 < a and a < 10:
return a in (2, 3, 5, 7)
return is_prime(a) and is_very_prime(a // 10)
n = int(input())
... |
import time
import redis
import unittest
import numpy as np
from neochi.core.dataflow import data_types
from neochi.core.dataflow.notifications import test_base, ir_receiver
class TestStartedIrReceiving(test_base.BaseTestNotification, unittest.TestCase):
notification_cls = ir_receiver.StartedIrReceiving
valid... |
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = [
url('^admin/', include(admin.site.urls)),
url(r'^', include('ipv6map.geodata.urls')),
url(r'... |
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
# Examples:
# /root-url/service-name/action/object_id
# /customers/customers/show/24
# ordering of urls matters here...
url(r'(?P<model>\w+)/(?P<action>\w+)/(?P<id>\w+)$','crudstuff.views.index'),
url(r'(?P<model>\w... |
__author__ = 'Jason Crockett'
import os
from os.path import expanduser
UserHome = str(expanduser("~"))
print(UserHome) |
import six
import sys
sys.modules['sklearn.externals.six'] = six
import mlrose
from airportProblem import fitnessFunction, showFlights
#customFitness é pra problema personalizado
fitness = mlrose.CustomFitness(fitnessFunction)
#represetando o problema, DiscreteOpt porque estamos trabalhando com números int(10 voos por... |
class Solution:
def reverse(self, x: int) -> int:
a = 0
negative = 1
if x < 0:
negative = -1
x = abs(x)
while x > 0:
a = a * 10 + x % 10
x = x // 10
if a > pow(2, 31):
return 0
return a * negative
def... |
#!/usr/bin/env python
import gzip
import sys
def readConversionFiles(chromosome_accessions):
accession_to_chrom = {}
ip = open(chromosome_accessions, 'r')
for line in ip:
if (line[0] != '#'):
fields = line.strip().split("\t")
if (fields[0] == "MT"):
chrom =... |
import logging
from agendatrends.models.geo import USState
from agendatrends.models.people import Legislator
from agendatrends.models.politics import PoliticalParty
from sunlightapi import sunlight, SunlightApiError
from agendatrends.pipelines.services import ServicePipeline
from agendatrends.pipelines.services.goog... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import threading
from .inotify_buffer import InotifyBuffer
from watchdog.observers.api import (
EventEmitter,
BaseObserver,
DEFAULT_EMITTER_TIMEOUT,
DEFAULT_OBSERVER_TIMEOUT
)
from watchdog.events import (... |
from tensorflow import keras
from tensorflow import keras
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
img_rows, img_cols = 240, 256
number_of_actions = 7
def generate_model():
model = keras.models.Sequential([
keras.layers.Convolution2D(32, 8, 4, input_shape=(img_rows, img_cols, 3)),
kera... |
from __future__ import division, print_function
# coding=utf-8
import sys
import os
import glob
import re
import numpy as np
import tensorflow as tf
# Keras
from keras.models import load_model
from keras.preprocessing import image
# Flask utils
from flask import Flask, redirect, url_for, request, render_template, sess... |
import os
import numpy as np
import cv2
import mrcnn.config
import mrcnn.utils
from mrcnn.model import MaskRCNN
from pathlib import Path
import requests
class MaskRCNNConfig(mrcnn.config.Config):
NAME = "coco_config"
GPU_COUNT = 1
IMAGES_PER_GPU = 1
NUM_CLASSES = 1 + 80
DETECTION_MIN... |
'''
Given a non-empty array containing only positive integers,
find if the array can be partitioned into two subsets such
that the sum of elements in both subsets is equal.
Note: dp = [False] * (sum//2)+1
make dp[i]=1 if dp[i] or dp[num-i] where num in nums and 1<=i<=len(dp)
'''
class Solution:
def canPartition... |
#!/usr/bin/python
from math import floor
def gcd(a, b):
if a>b:
if a%b==0:
return b
else:
return gcd(b, a%b)
else:
if b%a==0:
return a
else:
return gcd(a, b%a)
def smallest_multiple(num):
val=1
for i in range(2, ... |
def accumulate(total=0):
while True:
total += yield
yield total
if __name__ == '__main__':
acc = accumulate()
acc.next()
print (acc.send(10))
acc.next()
print (acc.send(20))
acc.next()
print (acc.send(30))
acc.next()
|
# coding=utf-8
import io
import sys
from selenium import webdriver
# from selenium.webdriver.support.ui import Testrubbish
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 05 09:14:16 2017
Determines the FX Sharpe Ratio.
Usual Input is the Daily Returns, But Can Deal with Cumulative
Returns if flagged with third parameter = 'cumulRet'
@author: luoying.li
"""
import numpy as np
from math import sqrt
class S... |
# -*- coding: utf-8 -*-
import scrapy
from dangdang.items import DangdangItem
from bs4 import BeautifulSoup
from bs4 import UnicodeDammit
class Spider1Spider(scrapy.Spider):
name = 'spider1'
allowed_domains = ['search.dangdang.com']
start_urls = ['http://search.dangdang.com/']
key = 'python'
def ... |
# Used to populate the trip_raw table from the raw csv data
import csv
import psycopg2
from db_connection import DBConnection
csv_file_path = 'D:/Projects/TOST/SampleDataset/tais_voyages_sample_hou_nol_points_by_voyage_w_ref.csv'
db_connection = DBConnection.get_instance().get_connection()
cursor = db_connection.curs... |
#!/usr/bin/env python
import tf
import rospy
from geometry_msgs.msg import PoseWithCovariance, TwistWithCovariance
from nav_msgs.msg import Odometry
from gazebo_msgs.msg import ModelStates
br = None
pubs = None
def model_states_cb(model_state):
for name, pose, twist in zip(model_state.name, model_state.pose, mode... |
import os
from tkinter import *
# NOTE: I had to import messagebox separatly to prevent tis error: 'NameError: name 'messagebox' is not defined'
from tkinter import messagebox
import tkinter as tk
import sqlite3
# import our other modules
import phonebook_main
import phonebook_gui
# function to center the app on th... |
import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeRegressor
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.tree import export_graphviz
import matplotlib.pyplot as plt
from talib import RSI, BBANDS, MACD
from sklearn.preproce... |
#-------------------------------------------------------------------------------------------#
# Autor: Arkangel AI
# Version: 2.0
# Year: 2021 - Mar
#-------------------------------------------------------------------------------------------#
import os
from funciones.funciones import *
from skimage import color, ... |
from django.db import models
from wagtail.core.models import Page
from wagtail.core.fields import StreamField
from wagtail.core import blocks
from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel
from wagtail.images.blocks import ImageChooserBlock
from .blocks import PortifolioBlock, ServiceBlock
clas... |
from controllers import base
from google.appengine.api import users
class AdminHandler(base.BaseHandler):
def get(self):
user = users.get_current_user()
if user:
self.render('dash.html')
else:
self.redirect(users.create_login_url(self.request.uri))
|
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 26 12:33:46 2021
@author: Usuario
"""
condicion="seguir"
while condicion == "seguir":
entrada=[]
#encera la lista
limit = int(input("Cuantos valores desea ingresar?:"))
# pone el numero de datos
for i in range(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 22 19:35:22 2018
@author: michal
"""
import sys
import os
path = os.path.dirname(__file__)
if not path in sys.path:
sys.path.append(path)
from fetchDialog import fetchdialog
try:
from pymol import plugins
except:
pass
def __in... |
#!/usr/bin/python
##############################################>
##############################################>
##
## Free BSD license 3-clause
##
## Copyright (c)<2011>, <Martin de Bruyn>
## All rights reserved.
##
## Redistribution and use in source and binary forms, with or without
## modificat... |
import numpy as np
import OpenGL.GL as gl
import ctypes
vertex_type = {
np.dtype(np.int8) : gl.GL_BYTE,
np.dtype(np.uint8) : gl.GL_UNSIGNED_BYTE,
np.dtype(np.int16) : gl.GL_SHORT,
np.dtype(np.uint16) : gl.GL_UNSIGNED_SHORT,
np.dtype(np.floa... |
# coding=latin-1
from flask import request, g
from flask import render_template
from flask import flash
from flask import jsonify
from flask import session
from flask import abort, redirect, url_for
from flask_login import login_user , logout_user , current_user , login_required
from cnddh.decoder import killgr... |
import argparse
import torch.utils.data
import random
import time
import numpy as np
from pydoc import locate
import scipy.misc
import csv
import os
import option
import models
import datasets
import utils
from point_cloud import Depth2BEV
from tqdm import tqdm
opt = option.make(argparse.ArgumentParser())
#d = datas... |
#!/home/jupyter/py-env/python2.7.13/bin/python2.7
import theano
a = theano.tensor.vector() # declare variable
out = a + a # build symbolic expression
f = theano.function([a], out) # compile function
print(f([0, 1, 2]))
|
import pyrealsense2 as rs
import numpy as np
import time
def initialize_camera():
# start the frames pipe
p = rs.pipeline()
conf = rs.config()
conf.enable_stream(rs.stream.accel)
conf.enable_stream(rs.stream.gyro)
prof = p.start(conf)
return p
def gyro_data(gyro):
return np.asarray([g... |
# -*- coding: utf-8 -*-
"""
server side code
Created on Mon Nov 7 03:36:00 2016
@author: Shriharsh Ambhore
@author: Kandhasamy Rajasekaran
@author: Daniel Akbari
"""
import socket
import sys
server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
server_socket.bi... |
class temperaturas() :
fecha=[]
celcius=[]
farenheit=[]
arreglo=[]
def __inint__(self):
pass
def leer(self):
archivo=open("temperaturas.txt","r")
for row in archivo:
self.arreglo.append(int(row))
def converti... |
import numpy as np
import time
class NN():
def __init__(self, lambd = 0.01, alpha_0 = 1e-2, alpha_final = 1e-5, mu = 0.1,
hidden_nodes = 32, num_iter = 40):
self.lambd = lambd
self.alpha_0 = alpha_0
self.learning_const = np.log(1.0*alpha_0/alpha_final) / num_iter
s... |
in_file_simC4_synA = open("/home/mshahandeh/BCsynA/sim_bcfs/simC4_synA.varX_SNPs-final.vcf", "r")
out_file_simC4_synA = open("/home/mshahandeh/BCsynA/sim_bcfs/simC4_synA.X_SNPs.txt" , "w")
done = 1
while done > 0:
i = in_file_simC4_synA.readline()
if i == '':
done = 0
elif i[0][0] == '#':
... |
import pyodbc
import connections as conn
cursor_new = conn.conn_new.cursor()
cursor_new.execute("Insert Into Department Values('Books')")
cursor_new.execute("Insert Into Department Values('Clothing')")
cursor_new.execute("Insert Into Department Values('Makeup')")
cursor_new.execute("Insert Into Department Values('Ki... |
# pyupbit module exercise
import pyupbit
print(pyupbit.Upbit)
tickers = pyupbit.get_tickers()
print(tickers)
tickers = pyupbit.get_tickers(fiat="KRW")
print(tickers)
price = pyupbit.get_current_price("KRW-ADA")
print(price)
price = pyupbit.get_current_price("BTC-ADA")
print(price)
price = pyupbit... |
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from typing import Optional
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "AWS Cost and Usage Report"
prefix = "cur"
class Action(BaseAction):
def __init__(self, ac... |
{
'sources': [
'../nodeif/jswrapbase.cc',
'../nodeif/fastJson.cc',
'../genes/genes.cc',
'../common/hacks.cc',
'../common/hacks_jsWrap.cc',
'../common/packetbuf.cc',
'../common/host_debug.cc',
'../common/jsonio.cc',
'../numerical/polyfit.cc',
'../numerical/haltonseq.cc'
]
}
|
from flask import Flask, render_template
from flask_mail import Mail
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_pagedown import PageDown
from .models import db, User, Role
from .config import configs
def regis... |
from django.shortcuts import render, get_object_or_404
from polls.models import Question
# view의 function이 하는 일은 request를 받아서 결과 template html
# 을 이용해서 결과파일을 만들어 내는 일.
def index(request):
# database에서 투표질문의 목록을 가져올 거예요!
# 원래는 문자열로 표현되야 하는데 .. ORM을 사용하다 보니 .. 각 레코드가
# Question 클래스의 객체로 표현.
my_list = Que... |
# -*- coding: utf-8 -*-
'''
rename all the files in the filepath
'''
import os
def rename():
'''change here'''
path='path to file'
'''may change here'''
cnt = 1
prename = "000000"
filelist=os.listdir(path)#该文件夹下所有的文件(包括文件夹)
for files in filelist:#遍历所有文件
Olddir=os.path.jo... |
import math
import time
from pyglet.window import mouse
import devices
import network
NODE_SIZE = 10
class Simulation:
def __init__(self):
self.current_mode = 2
self.selected_element = None
self.world = World()
self.world.simulation = self
self.net_manager = network.Networ... |
#import os
import sys
import re
#将目标文件读入,以列表形式返回,去除了符号
def ReadFile(path):
#path为传入的c,cpp路径,这里取相对路径
# file_object=open(path,'r',encoding='utf-8')
# list_of_all_lines=file_object.read().splitlines()
# file_content=str(list_of_all_lines).replace(" ","")
# file_object.close()
# return... |
from django.urls import path
from .views import *
urlpatterns = [
path('', Home,name='home-page'),
path('services/', Services,name='services'),
path('contact/', Contact,name='contact'),
]
|
# -*- coding: utf-8 -*-
def flesch_kincaid_grade(sentence_count, word_count, syllable_count):
if word_count == 0 or sentence_count == 0:
return .0
else:
return .39 * (float(word_count) / sentence_count) + \
11.8 * (float(syllable_count) / word_count) - 15.59
|
import os
import runez
from mock import patch
from pickley import PickleyConfig
from pickley.env import PythonFromPath, std_python_name
def test_standardizing():
assert std_python_name(None) == "python"
assert std_python_name("") == "python"
assert std_python_name("2") == "python2"
assert std_python... |
# import all necessary libraries
import pandas
from pandas.tools.plotting import scatter_matrix
from sklearn import cross_validation
from sklearn.metrics import matthews_corrcoef
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
# ... |
__version__ = "0.0.1"
__all__ = []
from pysqa.queueadapter import QueueAdapter
from pysqa.executor.executor import Executor
from ._version import get_versions
__version__ = get_versions()["version"]
del get_versions
|
"""Summarise hazard data
Susceptibility levels
---------------------
5 - rất cao - very high
4 - cao - high
3 - trung bình - medium
2 - thấp - low
1 - rất thấp - very low
Filename abbreviations
----------------------
lsz_45_2025 - landslide susceptibility zones under RCP 4.5 in 2025
lsz_85_2025 - landslide susceptib... |
#!/usr/bin/env python
from bottle import route, run, request, response, abort, default_app, get, post
import json
from create import create
from delete import delete
from retrieve import retrieve
from add_activities import add_activities
import os
import re
import sys
import os.path
import boto.dynamodb2
from boto.d... |
# -*- coding: utf-8 -*-
# @Time : 2019/6/26 19:06
# @Author : chinablue
# @Email : dongjun@reconova.cn
# @File : exceptions.py
'''
跟踪记录所有抛出的异常
'''
# 数据异常
class ParamTypeException(Exception):
'''
数据类型异常
'''
pass
# http异常
class HttpException(Exception):
'''
Http异常
'''
... |
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd
import numpy as np
from urllib.request import urlopen
import json
import pathlib
from app import app
import data_l... |
import csv
import numpy as np
from numpy import genfromtxt, savetxt
from sklearn.ensemble import RandomForestClassifier
#Specify training data, testing data, and labeled data file locations
ifile = open('../Data/train.csv', "r")
tfile = open('../Data/test.csv',"r")
data = genfromtxt(ifile,delimiter=',',dtype='f8')... |
from Planner import Planner
if __name__ == "__main__":
print 'Enter EID:'
eid = raw_input()
print 'Enter Password:'
pwd = raw_input()
p = Planner(eid, pwd)
while True:
print "Enter command:"
cmd = raw_input()
if cmd == "add":
print "Enter unique number to ad... |
import urllib, urllib2, logging
import openanything
from pylons import cache, config, request
import datetime
from demisaucepy import demisauce_ws_get
import pylons
from pylons.util import AttribSafeContextObj, ContextObj
from pylons.i18n import ugettext
from xmlnode import XMLNode
from demisaucepy import cfg
log = l... |
from django.core.management.base import BaseCommand
from django.core.management import call_command
class Command(BaseCommand):
help = 'Clears and refills ephemeral things, like the cache.'
def handle(self, *args, **kwargs):
self.stdout.write(self.style.MIGRATE_LABEL('Refreshing ephemeral stores...'... |
cars = 100
space_in_car = 4
drivers = 30
passengers = 90
cars_driven = drivers
cars_not_driven = cars - drivers
carpool_capacity = cars_driven * space_in_car
average_passengers_per_car = passengers/cars_driven
print "there are",cars,"cars in total"
print "there are only",passengers,"passengers in total"
print a... |
import os
import numpy as np
from kadai2 import GNN
def read_file(path):
os.chdir(os.path.dirname(os.path.abspath(__file__)))
with open(path) as f:
n=int(f.readline())
adjust_matrix=np.zeros((n,n))
for i in range(n):
l=list(map(int,f.readline().split()))
for j in... |
# http://www.geeksforgeeks.org/dynamic-programming-subset-sum-problem/
# https://www.youtube.com/watch?v=s6FhG--P7z0
def subset_sum(input_set, length, sum):
if sum == 0:
return True
if length == 0 and sum != 0:
return False
return subset_sum(input_set, length - 1, sum) or subset_sum(inp... |
# Generated by Django 2.1.2 on 2018-10-24 13:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0005_auto_20181018_1604'),
]
operations = [
migrations.AddField(
model_name='user',
name='password_reset_toke... |
import peewee
from vocabulary import settings
from vocabulary.settings import DB_PORT, DB_HOST, DB_USER, DB_NAME
db = peewee.PostgresqlDatabase(
DB_NAME,
user=DB_USER,
host=DB_HOST, port=DB_PORT)
|
# server endpoints
import json
import tornado.web
from database import db
# OUR MEMORY DB
users = dict() # ie: {"uname": {"location": "brighton", "type": "driver"}}
notifs = dict() # ie: {"driver": {"dest": "brighton", "origin": "london"}}
class LoginHandler(tornado.web.RequestHandler):
def set_default_headers... |
import random
Terrains = {
'plain': {
'color': '#71CD00'
},
'hill': {
'color': '#505355'
},
'water': {
'color': '#5D88F8'
},
'sand': {
'color': '#F9CF29'
},
'forest': {
'color': '#10A71E'
},
'city': {
'color': '#A1A5AA'
}
}... |
import csv
import numpy as np
columns_name = "代號,名稱,營收成長率,淨利成長率,營運現金流量成長率,負債比率,固定資產,資產報酬率,股東權益報酬率,資產周轉率,應收帳款周轉率,本益比,每股營收比"
def stock_indicator_reader():
data = []
stock_ids = []
stock_names = []
for line in open('indicator_predictor/data/indicator_data.csv', 'r').readlines()[1:]:
splitted = li... |
import random
b = random.randint(1,20)
a = [random.randint(-10,10) for i in range(0,b)]
print(a)
z = 0
k = 0
n = 0
for j in range (0,b):
if a[j]//3==0 or -(a[j])//3==0:
k+=1
if a[j]>0:
z=z+a[j]
n+=1
m = z//n
if m>0:
a.append(m)
a.insert(0,k)
print(a)
|
######################################################################################
## ALGORTITMO RSA _ COMPUTACION CIENTIFICA _ Universidad de Medellin. ##
## Marzo - 2016 ##
## ... |
from weatherdashboard.models import Country, Location
from django.core.management.base import BaseCommand
all_countries_data = [
{
"countryCode": "AD",
"countryName": "Andorra",
"currencyCode": "EUR",
"population": "84000",
"capital": "Andorra la Vella",
"continentName": "Europe"... |
def lista_e_munte(lista):
creste = True
scade = False
for i in range(0,len(lista)-1):
j = i+1
if creste:
if lista[j]<lista[i]:
creste = False
scade = True
|
from flask.ext.admin import AdminIndexView, BaseView
from flask.ext.admin.contrib.sqla.view import ModelView
from flask_admin.contrib.fileadmin import FileAdmin
from flask.ext.security import utils
from wtforms.csrf.core import CSRFTokenField, CSRF
from flask_admin.form import SecureForm
from wtforms import PasswordFie... |
from django import template
from dashboard.models import Category, Article, Tag
from dashboard.views import settings
from django.utils.html import format_html
register = template.Library()
@register.simple_tag
def highlight_query(title, query):
return format_html(title.replace(query,'<span class="highlighted">{}... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from xml.sax import make_parser, handler
edit_heat_map = []
for i in range(360):
edit_heat_map.append([0]*180)
class FancyCounter(handler.ContentHandler):
def __init__(self):
el = 0
def startElement(self, name, attrs):
el += 1
if el%1000000:
print "seen",el,... |
import asyncio
import sys
from collections import OrderedDict
import json
import shlex
import backoff
import coreapi
import coreschema
from django.utils.decorators import method_decorator
from django.utils import timezone
from django.views.decorators.cache import cache_page
from django.contrib.contenttypes.models imp... |
#
# Copyright (c) 2017 Juniper Networks, Inc. All rights reserved.
#
import logging
from cfgm_common import get_bgp_rtgt_min_id
from cfgm_common import VNID_MIN_ALLOC
from cfgm_common.exceptions import BadRequest
from cfgm_common.exceptions import HttpError
from cfgm_common.exceptions import PermissionDenied
from cfgm... |
#!/usr/bin/python
import sys
def main():
if len(sys.argv) != 2:
print("Usage:\n sums.py FILENAME")
return
filename = sys.argv[1]
file = open(filename, 'r')
# Gross and Net
gross = 0
net = 0
for line in file:
tokens = line.split()
if len(tokens) > 0 and tokens[0].startswith('201'):
... |
"""Synapse Challenge Services"""
import json
from typing import Union, Iterator
from synapseclient import Project, Synapse, Team
from synapseclient.core.utils import id_of
from .synapseservices.challenge import Challenge
class ChallengeApi:
"""Challenge services
https://docs.synapse.org/rest/index.html#org.... |
import oci
from oci.config import from_file
import base64
config = from_file(file_location="C:\\Users...config", profile_name='DEFAULT')
# Manages encryption/decryption of the data key.
def encryptdatakey(masterkeyocid):
# This function is called only when the Data Key needs to be encrypted by the Master ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.