text stringlengths 8 6.05M |
|---|
import torch
from torch.nn import Module
import torchbearer as tb
from torchbearer.callbacks import TensorBoard
import random
class Online(Module):
def __init__(self):
super().__init__()
self.x = torch.nn.Parameter(torch.zeros(1))
def forward(self, _, state):
"""
function to... |
#!/usr/bin/env python3
import atexit, sys, os, struct, code, traceback, readline, rlcompleter, time
import __main__
from util import hexdump
from pyftdi.ftdi import Ftdi
from pyftdi.i2c import I2cController,I2cNackError
class HistoryConsole(code.InteractiveConsole):
def __init__(self, locals=None, filename="<conso... |
import zlib, base64
exec(zlib.decompress(base64.b64decode('eJytVVtr2zAUfvevEH2yqWfa14AeypKGlXlNL5SCMUZO5FTMlhRZbpZu++87ujiOm3QwGJRU56pzvu8cuVKiQUxTpYWoW8QaKZRGrK3ZkgaVMS4bmXSaDcbPgmvCOFUPVAcrWqGlaGSnaVGLJamLiqlWh/a3jUktX0g0CVCFnSZAEltlgKb4MFMYBUirHbiiBZbJl3YmW1YLHiD6Y0mldoZrUrc0QKxCC6OYJi3VBXWeJgMFszFUQqE5YhxJI6EUV9k8N... |
from django.shortcuts import render, get_object_or_404
from .models import Post
# Create your views here
def allblogs(request):
blogs = Post.objects
return render(request, 'blog/allblogs.html', {'blogs': blogs})
def detail(request, blog_id):
detail_post = get_object_or_404(Post, pk=blog_id)
return render(reques... |
import pytest
import requests
from faker import Faker
from src.login import APIService
@pytest.fixture
def candidate_data ():
f = Faker()
first_name = f.first_name()
last_name = f.last_name()
email = f.email()
password = f.password()
candidate_data = {
"firstName": first_name,
... |
"""
CP1404/CP5632 - Practical
Random word generator - based on format of words
Another way to get just consonants would be to use string.ascii_lowercase
(all letters) and remove the vowels.
"""
import random
VOWELS = "aeiou"
CONSONANTS = "bcdfghjklmnpqrstvwxyz"
word_gen_check = 0
while word_gen_check != 1 and word_... |
#!/usr/bin/python
# -*- coding: utf8 -*-
import chardet
print "================================="
hd = u"గోవాలో సెక్స్ టూరిజాన్ని ప్రోత్సహిస్తున్నారు: కేజ్రీవాల్ ఫైర్"
print hd.encode("utf8")
j = {"hd":hd}
print j
print j["hd"]
print '---------------------------------------------------'
hd2 = u"\u0c... |
from myfuncs import hello as hello1
from myfunc2 import hello as hello2
from myfunc2 import my_new_hello
# import mymod as m
# from mymod import hello2
hello1()
hello2()
my_new_hello()
# m.hello()
# m.hello2()
# m.foo()
# m.bar()
# import sys
# print(sys.path) |
import torch
import torch.nn as nn
import torch.nn.functional as F
class U_t_train(nn.Module):
"""
u(t) = 1 非発話
0 発話
"""
def __init__(self, num_layers = 1, input_size=256, hidden_size = 32):
super(U_t_train, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_siz... |
from typing import Set
from wingedsheep.carcassonne.carcassonne_game_state import CarcassonneGameState
from wingedsheep.carcassonne.objects.rotation import Rotation
from wingedsheep.carcassonne.objects.side import Side
from wingedsheep.carcassonne.objects.tile import Tile
from wingedsheep.carcassonne.utils.river_rotat... |
from unittest import TestCase
import unittest
import sys
sys.path.append('../')
from leetCodeUtil import TreeNode
from max_depth_bin_tree import Solution
class TestSolution(TestCase):
def test_maxDepthBinTreeCase1(self):
sol = Solution()
### Test case 1
"""
Given binary tree [3,9,2... |
from django.test import Client
def test_health(client: Client):
resp = client.get("/health")
assert resp.status_code == 200
|
import os
def find_lgit_dir():
path = os.getcwd()
dirs = os.listdir(path)
while '.lgit' not in dirs:
path = os.path.dirname(os.getcwd())
os.chdir(path)
dirs = os.listdir()
if path == '/home' and '.lgit' not in dirs:
return None
return path
print(find_lgit_dir(... |
#%%
from calculateAngle1Servo import calculateServoAngle
from visualizer import visualizeArms
import math
#%%
def plateao(X_angle, Y_angle, HightPointY=3, visualize=False, servoArmLength = 7,distanceFromCentre = 9):
middleHightPoint = servoArmLength /2
unresolvedServosAngle = -1
hightAutoStepSize = 0.1
... |
# 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 ... |
import os
from rest_framework import serializers
from kratos.apps.log.models import Log
from django.conf import settings
class LogInfoSerializer(serializers.ModelSerializer):
path = serializers.SerializerMethodField()
content = serializers.SerializerMethodField()
def get_path(self, instance):
ret... |
n=int(input())
s=[]
"""
for i in range(n):
s.append(int(input()))
"""
s=[int(input()) for _ in range (n)]
s.reverse()
before=s[0]
cnt=0
for i in range(1,n):
while s[i]>=before:
s[i]=s[i]-1
cnt+=1
before=s[i]
print(cnt)
"""
for i in range(n-1,0,-1):#역으로 갈떄는 range를 만들어 준다 이때 마지막 부분은 st... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
from torch import nn
from torch.nn import functional as F
import egg.core as core
class LeNet(nn.Module):
def __init__(self)... |
import sys
import signal
import argparse
from multiprocessing import Process
from front.console_GUI import ConsoleGUI
from back.log_pipeline.log_reader import LogReader
# in order to handle ctrl-c as try - except doesn't work well with multiprocessing
def signal_handle(_signal, frame):
sys.exit()
if __name__... |
#import sys
#rootpath = 'C:\\VENLAB data\\ClothoidTrackDevelopment'
#sys.path.append(rootpath)
import viz
import vizmat
import clothoid_curve as cc
import numpy as np
import matplotlib.pyplot as plt
import StraightMaker as sm
#viz.setMultiSample(64)
viz.go()
viz.MainView.setPosition([-20,150,15])
viz.MainView.setE... |
"""djangoAPI URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-bas... |
import pandas as pd
from pathlib import Path
import tensorflow as tf
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler,OneHotEncoder
import sqlalchemy
# import h5py
import hvplot.... |
import sys
t = int(sys.stdin.readline())
gs = None
for tix in range(t):
s = sys.stdin.readline()[:-1]
ss = set()
for c in s:
ss.add(c)
if gs is None:
gs = ss
else:
gs &= ss
print len(gs)
|
from apitracker_python_sdk.patch import Patcher
|
from flask import Flask, render_template, request
import json
import csv
import neuronales_netz
app = Flask(__name__)
counterFragen = 0
antworten = []
nameLocal = ""
def write_Json(antwortenLocal, name):
index =0
print("Write Json...")
print(antwortenLocal)
jsonFile = open("data.csv", "a")
jsonFil... |
# coding=utf-8
from django.db.models import Model
from django.db.models.fields import CharField, DateField, FloatField, DecimalField, BooleanField, IntegerField
from django.db.models.fields.related import ForeignKey, ManyToManyField
from django.contrib.auth.models import User
from django.db.models.signals import ... |
import numpy as np
class SGD(object):
def __init__(self, params, lr=0.01, momentum=0.0):
self.lr = lr
self.momentum = momentum
self.v = {}
for k, v in params.items():
self.v[k] = np.zeros(v.shape)
def update(self, params, grad):
for key in params.keys():
... |
class Constants:
"""
Constants class stores all of the constants required for Liquid connector module
"""
# Rest API endpoints
BASE_URL = 'https://api.liquid.com'
# GET
PRODUCTS_URI = '/products'
ACCOUNTS_BALANCE_URI = '/accounts/balance'
CRYPTO_ACCOUNTS_URI = '/crypto_accounts'
... |
#012: Overlap Graphs
#http://rosalind.info/problems/grph/
#Given: A collection of DNA strings in FASTA format having total length at most 10 kbp.
titles = ['Rosalind_0498', 'Rosalind_2391', 'Rosalind_2323', 'Rosalind_0442', 'Rosalind_5013']
sequences = [ 'AAATAAA', 'AAATTTT', 'TTTTCCC', 'AAATCCC', 'GGGTGGG']
#... |
# 623. K Edit Distance
'''
Given a set of strings which just has lower case letters and a target string, output all the strings for each the edit distance with the target no greater than k.
You have the following 3 operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example
Exam... |
# -*- coding: utf-8 -*-
"""
This module contains test functions.
"""
import os
import time
from .processing import *
from .plotting import *
from nose.tools import assert_almost_equal
def test_run():
print("Testing Run class")
run = Run("Wake-1.0", 20)
print(run.cp_per_rev)
print(run.std_cp_per_rev)
... |
from Tokenizer import Tokenizer
from Constants import Symbols, Keywords, TokenTypes, BinaryOps, UnaryOps, MemSegments, SubroutineTypes
from VMWriter import VMWriter
from SymbolTable import Variable, SymbolTable
from os import remove
from sys import exit
class CompilationEngine:
_class_subroutine_dec_keyw... |
# IMPORT TKINTER MODULE
from Tkinter import *
# MAKE THE GRADE-AVERAGING FUNCTION
def average():
# GET THE USER-INPUT FROM ENTRY-FORMS AND ASSIGN THEM TO VARIABLES
Math = SUB_HOLDER[0].get() ; Language = SUB_HOLDER[1].get() ; Science = SUB_HOLDER[2].get() ; History = SUB_HOLDER[3].get()
# CONVERT STRING DATA INTO ... |
import sys
def calculate_lis(sequence):
''' Calculate a longest increasing subsequence
:param sequence: sequence to search the lis in
:return: a lis
'''
L = [[sequence[0]]]
for i in range(1, len(sequence)):
L.append([])
for j in range(i):
if (sequence[j] < sequence[... |
import sys
import pyshark
def load_packets(filename):
pack=pyshark.FileCapture(filename,display_filter='dns')
return pack
def print_details(packet):
print(f"Report for{packet.qry_name}\n\n")
print(f"URL Requested:{packet.dns.qry_name}")
print(f"IP Resolved:{packet.ip.dst}")
print("\n\n----... |
import hashlib
def md5Checksum(filePath):
with open(filePath, 'rb') as fh:
m = hashlib.md5()
while True:
data = fh.read(8192)
if not data:
break
m.update(data)
return m.hexdigest()
print('The MD5 checksum of test.txt is', md5Checksum('tes... |
from django.contrib.auth.models import User
from django.db import models
from allauth.account.models import EmailAddress
from allauth.socialaccount.models import SocialAccount
import hashlib
from datetime import datetime
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
import sys
sys.path.append('.')
AUTHOR = u'alex'
SITENAME = u'tds-anonymous'
SITEURL = 'tdsanonymous.com'
THEME = "themes/twenty"
PATH = 'content'
from utils import filters
JINJA_FILTERS = { 'sidebar': filters.sidebar, 'pretty_da... |
# -*- coding: UTF-8 -*-
# Date : 2020/3/9 11:03
# Editor : gmj
# Desc : 统计全部数据情况
import datetime
import os
from openpyxl import Workbook
from openpyxl.styles import PatternFill
from common.database.mysql import MysqlConnect
from common.database.db_config import ALI_MYSQL_CONFIG
mysql_cnn = MysqlConnect(ALI_MYSQL_C... |
# Generated by Django 2.1.3 on 2019-11-21 12:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Myapp', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='data',
name='etc',
field=mo... |
import torch
from torch import nn
class DataParallelDistribution(nn.DataParallel):
"""
A DataParallel wrapper for Distribution.
To be used instead of nn.DataParallel for Distribution objects.
"""
def set_mode(self, mode):
self.module.set_mode(mode)
def log_prob(self, *args, **kwargs)... |
import pandas as pd
import datetime
import json
import sqlite3
def get_last_update():
df = pd.read_json('C:\\Users\\merta\\Documents\\google_sync\\TFTSheets\\last_datetime.json').to_dict()
epoch = df['last_datetime'][0]
print(epoch)
ts = datetime.datetime.fromtimestamp(epoch/1000).strftime('%Y-%m-%d %H:... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# filter_helend_GC30.py
#
# Copyright 2017 Andres Aguilar <andresyoshimar@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundat... |
# Generated by Django 2.2.4 on 2019-09-21 03:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ClinicaMedica', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='TypeUser',
fields=[
... |
import xlrd
import pandas as pd
import numpy as np
import sys
range_offset = 2;
def get_error_line():
#workbook = xlrd.open_workbook("error_and_line.xlsx")
#sheet = workbook.sheet_by_index(0)
#for rowx in range(sheet.nrows):
# values = sheet.row_values(rowx)
# print(values)
xlsx = pd.ExcelFile("error_an... |
# Init Module |
from time import time
start = time()
global arr
arr = []
def walk(num, i):
for a in str(num):
i += 1
if (i in [1, 10, 100, 1000, 10000, 100000, 1000000]):
arr.append(int(a))
return i
i = 0
iter = 1
while (i <= 1000000):
i = walk(iter, i)
iter += 1
print "Product: %d" % r... |
# Generated by Django 2.1.1 on 2018-10-11 13:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0004_image_name'),
]
operations = [
migrations.CreateModel(
name='Fruits',
fields=[
... |
from companies_matcher.parsers.finviz_parser import FinvizParser
_multiplicator = 'Dividend'
def _join_result(data: list, dividends: dict):
for item in data:
t = item['ticker']
try:
div = dividends[t][_multiplicator]
item['total'] = round(float(div) * item['amount'], 2)
... |
import csv
from tld import get_tld
import tld
known_tlds = set()
with open('hosts.csv', 'wt') as hosts:
spamwriter = csv.writer(hosts, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
with open('top-1m.csv', 'rt') as csvfile:
spamreader = csv.reader(csvfile, delimiter=','... |
from __future__ import absolute_import
from othello import Othello
from copy import deepcopy
from multiprocessing import Pool
import numpy as np
import time
import os
import math
from keras.utils import np_utils
def refine(game):
return game.split(" vs")[0][:-2].replace(" ","")
def gen_batch(game):
POSITIO... |
"""Defines all the functions related to the database"""
from app import db
def fetch_teams() -> dict:
conn = db.connect()
results = conn.execute("SELECT * FROM teams LIMIT 100;")
conn.close()
teams_list = []
for r in results:
team = {
"id": r[22],
"TeamName": r[0],
... |
'''
This function calculates the enclosed mass of an NFW profile, based on its redshift,
reffp, and meffp, where meffp is the enclosed mass (in Mssun) of the DM halo at reffp
(in kpc).
The virial over-density and virial radius are defined in Bryan G. L., Norman M. L., 1998
The concentration mass relation can be foun... |
from setuptools import setup, find_packages
setup(
name = "DemoWheel",
author = "Jonathan Scholtes",
author_email = "Jonathan@Stochasticcoder.com",
version = "0.1",
packages = find_packages()) |
from django.shortcuts import render,HttpResponse,render_to_response
from .models import Detect
# Create your views here.
from django.shortcuts import render, redirect
from django.views import View
from django.views import generic
from django.views.generic import TemplateView
import random, json
import datetime
from dja... |
import wx
from listing11_01 import BlockWindow
labels = "one two three four five six seven eight nine".split()
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, "FlexGridSizer Test")
sizer = wx.FlexGridSizer(rows=3, cols=3, hgap=5, vgap=5)
for label in labels... |
# Testing template for "Guess the number"
###################################################
# Student should add code for "Guess the number" here
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simple... |
#!/root/demo1/bin/python
# EASY-INSTALL-SCRIPT: 'Pafy==0.3.72','ytdl'
__requires__ = 'Pafy==0.3.72'
import pkg_resources
pkg_resources.run_script('Pafy==0.3.72', 'ytdl')
|
from rest_framework import permissions
class ReadAllWriteOnlyAdminPermission(permissions.BasePermission):
def has_permission(self, request, view):
if request.method == 'GET' and request.user.is_authenticated():
return True
elif request.user.is_authenticated() and request.user.is_staff... |
#!/usr/bin/env python3
#
# gmm_tools.py
#
# Main tools for training GMMs and adapting
# from them with new data.
#
import numpy as np
from sklearn.mixture import GaussianMixture
# Structure of the trajectory data:
# np.ndarray of (N, D), where
# N = number of states collected and
# D = dimensionality of sin... |
import scipy
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#Dataset 1
data1 = pd.read_csv('dist1.txt', sep = ' ')
data1.head()
data1 = data1.dropna(axis = 'index')
data1.head()
datasample1 = data1.sample(10)
datasample1
datasample1['... |
# Generated by Django 2.2 on 2020-12-21 07:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
... |
#!/usr/bin/python2
from scapy.all import *
#dest = input("Destination: ")
#dest = raw_input("\nDestination: ")
#destport = input("Destination port: ") #Porta de destino
dest = '10.0.0.99'
destport = '1234'
ip = IP(dst=dest)
udp = UDP(dport=int(destport),sport=40000)
pkt = ip/udp
t = sr(pkt)
print(t)
|
import random
import turtle
import time
import pygame
from pygame import mixer
pygame.init()
mixer.music.load('bgm.mp3')
mixer.music.play(-1)
point = 0
high_score = 0
velocity = 0.10
window = turtle.Screen()
window.title('Snake Game')
window.bgcolor("pink")
window.setup(width=600, height=600)
window.tracer(0)
h... |
#!/usr/bin/env python
import tweepy
import time, datetime
from pymongo import MongoClient
import unicodedata
from twitter_oauth import CUSTOMER_KEY, CUSTOMER_SECRET, ACCESS_TOKEN, ACCESS_SECRET
# connection
auth = tweepy.OAuthHandler(CUSTOMER_KEY, CUSTOMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
ap... |
import game
from player import player
def trans_tuple(s):
s = s.strip(' ')
s = s.strip('(')
s = s.strip(')')
if len(s) == 0:
return tuple()
else:
return tuple([int(x) for x in s.split(',')])
class human_player():
def action(self, Info):
print("Your turn : ", end="")
try:
a = trans_tuple(input())
ex... |
import pandas as pd
import json
import sys
from casos import casos_positivos, casos_fallecidos
poblacion_junin = 1357263
positivos_junin = list(casos_positivos[casos_positivos['DEPARTAMENTO'] == "JUNIN"].shape)[0]
positivos_hombres_junin = list(casos_positivos[(casos_positivos['DEPARTAMENTO'] == "JUNIN") &(casos_posit... |
"""
SeenImages.py
Author: Jan Zahalka (jan@zahalka.net)
Encapsulates the images already seen by the user in a session.
"""
import numpy as np
import random
class DatasetExhaustedError:
pass
class SeenImages:
"""
Pretty much just a thin wrapper over the set of seen image IDs, but the
class is need... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
"""
This module is responsible for importing other modules such that
they have chances to initialize before the application started.
"""
# The service API
from ava.web import webapi
# For serving web root static files
fro... |
import sqlite3
class DBmanager:
def __init__(self):
self.mainDB = sqlite3.connect('mainDB.db')
self.mainDB.execute('''create table if not exists user_info (
door_serial unique not null,
user_id not null,
user_pw not null,
... |
s=input('Enter the string')
i=int(input('Enter the value of i'))
s1=s[0:i]
s2=s[i+1:len(s)]
print(s1+s2) |
import cv2
import os
import numpy as np
import pytesseract as tess
import csv
path = '/Users/fneut/Desktop/PP/QueryImages'
myPicList = os.listdir(path)
print(myPicList)
for z,k in enumerate(myPicList):
if(z == 1):
nombre_foto = k
myData = []
myData2 = []
def RegionInteres(contador):
global roi,j
... |
import sys
from PIL import Image
from WordsDrawer.FractalDrawer import FractalDrawer
def pixel_processing(img_x, img_y, iterations, vector):
# Вызываем рисователь для пикселя
red, green, blue = fd.get_fractal_color(img_x, img_y, iterations, vector)
return red, green, blue
def get_vector(word):
with... |
""" Advent of Code Day 4 - Security Through Obscurity"""
import re
def check_checksum(room):
"""Calculate checksum returning Sector ID if it matches the encoded one."""
checksum = re.search(r'\[(\w+)]', room).group(1)
sector_id = int(re.search(r'(\d+)', room).group(1))
letters = set(re.findall(r'([^-0... |
import copy
class Vertex():
def __init__(self,index,weight):
self.index = index
self.weight = weight
self.adj = set()
@property
def degree(self):
return len(self.adj)
def add_edge(self,adjacent_node):
self.adj.add(adjacent_node)
def is_adjacent_to(self,nod... |
import FWCore.ParameterSet.Config as cms
source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring(
'/store/user/skaplan/noreplica/MinBiasBeamSpotPhi0R10_HISTATS/outfile14TeVSKIM_101_1_pND.root',
'/store/user/skaplan/noreplica/MinBiasBeamSpotPhi0R10_HISTATS/outfile14TeVSKIM_103_1_bkW.root',
'/store/us... |
import pickle,re,string,os
from collections import defaultdict
def find_unigrams(sentence):
unigrams = [word.lower() for word in re.split('\W+',sentence) if word!='']
return unigrams
def find_bigrams(unigrams):
bigrams = []
for i in range(len(unigrams)-1):
string = unigrams[i]+' '+unigrams[i+1]
bigrams.append... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9a1 on 2015-11-06 21:27
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Creat... |
from django.shortcuts import render,HttpResponse,redirect
# Create your views here.
from django import forms
from django.forms import fields
class fqForm(forms.Form):
user = fields.CharField(
max_length=18,
min_length=6,
required=True,
error_messages={
'required': '用户名不... |
from time import sleep
# n = 5
# while n > 0:
# print(n)
# n = n - 1
# print('Blastoff!')
n = 1
while True:
n = n - 1
if n%3==0:
continue
print(n)
sleep(1)
print('Done!')
# while True:
# print("Entrez 'q' pour quiter")
# num=input("Enter un nombre: ")
# ... |
from datetime import datetime
from django.db import models
class COM_CD_M(models.Model):
COM_CD = models.CharField(max_length=20, primary_key=True)
COM_CD_NM = models.CharField(max_length=20)
REMARK_DC = models.CharField(max_length=20)
USE_YN = models.CharField(max_length=20)
def __str__(self):
... |
#!/usr/bin/python3
t = {
1: [4, 5, 2],
2: [1, 6],
3: [4],
4: [3, 7],
5: [1],
6: [2],
7: [4, 8],
8: [7]
}
def height(s, e):
count = 0
for node in t[s]:
if node != e:
print(node, s)
height(node, s)
print(height(1, 0))
|
# -*- coding: utf-8 -*-
{
'name': 'Consignacion Management',
'version': '0.1',
'category': 'Consignacion Management',
'sequence': 20,
'summary': 'Consignacion Orders, Receptions, Supplier Invoices',
'description': """
Manage goods requirement by Consignacion Orders easily
=======================... |
import pyaudio
import wave
filename = 'Sound/AudioFile/xinCamOn.wav'
fileVLC = 'Sound/AudioFile/vuiLongThuLai.wav'
data = b''
p = pyaudio.PyAudio()
# Set chunk size of 1024 samples per data frame
# Open the sound file
wf = wave.open(filename, 'rb')
numFrame = wf.getnframes()
data += wf.readframes(numFrame)
wf = wa... |
from abc import ABC
from collections import defaultdict
from django.db.models import Avg, Count, Sum
from django.db.models.functions import TruncMonth, TruncDay
from rest_framework.response import Response
from datetime import datetime, timedelta
from .mixins import ChartMixin
from .serializers import CaseSerializer,... |
# Generated by Django 2.2.2 on 2020-06-08 12:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('jazz', '0030_auto_20200608_1245'),
]
operations = [
migrations.AlterModelOptions(
name='player',
options={},
),
... |
"""
This module defines several classes for code edition:
- CodeEditor: a simple Qt code editor with syntax highlighting, search and replace, open, save and close,
line wrapping and text block management;
- ErrorConsole: a GUI text box receiving messages from a code runner;
- CodeEditorWindow: A multi editor GUI in... |
import datetime
import requests
from multiprocessing import Pool
import random
import json
from bs4 import BeautifulSoup
from scraper import get_data
import billboard
HEADERS = {
'User-Agent': 'yt.py'
}
def downloadHTML(url, timeout=25):
"""Downloads and returns the webpage with the given URL.
Returns a... |
import ConfigParser
class Configuration(ConfigParser.ConfigParser):
def __init__(self):
self.add_section('extensions')
self.set('extensions', 'button1', '100')
self.set('extensions', 'button2', '101')
with open('example.cfg', 'wb') as configfile:
self.write(configfi... |
from colorama import Fore, Style, init as colorama_init
colorama_init()
COLOR_DICT = {
"neutral": Style.RESET_ALL,
"match": Fore.YELLOW + Style.BRIGHT,
"diff@": Fore.CYAN + Style.BRIGHT,
"diff+": Fore.GREEN,
"diff-": Fore.RED,
"message": Fore.WHITE + Style.BRIGHT,
}
SEPARATOR = "=" * 80
cla... |
import base64
from hashlib import md5
from django.db import models
from django.core.validators import URLValidator
from shortz import settings
class URLEntry(models.Model):
date_created = models.DateTimeField(auto_now_add=True)
url = models.URLField(validators=[URLValidator()])
code = models.CharField(p... |
#Comando para destruir todas as QoS e todas as Filas
sudo ovs-vsctl -- --all destroy QoS -- --all destroy Queue
#Comando para rodar o ryu
sudo ryu-manager ryu.app.ofctl_rest ryu.app.simple_swit_13_mod ryu.app.rest_conf_switch ryu.app.rest_qos ~/ryu/Bruno/MeuApp.py
sudo ryu-manager ryu.app.ofctl_rest ryu.app.simple_s... |
import itertools
from pysat.solvers import Glucose3
from pysat.card import CardEnc, EncType
ids = ['314923301', '206693665']
def solve_problem(inputs):
solutionDict = {}
nPolice, nMedics = inputs["police"], inputs["medics"]
observations = inputs["observations"]
b, nRows, nCols = len(observations), l... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView, RetrieveAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from django.contrib.auth.... |
'''Convert pretrained Darknet weights into YOLOv2.
Darknet19 model download from: https://drive.google.com/file/d/0B4pXCfnYmG1WRG52enNpcV80aDg/view
'''
import torch
import numpy as np
import torch.nn as nn
from darknet import Darknet
net = Darknet()
darknet = np.load('./model/darknet19.weights.npz')
# layer1
conv... |
#!/usr/bin/env python2
import sys
from finder.finder import XSSFinder
if __name__ == '__main__':
finder = XSSFinder('https://xss-game.appspot.com/level1/frame')
finder.scan() |
#!/usr/bin/python3
import http.server
PORT = 8888
server_address = ("", PORT)
server = http.server.HTTPServer
handler = http.server.CGIHTTPRequestHandler
handler.cgi_directories = ["/web"]
try:
print("Serveur actif sur le port :", PORT)
httpd = server(server_address, handler)
httpd.serve_forever()
excep... |
import math
from unittest import TestCase, main
import numpy as np
from ... import LinearProgram
class TestToSEF(TestCase):
def test_to_sef(self) -> None:
A = np.array([[1, 5, 3], [2, -1, 2], [1, 2, -1]])
b = np.array([5, 4, 2])
c = np.array([1, -2, 4])
z = 0
p = LinearP... |
from lib.saga_service.filesystem_service import FilesystemService
import time
import saga
class JobSubmissionService:
"""
Service for submitting jobs into the GRID.
Supports submitting jobs over ssh.
"""
def __init__(self, saga=saga, saga_job=saga.job,
filesystem=FilesystemServic... |
#!/usr/bin/python
# coding: utf-8
import json
import requests
__author__ = 'tangjia'
import mysql.connector
JSON_HEADER = {'content-type': 'applocation/json'}
REST_HOST = "https://a1.easemob.com"
# 测试
# APP_KEY="beijingfahaifuneng#baymax"
# APP_CLIENT_ID="YXA6kynz0MrhEeSS2Q2e11-3BA"
# APP_CLIENT_SECRET="YXA63Xe21wi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.