text stringlengths 38 1.54M |
|---|
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.template.context_processors import csrf
from django.conf import settings
from django.shortcuts import render_to_response
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from .... |
# TUPLES LESSON
# Tuples
# What is a Tuple in Python?
# A Python tuple is a collection type data structure which is immutable bydesign and holds a sequence of heterogeneous elements.
# It functions almost like a Python list but with the following distinctions. Tuples store a fixed set of elements
# and don’t allow chan... |
# -*- coding: utf-8 -*-
from datetime import datetime
import pika,time,random
from app_demo1.lib.redisConnector import Connector as redisConnector
from app_demo1.config import config as CONFIG
'''
对已创建任务未执行任务进行切片环境匹配检查,有空闲且匹配的环境则发送给对应worker的消息通道
'''
def send_task(self,task,slave):
#发送task到redis
task = {
... |
"""
Exercise from: https://www.practicepython.org/exercise/2014/12/14/23-file-overlap.html
Code created by Ruben Jimenez
"""
def filetoIntlist(theFile):
theList = []
with open(theFile,'r') as f:
line = f.readline()
while line:
theList.append(int(line))
line = ... |
from flask import Flask, make_response
import dadosApiRest
app = Flask(__name__)
@app.route('/getDisciplinasPorPeriodo')
def disciplinas_por_periodo():
response = dadosApiRest.disciplinas_por_periodo()
response = make_response(response)
response.headers['Access-Control-Allow-Origin'] = "*"
return response
@a... |
# -*- coding: utf-8 -*-
###############################################################################
#
# SendMail
# Allows you to send emails.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... |
import re
lines = open('input.txt').read().replace('\n\n', '\n').split('\n')
accumulator = 0
executed_lines = []
i = 0
while i < len(lines):
if i in executed_lines:
print(accumulator)
break
executed_lines.append(i)
matches = re.match(r'(\S+) ([+-])(\d+)', lines[i])
operation, argument... |
# Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
# You may assume that the array is non-empty and the majority element always exist in the array.
# Example 1:
# Input: [3,2,3]
# Output: 3
# Example 2:
# Input: [2,2,1,1,1,2,2]
# Output: 2... |
"""
Sort
Quck Sort - Pivots
Get the first value (current value), itterate through the unsorted list and
place anything that is smaller than the current value to the left of it. Set
this value as a pivot, and then repeat for the next value.
"""
def Quick_Sort_Pivots(array, show):
def Show_Value... |
from dataclasses import dataclass
@dataclass
class MockLine:
"""
Helper class for testing line drawing.
We don't care if a line is drawn from A->B or B->A and we want the
two cases to be considered equal, so we define this class and
override the __eq__ and __hash__ methods.
"""
p1: tuple
... |
# Created on 2011-12-08
# implement a (near)real-time feed of user activities, sorta like a
# Facebook Feed or Twitter stream
import pygtk
pygtk.require('2.0')
import gtk, pango, gobject
import os, sys, gc
import datetime
import filecmp
import atexit
from signal import signal, SIGTERM
from pymongo import Connectio... |
import random
import numpy as np
from environment import Agent, Environment
from planner import RoutePlanner
from simulator import Simulator
n_trials = 200 # Sets number of trials
class LearningAgent(Agent):
"""An agent that learns to drive in the smartcab world."""
def __init__(self, env):
super(Le... |
destinations = [
"Space Needle",
"Crater Lake",
"Golden Gate Bridge",
"Yosemite National Park",
"Las Vegas, Nevada",
"Grand Canyon National Park",
"Aspen, Colorado",
"Mount Rushmore",
"Yellowstone National Park",
"Sandpoint, Idaho",
"Banff National Park",
"Capilano Suspension Bridge",
]
import geocoder
# Declare de... |
# -*- coding=utf-8 -*-
# author: yanyang.xie@thistech.com
import os
import re
class ManifestPaser(object):
def __init__(self, manifest, request_url, psn_tag=None, ad_tag=None, sequence_tag='#EXT-X-MEDIA-SEQUENCE', asset_id_tag='vod_', provider_tag = 'ProviderId'):
self.manifest = manifest
self.req... |
import os
home_dir = os.system("pytest test/configuration/testConfiguration.py test/extractors/testCsvExtractor.py "
"test/extractors/testSpiderWebScrapperExtractor.py ")
|
__author__ = 'svankiE'
from clew.core.model import Event
from clew.search.index_builder import IndexBuilder
if __name__ == '__main__':
print "Building object index..."
builder = IndexBuilder()
events = Event.query.all()
if events:
# for now, building clean, shiny indexes.
builder.buil... |
from unittest import TestCase
from jira.Objects import StatusObject
class TestStatusObject(TestCase):
def test_properties(self):
item = StatusObject(
ident='ident1',
name='display_name1'
)
self.assertEqual('ident1', item.ident)
self.assertEqual('display_nam... |
from django.contrib import admin
from accounts.models import ApiSecretToken
admin.site.register(ApiSecretToken)
|
import numpy as np
from .optimizer import Optimizer
class RMSprop(Optimizer):
"""TODO: RMSprop docs"""
def __init__(self, lr, momentum=0.9):
super().__init__()
self.lr = lr
self.momentum = momentum
self.cache = {}
def step(self, model):
for i, (param, grad) in enu... |
import urllib2
import urllib
import getpass
import socket
import os
user = getpass.getuser()
home = os.environ['HOME']
host = socket.gethostname()
info = {"user": user, "home": home, "host": host}
message = ("Hello, I am {user}, my things are in {home}." +
" Come find me on {host}!").format(**info)
args... |
"""
Input Format
The first line of input contains the original string. The next line contains the substring.
Testing things
Output Format
Output the integer number indicating the total number of occurrences of the substring in the original string.
Sample Input
ABCDCDC
CDC
Sample Output
2
"""
str,sub,count=raw_i... |
def min_path_sum(matrix):
row_length = len(matrix)
col_length = len(matrix[0])
dp = [[0 for _ in range(col_length)] for _ in range(row_length)]
# fill first row and col..
dp[0][0] = matrix[0][0]
for row in range(1, row_length):
dp[row][0] = matrix[row][0] + dp[row-1][0]
for col ... |
"""
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class DataItem(object):
def __init__(self):
self._biz_trace_id = None
self._ext_res_field = None
self._highlight_summary = None
self._highlight_title = None
self... |
#!/usr/bin/env python
PACKAGE = "ros_basics_exercise"
from dynamic_reconfigure.parameter_generator_catkin import *
gen = ParameterGenerator()
mode_enum = gen.enum([gen.const("Obstacle_Avoidance", int_t, 0, "run with obstacle avoidance"),
gen.const("Test", int_t,... |
# -*- coding: utf-8 -*-
from datetime import time
from datetime import timedelta
from datetime import datetime
#Strings player inputs
WAIT = "Wait"
CLIMB = "Climb"
CHECK = "Check"
ROLL = "Roll"
#Strings world situations
ALIVE = "You are alive"
#Strings narrator outputs
#Initialization of variables
player_avai... |
'''
소수 찾기 코드
가장 기본적인 내용만을 사용한 파이썬 코드
(1과 자기 자신의 수 외의 수로 나눠지는 경우 소수가 아님을 활용하여
입력된 특정한 숫자 하나가 소수인지 아닌지 판별하는 단순한 코드)
'''
def FindPrime(x):
for i in range(2, x):
if(x % i == 0):
return False
return True
print(FindPrime(67))
|
import eng
class Bar:
name = 'Bar'
visited = False
visible = False
aliases = []
descriptions = {'shortDesc': "You're in the bar again. People are still enjoying conversation and drinks. There are exits to the south and west, and a door to the east leading outside. ",
'longDesc': "You've found a bar... |
if __name__ == '__main__':
n = int(raw_input())
arr = map(int, raw_input().split())
max = max2 = None
for x in arr:
if x == max:
max2 = max2
elif x > max:
max, max2 = x, max
elif x > max2:
max, max2 = max, x
print max2 |
from os import path
from flask.ext.uploads import (UploadSet, configure_uploads, AllExcept, SCRIPTS,
EXECUTABLES)
from flask.ext.wtf import (Form, TextField, TextAreaField, BooleanField,
SelectField, RadioField, PasswordField, FileField,
... |
from tkinter import *
from tkinter import messagebox
def CleanJavab(labl):
labl.config(text="")
labl.update()
def Add(labl,txt):
g = labl['text']
labl.config(text=g + txt)
labl.update()
def Remove_a_Number(label):
g = label['text']
resualt = ""
if(len(g) > 0):
for i,... |
from view.resources.top_five_view import TopFive
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QDialog, QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget
class EmployeeGrid(QWidget):
"""QWidget to present the employees tab
"""
def __init__(self, db_controller):
super().__init__... |
# for i in range(1,10):
# if (i<4) :
# print(i)
# elif (i>7) :
# print("우리집강아지")
# else :
# print("복슬강아지")
# a = 1
# while a <= 10:
# if a % 2 == 0 :
# print(a)
# a = a + 1
# print("sum =", "sum")
# a=10
# while True :
# print(a)
# a = a + 1
# if a > 10... |
# -*- coding:utf-8 -*-
r"""Identify objects
This module provides a object to represent all Senators and Federal Deputies elected in previously elections, with his
unique identifiers based on a .csv file located in IDENTITY_FILE location.
This module also provide a way to update the content of the IDENTITY_FILE, in th... |
# coding: utf-8
# comeca com consoante
# raquel ambrozio
palavra = ""
palavras = []
comeca_consoantes = 0
while palavra != "***":
palavra = raw_input()
if palavra[0] not in "AaEeIiOoUu*":
comeca_consoantes += 1
print "Palavras: %d" % comeca_consoantes
|
N = int(input())
S = input()
T = 'b'
i = 0
len_T = 1
while len_T < N:
i += 1
r = i % 3
if r == 1:
T = 'a' + T + 'c'
elif r == 2:
T = 'c' + T + 'a'
else:
T = 'b' + T + 'b'
len_T += 2
if len_T != N or S != T:
print(-1)
else:
print(i)
|
########################################
### IMPORT MODULES ###
########################################
import pandas as pd
import googlemaps
gmaps = googlemaps.Client(key='AIzaSyAj5JExaDTeWni5CWXLr8AK4j6Bh8EJDAk')
########################################
### LOOP THROUGH BOROUGHS ###
##############... |
print 'What do you get when you cross a snowman with a vampire?'
raw_input()
print 'Frostbite!'
raw_input()
print 'What do desntists call an astronaut\'s cavity?'
raw_input()
print 'A black hole!'
raw_input()
print 'Knock knock'
raw_input()
print 'Who\'s there?'
raw_input()
print 'Interrupting cow'
raw_input()
print 'I... |
from base import Pedsnet_base, Pcornet_base
from sqlalchemy import Column, Integer, String, Numeric, Date, TIMESTAMP, Float
class DeathPedsnet(Pedsnet_base):
__tablename__ = 'death'
# placeholder schema until actual schema known
__table_args__ = {'schema': 'pedsnet_schema'}
cause_concept_id = Column(... |
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
#
# 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 applicab... |
# -*- coding: utf-8 -*-
__author__ = "radek.augustyn@email.cz"
if __name__ == "__main__":
import sharedtools.log as log
log.createLogger("Deploy")
import argparse
from updatemode import UPDATE_MODE
from config import Config
from directoryprocessor import DirectoryProcessor
parser = argpa... |
import numpy as np
import operator
def itemgettergeneral(keys,listdict, cast_to_np_array=False):
"""itemgettergeneral accept a single key or a iterable? and extract
from list of dict listdict.
Due to numpy ufunc limitatation (Cannot construct a ufunc with more
than 32 operands) we switch from np,vec... |
"""
logic operation
and, or, not
T: True
F: False
T and T = T
T and F = F
F and T = F
F and F = F
T or T = T
T or F = T
F or T = T
F or F = F
not T = F
not F = T
"""
def logic_and(a,b):
return a and b
def logic_or(a, b):
return a or b
def logic_not(a):
return not a
|
import random
myList=['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg', 'hh', 'ii', 'jj', 'kk', 'll']
print 'This is my list= ', myList
print
randomIndex=random.randint(0, len(myList)-1)
print 'this is my random index= ', randomIndex
currentIndex=randomIndex
while True:
if randomIndex in range(0,len(myList)):
curr... |
from django.contrib import admin
# Register your models here.
from porters.models import Porter
class PorterAdmin(admin.ModelAdmin):
pass
admin.site.register(Porter, PorterAdmin)
|
import time
score = 0
name = str(input("What's your name? "))
print("Welcome, " + name + " to the quiz!\n")
def score_plus():
global score
score += 1
print("Your score: ", score)
def score_minus():
global score
score -= 1
print("Your score: ", score)
def q1():
print("\n1. What is El ... |
from django.conf.urls import url
from . import views
app_name = 'chat'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^about/', views.AboutView.as_view(), name='about'),
url(r'^pusher_auth/', views.pusher_auth, name='pusher_auth'),
url(r'^find_users/$', views.find_users, name='find_users... |
'''
Sequential Search
**Computational complexity**:
- best case = 1
- Worst Case = n
- Average Case = n/2
**Advantages**:
- Simple
- small data
**Disadvantages**:
- high computational complex
- big data is slow
- inefficient
'''
def busca_sequencial_for(lista, valor_procurado):
for i in range(len(lista... |
import tkinter as tk
import tkinter.messagebox as messagebox
from tkinter import StringVar
from jiami import *
from test import Post, test_token
import os
app = tk.Tk()
app.title('到梦空间')
app.geometry('1060x800')
tk.Label(app, text='User name:', font=('Arial', 14)).place(x=10, y=0)
tk.Label(app, text='Password:', font... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(executable_path='./chromedriver')
driver.get("http://tutorialsninja.com/demo/")
driver.close()
search_field = driver.find_element_by_name("search")
pass |
import logging
from cached_property import cached_property
from django.conf import settings
import requests
logger = logging.getLogger(__name__)
# NOTE: geonames code adapted and extended from winthrop project; will need
# to be spun off into its own library at some point down ther oad
class GeoNamesError(Excepti... |
message = "This is a simple message"
print(message)
message = "This is an another simple message"
print(message) |
#!/usr/bin/env python
# coding: utf-8
# ## Module 2
#
# #### In this assignment, you will work on movie data from IMDB.
# - The data includes movies and ratings from the IMDB website
# - Data File(s): imdb.xlsx
#
# #### Data file contains 3 sheets:
# - “imdb”: contains records of movies and ratings scraped from IMDB... |
def magical_string(n):
string = string_gen(n)
return string.count('1')
def string_gen(n):
start = '122'
i = 2
alt = '1'
while len(start) < n:
if start[i] == '2':
start += alt * 2
else:
start += alt
if alt == '1':
alt = '2'
... |
# -*- coding: utf-8 -*-
'''
Created on 9 may. 2017
@author: jose
'''
import psycopg2
import time
def consulta (conn,sql):
cur=conn.cursor()
cur.execute(sql)
rows = cur.fetchall()
return rows
def ObtieneTipoTabla (tipo):
if tipo=='r':
cod='TBL'
else:
cod='VST'
... |
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.contrib.staticfiles import finders
import os
import urllib2 # the lib that handles the url stuff
def index(request):
return HttpResponse("Hello, world. You're... |
import unittest
import math
import copy
from model.basic_operation import *
class TestAtma(unittest.TestCase):
def setUp(self) -> None:
self.mat = torch.tensor([[1.0, 1.0], [0.0, 1.0]])
self.batch_mat = self.mat.unsqueeze(0)
self.result = [[1.0, 1.0], [1.0, 2.0]]
def test_mat_multip... |
import csv
from .models import FinancialData, StatsData
def import_financial_data(request):
available_data = []
with open('/Users/Hannan/Documents/Projects/analytics_assistant/virtual_analyst/static/csv/2013.csv', 'r') as f:
rows = csv.reader(f)
headers = next(rows)
for row in rows:
... |
def hardestProblem(a, b, c):
if c<b and c<a:
print('Alice')
elif b<c and b<a:
print('Bob')
else:
print('Draw')
try:
t = int(input())
while t>0:
t -= 1
a, b, c = map(int, input().split())
hardestProblem(a, b, c)
except:
pass
|
a=[3,8,9,7,6]
b=3
c=b-1 #2
# key=a[0]
print(len(a))
output=[]
for i in range(0,len(a)):
if i<=c:
output.append( a[i+c])
# a[i-1]=a[i]
else:
output.append(a[i-b])
print(a)
print(output)
# key2=a[0]
# for j in range(0,len(a)):
# if j<len(a)-1:
# a[j]=a[j+1]... |
from ortools_op import SolveMaxMatching
import numpy as np
def results2objective(results, nworkers, ntasks):
objective = np.zeros([nworkers, ntasks])
for i,j in results: objective[i][j]=1
return objective
def test1():
'''
Results :
unary potential :
[[ 0.89292312 0.64831936 0.56726688 0.1320... |
i = 0
while i < 4:
if i > 2:
print(i)
elif i < 1:
print(i)
else:
print('hey')
i += 1
|
from dataclasses import dataclass
from typing import Callable
class Car:
"""
Generic car class
"""
def __init__(self, name: str, released_year: int, manufacturer: str, is_ev: bool, battery_range: int):
self.name = name
self.released_year = released_year
self.manufacturer = manu... |
string = input("Setning: ")
for char in string:
if char == "," or char == "." or char == '"' or char == "'" or char == "-" or char == "!":
string = string.replace(char,"")
print(string) |
from django.db import models
# Create your models here.
class Currencies(models.Model):
fullName = models.CharField(max_length=200)
Sign = models.CharField(max_length=200)
isActive = models.CharField(max_length=200)
updated_at = models.CharField(max_length=200)
created_at = models.CharField(max_len... |
#发送广播
from socket import *
import time
#广播地址
dest=("localhost",6666)
s=socket(AF_INET,SOCK_DGRAM)
s.setsockopt(SOL_SOCKET,SO_BROADCAST,1)
data="""asdfk
********************************
tarena@tarena:~$ ifconfig
enp2s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 172.40.74.131 netmask 255.255.25... |
import pandas as pd
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.metrics import confusion_matrix
def pca_dim_reduction(x_train, x_test, total_variance = 0.95):
"""
Use PCA Transform To Extract Uncor... |
try:
from _jep import *
except ImportError:
raise ImportError("Jep is not supported in standalone Python, it must be embedded in Java.")
from .version import __VERSION__, VERSION
from .java_import_hook import *
from .shared_modules_hook import *
|
# Standard libs:
import sys, re, os, pickle, copy, time, traceback, webbrowser
from optparse import OptionParser
from math import floor
from types import ListType
# BioPython modules:
from Bio.Nexus import Nexus, Trees, Nodes
from SAP import Fasta
# Custom modules:
from SAP import MachinePool, SGE, Options
from SAP... |
def f(x):
return x*x + 2*x
def fdx(x):
return 2*x + 2
#中点法,f为搜索的函数,fdx为f的导函数,interval 为搜索的区间
def MidPointMethod(fdx,interval):
e = 10**-8
a = float(interval[0])
b = float(interval[1])
while 1:
lambda_ = (a + b)/2
fdxl = fdx(lambda_)
if abs(fdxl) < e:
break
... |
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input
from tensorflow.keras.applications import ResNet152V2
from tensorflow.keras.applications.resnet_v2 import preprocess_input
from . import _utils
MODEL_NAME = 'resnet152v2'
IMAGE_SIZE = 224
def load_model(model_version = 'default'):
... |
# Generated by Django 2.2 on 2021-06-18 12:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('produccion', '0008_auto_20210617_1959'),
]
operations = [
migrations.AddField(
model_name='catanimal',
name='det',
... |
import pygame
import numpy as np
import tkMessageBox
import math
import collections
class Mark:
""" Mark class for action of placing a mark on screen and checking for win
Attributs:
screen (pygame surface)
length (int/float) representing radius for a circle or width for a line
... |
# -*- coding: utf-8 -*-
"""
@author: Kotarou
"""
from entity import Component
from pyglet.window import key
from .KeyComponent import *
class KeyPressComponent(KeyComponent):
# def __init__(self, key, string="Whatever!"):
# self.response = string
# self.key = key
# self.hoverTime = 0
#... |
'''
No Crypto (Crypto 200)
The folowing plaintext has been encrypted using an unknown key, with AES-128 CBC:
Original: Pass: sup3r31337. Don't loose it!
Encrypted: 4f3a0e1791e8c8e5fefe93f50df4d8061fee884bcc5ea90503b6ac1422bda2b2b7e6a975bfc555f44f7dbcc30aa1fd5e
IV: 19a9d10c3b155b55982a54439cb05dce
How would you modify ... |
import math as m
import matplotlib.pyplot as plt
import numpy as np
import scipy.sparse as sp
from matplotlib.collections import LineCollection
from scipy import spatial
plt.rcParams['figure.figsize'] = [5, 3]
filename = "SampleCoordinates.txt"
radius = 0.06
def read_coordinate_file(filename):
... |
import cv2
import pickle
data = pickle.load(open("/Users/balazs/real_data/data_training.pkl", 'rb'))
for image, truth in data:
if len(truth) > 50:
print(truth)
cv2.imshow("image", image)
cv2.waitKey(0) |
#!/usr/bin/python
print "Content-type: text/html"
print
#print "<pre>"
import cgitb
import cgi
from osgeo import gdal,ogr
import struct
cgitb.enable()
form = cgi.FieldStorage()
mx = float(form.getvalue('lon'))
my = float(form.getvalue('lat'))
rast='/var/www/html/CartoLabFS16/Carto-Lab-Terroni/Map/Data/wellington5m.tif... |
import re
sentences = []
with open('../../../data/nlp.txt', mode='r') as f:
sentences.extend(re.split(r'[.;:?!]\s+(?=[A-Z])', f.read().strip()))
if __name__ == '__main__':
for sentence in sentences:
print(sentence)
|
# import calendar
import common
import sfc_netconf_regression_messages as sfc_nrm
import subprocess
import argparse
import time
import requests
__author__ = "Reinaldo Penno"
__author__ = "Andrej Kincel"
__copyright__ = "Copyright(c) 2014, Cisco Systems, Inc."
__license__ = "New-style BSD"
__version__ = "0.3"
__email__... |
from lazysql import Base, update_all, viewtable, db
class User(Base):
__tablename__ = 'users'
user_id = ('SERIAL', 'PRIMARY KEY')
username = ('varchar(256)', 'NOT NULL')
class Post(Base):
__tablename__ = 'posts'
post_id = ('SERIAL', 'PRIMARY KEY')
text = ('varchar', 'NOT NULL')
update_all()... |
"""
Number of Paths
You’re testing a new driverless car that is located at the Southwest (bottom-left) corner of an n×n grid.
The car is supposed to get to the opposite, Northeast (top-right), corner of the grid. Given n, the size of the grid’s axes,
write a function numOfPathsToDest that returns the number of the poss... |
"""Exemple of handling callback from cyphernode"""
from libcn.libcn import CallbackServer
import json
class WaitCallback(CallbackServer):
"""Exemple of using 'CallbackServer' class for handling callbacks and execute actions.
Each functions must reflect the callbacks url used in cyphernode callbacks config.
... |
import json
import pickle
import sys
import getopt
from os import listdir
from os.path import isfile, join
import random
import pandas as pd
def checkinexclusion(nodename):
with open('./nodes/exclusion.nodes', 'r') as nodelines:
for x in nodelines.readlines():
# print(nodename)
if ... |
def hpaste():
import vim, sys, urllib, urllib2
enc = vim.eval('&fileencoding') or vim.eval('&encoding')
code = vim.eval('l:code').decode(enc, 'ignore').encode('utf-8')
title = vim.eval('input("Title: ")')
if not title:
print 'aborted'
return
author = vim.eval('s:GetHPasteAutho... |
n = int(input())
plist = []
for _ in range(n):
p = int(input())
plist.append(p)
print(sum(plist) - max(plist)//2)
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.animation as animation
fig, ax = plt.subplots()
xdata, ydata, xmydata, ymydata = [], [], [], []
ln1, = ax.plot([], [], 'b-')
ln2, = ax.plot([], [], 'r-')
data_spain_ccaa = pd.read_cs... |
#!/usr/bin/python
def displayPathtoPrincess(n,grid):
botp = [-1, -1]
prinp = [-1, -1]
for x in range(0, n):
for y in range(0, n):
z = grid[x][y]
if z == 'm':
botp[0] = x
botp[1] = y
if z == 'p':
prinp[0] = x
prinp[1] = y
#print("botp:", botp[0], botp[1])
#print("prinp:", prinp[0], prinp... |
# Copyright 2015, Pinterest, 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 law or agreed to in writ... |
from django import forms
from django.forms import ModelForm
from .models import Profile
from django.contrib.auth.models import User
class CreateUserForm(forms.Form):
Username = forms.CharField(max_length=20, label='Nombre de Usuario:')
Password = forms.CharField(max_length=10, label='Password: ', widget=forms.... |
<h1>Mon titre principal</h1>
<h2>Mon titre de section</h2>
<h3>Mon sous-titre</h3>
<h4>Mon sous-sous-titre</h4> |
# project euler problem #2
# find sum of even valued fibonacci numbers
# more list comprehension go brrrrrrrrrrrrr but with more steps
# basically build a fibonacci generator then list comprehension it
def fib(n):
f1, f2 = 1, 2
# try to generate up to n + 1 since we know that the sequence will outgrow n before... |
class Task:
def __init__(self, task, answer):
self.task = task
self.answer = answer
def get_task(self):
return "Your task is: {}".format(self.task)
def get_answer(self):
return "The correct answer is: {}".format(self.answer)
|
#!/usr/bin/python
#######################################################
# Copyright (c) 2015, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
####################################... |
def inicstr(str_data):
d = {}
if len(str_data) > 0:
lst = str_data.split('/')
if len(lst) > 3:
|
def getModeForParam(pos, data, ins):
if pos == 1:
return (data[ins] % 1000) // 100 is 1
if pos == 2:
return data[ins] // 1000 is 1
def getParamByMode(pos, data, ins):
if getModeForParam(pos, data, ins):
return data[ins + pos]
else:
return data[data[ins + pos]]
def set... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-01-31 05:12
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rcapp', '0006_recordings_device'),
]
operations = [
migration... |
def findOne(strrr):
return strrr.index('1')
def checkRemainder(inputString, divisor):
global flag
crcAdded = list(inputString)
# crcAdded = crcAdded + list('0'*(len(crc_32)-1))
lenInput = len(inputString)
lenDivisor = len(divisor)
while '1' in crcAdded[:lenInput]:
latestOne = fin... |
import os
import numpy as np
import torch
from torch.utils.data.dataset import Subset
from torchvision import datasets, transforms
import json
from utils.utils import set_random_seed
DATA_PATH = '~/data/'
IMAGENET_PATH = '~/data/ImageNet'
CIFAR10_SUPERCLASS = list(range(10)) # one class
IMAGENET_SUPERCLASS = list(... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 1 09:43:17 2017
@author: casari
"""
master_params_1_0_0 = [{'name': 'System','type':'str','value':'MASTER'},
{'name':'PMEL Serial Number','type':'str','value':'XXXXXXXXXX'},
{'name':'Firmware Version','type':'str','value':'XXXXXXXXXX'}]
com_params_1_0_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.