text stringlengths 38 1.54M |
|---|
import numpy as np
import pandas as pd
import random
from collections import namedtuple
import mysql.connector
import datetime
import pytz
L1_ALPHA = 16.0
def _clone_and_drop(data, drop_cols):
""" Returns a copy of a dataframe that doesn't have certain columns. """
clone = data.copy()
for col in drop_cols... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2017-06-20 01:41
from __future__ import unicode_literals
from decimal import Decimal
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ca... |
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/inicio')
@app.route('/')
def inicio():
return render_template('inicio.html')
@app.route('/login')
def outro_inicio():
return render_template('Login.html')
if __name__ == '__main__':
app.run(host='0.0.0.0',port=port) |
#!/usr/local/bin/python3
meal_cost = float(input().strip())
tip_percent = int(input().strip())
tax_percent = int(input().strip())
tip = meal_cost * tip_percent/100.0
tax = meal_cost * tax_percent/100.0
totalCost = meal_cost + tip + tax
print('The total meal cost is {0:d} dollars.'.format(round(totalCost)))
|
# Copyright 2017 The Forseti Security Authors. All rights reserved.
#
# 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 ap... |
import cv2
import numpy as np
# We are going to use:
# 1. resize
# 2. Median blurring
class PreprocessedImage:
def __init__(self, image):
self.image = cv2.imread(image)
def run(self):
return self.median_blurring(self.resize(self.image))
def run_with_grayscale(self):
return se... |
import csv
import json
from django.db import transaction
from django.http import HttpResponse
from geonode.utils import json_response
from geonode.utils import resolve_object
from mapstory.storypins.forms import StoryPinForm
from mapstory.storypins.models import StoryPin
from mapstory.storypins.utils import unicode_... |
#!/usr/local/bin/python2.7
import cgi
import cgitb
cgitb.enable()
import myfunc
import mysessions
import pfuser as users
import pageElements
def sorting(postdata):
"""
My basic logic:
mysessions.start()
if the post data says to send the daily email, send that ish.
if the post data has login info, try and... |
#! /usr/bin/python
import ctypes
import sys
import os
import time
# gpio_dma.so loaded to the python file
# using fun.myFunction(),
# C function can be accessed
# but type of argument is the problem.
fun = ctypes.CDLL(os.path.abspath('../lib/gpio_driver.so'))
fun.get_byte.restype = ctypes.c_ubyte
#fun.get_byte... |
from django import forms
from django.conf import settings
class ProfileForm(forms.Form):
STUDY_TITLE_CHOICES = [
("Diploma", 'Diploma'),
("Laurea", 'Laurea'),
]
name = forms.CharField(label="Nome")
surname = forms.CharField(label="Cognome")
email = forms.EmailField()
phone = forms.IntegerField(label="Numero ... |
#
import xbmc
import xbmcaddon
__scriptname__ = "audo"
__author__ = "lsellens"
__url__ = "https://github.com/lsellens/xbmc.addons"
__icon__ = xbmcaddon.Addon(id='script.module.audo').getAddonInfo('icon')
#try to get service addon info or send notification to install it.
try:
__addon__ = xbmcaddo... |
imp_list = open("employees.csv").read().split("\n")
imp_list_2 = imp_list.split(",")
print(imp_list)
# print(imp_list[0])
# employees = []
# for employee in imp_list:
# for header in imp_list[0]:
# add_dictionary = {}
# # add_dictionary[header] = employee
# print(imp_list[0])
# pr... |
class Borg(object):
__shared_state = {}
def __new__(cls, *args, **kargs):
obj = super(Borg, cls).__new__(cls, *args, **kargs)
obj.__dict__ = cls.__shared_state
return obj
b = Borg()
b1 = Borg()
b.x = 4
print("Borg Object 'b':", b)
print("Borg Object 'b1':", b1)
print("Object State 'b... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main.ui'
#
# Created by: PyQt5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QAp... |
import typing
import weakref
import collections.abc
import functools
import copy
import contextlib
from . import _helpers
from . import _manage
__all__ = (
'Tool', 'resolve', 'theme', 'Unit', 'update',
'Object', 'keyify',
'List', 'Dict', 'add', 'pop',
'collect', 'Collection',
'strip'
)
_Data... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#.--. .-. ... .... -. - ... .-.-.- .. -.
import click
import meinheld
from flask.ext.script import Manager
from ast import create_app, app
manager = Manager(app)
@manager.command
def runserver():
"Runs the App"
create_app()
if app.config['MEINHELD']:
... |
from actions import SequenceAction
from graph_actions.generate_graph import GraphInput
from graph_actions.partition import Partition
from graph_actions.contraction import Contraction
from graph_actions.treewidth import Treewidth, WeightedTreewidth
from graph_actions.partition_bags import PartitionBags, PartLargestBag
f... |
from django.contrib import admin
from app.models import *
class ObjectAdmin(admin.ModelAdmin):
list_display = ('title', 'price')
class ForemanAdmin(admin.ModelAdmin):
list_display = ('name', 'login', 'account_summ', 'account_dollar')
class MaterialAdmin(admin.ModelAdmin):
list_display = ('user_id', 'title... |
from .encode_quads import encode_quads
from .read_sample import read_sample
from .decode_predictions import decode_predictions
from .generate_default_quads_for_feature_map import generate_default_quads_for_feature_map
from .get_number_default_quads import get_number_default_quads
from .match_gt_quads_to_default_quads i... |
import pandas as pd
def partial(func, *args, **keywords):
'''
This partial, currying function takes in another function,
and default arguments and returns a new function that
has these default arguments.
Example:
a line function usually would take in slope, y intercept,
and x value to g... |
from rdflib import Graph, Literal
from rdflib.namespace import Namespace, FOAF
from ecsdiLAB.ecsdimazon.controllers import Constants
from ecsdiLAB.ecsdimazon.model.BoughtProduct import BoughtProduct
from ecsdiLAB.ecsdimazon.model.Product import Product
from ecsdiLAB.ecsdimazon.model.User import User
class SendProdu... |
from convolution import convolve
from pooling import max_pool
from backprop import backpropogation
from relu_activation import relu
import numpy as np
import torch as tr
import torchvision
import torch.nn as nn
import Mnist_load
chnls_input=1
batch_size=32
input_vec=np.random.randn(batch_size,chnls_input,28,28)
kernel... |
#!/usr/bin/env python
"""Demonstrates raw_input in a while loop."""
while True: # True/False are keywords.
answer = raw_input('What is your favorite number? ')
try:
number = int(answer)
except ValueError:
print answer, 'is not a number! Please try again.'
else:
break
p... |
from autodesk.hardware import Hardware
from autodesk.model import Down, Up, Active, Inactive
from unittest.mock import MagicMock, call, patch
import sys
import unittest
class TestHardware(unittest.TestCase):
def setUp(self):
self.time_patcher = patch('time.sleep')
self.time_sleep = self.time_patch... |
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('mysql+pymysql://root:Nomelose123@87.4.5.139:3306/faveolivetest')
Session = sessionmaker(bind=engine)
Base = declarative_base() |
#!/usr/bin/python3
from test.dao.PagamentoDAOTest import PagamentoDAOTest
print("\nTesting PagamentoDAO\n")
pagamentoDAOTest = PagamentoDAOTest()
pagamentoDAOTest.test()
|
# Copyright (c): Wenyi Tang 2017-2019.
# Author: Wenyi Tang
# Email: wenyi.tang@intel.com
# Update Date: 2019/5/7 下午5:21
try:
# torch >= 1.1.0
from torch.utils.tensorboard import SummaryWriter
except ImportError:
from tensorboardX import SummaryWriter
_writer_container = {}
class Summarizer:
def __init_... |
import sys
# D is the total distaince in mm we need to more
# T is the number of jumps forward
# B is the length of the big jump
# small jump is 1
class LongLongTripDiv2 :
def isAble(self, D, T, B) :
# print("Testing: " + repr(D) + "/" + repr(T) + "/" + repr(B))
if (D < 1) or (D > 100000000000000000) :
retur... |
#!/usr/bin/env python3
# Copyright © 2014, 2015 Anton Tsyganenko
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy... |
import datetime
from migration_state import _execute, _execute_in_transaction, table_present
MIGRATION_LOG_SQL = """
CREATE TABLE `dmigrations_log` (
`id` int(11) NOT NULL auto_increment,
`action` VARCHAR(255) NOT NULL,
`migration` VARCHAR(255) NOT NULL,
`status` VARCHAR(255) NOT NULL,
`datetim... |
DEBUG = False
TESTING = False
#: site
SITE_TITLE = 'June Forum'
SITE_URL = '/'
SITE_FEED = ''
SITE_LOGO = ''
SITE_GOOGLE_ANALYTICS = None
#: session
SESSION_COOKIE_NAME = 'june'
#SESSION_COOKIE_SECURE = True
PERMANENT_SESSION_LIFETIME = 3600 * 24 * 30
#: account
PASSWORD_SECRET = 'password-secret'
GRAVATAR_BASE_URL ... |
import re
from nautapy.exceptions import NautaFormatException
_re_time = re.compile(r'^\s*(?P<hours>\d+?)\s*:\s*(?P<minutes>\d+?)\s*:\s*(?P<seconds>\d+?)\s*$')
def strtime2seconds(str_time):
res = _re_time.match(str_time)
if not res:
raise NautaFormatException("El formato del intervalo de tiempo es ... |
# Generated by Django 3.1.2 on 2021-02-11 16:54
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='crop',
fields=[
('id', models.AutoField(aut... |
#!/usr/bin/python
import sys
from lxml import html
import requests
url='http://it.unknownphone.com/search.php?num=' + sys.argv[1]
#print url
page = requests.get(url)
tree = html.fromstring(page.content)
#score = tree.xpath('img[@class="scoreimage"]/text()')
score = tree.xpath('//div[@class="comment_content"]/text()')
... |
rule viola: # used by both modes
input:
os.path.join(
"{path}",
"{tumor}--{normal}",
"{outdir}",
"{}{}".format("{prefix}", config.file_exts.vcf),
)
if config.mode is config.mode.PAIRED_SAMPLE
else os.path.join(
"{path}",
... |
#!/usr/bin/python
# spymer v3
# Author: FSystem88
class spymer:
def main(self):
print('8888888888888888888888888\n8888888888888888888888888\n888 888 888\n888 888888888 8888 888\n888 888888888 888888888\n888 888888888 888888888\n888 888 888\n888 888888888888888 888\n888 888888888... |
#!/usr/bin/env python
from setuptools import setup
setup(
name="records",
version="0.0.1",
packages=[],
entry_points={
'console_scripts': ['Records = Records.__main__:main']
}
) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'krajcovic'
__name__ = 'fibo'
def fib(n):
"""
Vytiskne fibonacciho rozvoj
:param n: Maximalni rozsah
:return:
"""
a, b = 0, 1
while b < n:
print(b, end = '\t')
a, b = b, a+b
def fib2(n):
"""
Vrati Fibonacciho ... |
#!/usr/bin/env python
# coding=utf-8
from __future__ import unicode_literals, absolute_import, print_function, division
import sopel.module
import ConfigParser
import requests
import urllib2
import json
from BeautifulSoup import BeautifulSoup
from random import randint
import sys
import os
moduledir = os.path.dirname(_... |
import pygame
from objects.block import Block
class Fruit(Block):
def __init__(self, x, y, unit_width, unit_height, background, image):
super().__init__(x, y, unit_width, unit_height, background)
self.unit_width = unit_width
self.unit_height = unit_height
self.image = pygame.image.load(image)
self.scale_... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('hiwi_portal', '0008_worktime_activity'),
]
operations = [
migrations.A... |
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
from threading import Thread
import subprocess
from queue import Queue
import re
num_ping_threads = 2
num_arp_threads = 2
in_queue = Queue()
out_queue = Queue()
ips = ["10.0.1.1","10.0.1.2","10.0.1.3","10.0.1.4"]
def ping(i,iq,oq):
while True:
ip = iq.get()
... |
import os,glob
user="rhardin"
machine = "schroedinger.csail.mit.edu"
project_dir = "/home/rhardin/research/ddbms/distDBX/"
PATH=os.getcwd()
result_dir = PATH + "/results/"
test_dir_name = sorted(glob.glob("tests-*"),key=os.path.getmtime,reverse=True)[0]
test_dir = PATH +"/" + test_dir_name
cmd = "tar -czvf {}.tgz {... |
######################################
#
# Deborah Pinna, August 2015
#
######################################
from utils import *
JetHTbv3 = sample()
JetHTbv3.files = outlist (d,"JetHTbv3")
JetHTbv3.skimEff = 1
JetHTbv3.sigma = 1
JetHTbv3.color = ROOT.kBlack
JetHTbv3.jpref = jetLabel
JetHTbv3.jp = jetLabel
JetHTbv... |
from init import init
import numpy as np
import random
def crossover(initValues : init, matingPool : list):
parentNum = np.random.permutation(initValues.n)
newPopulation = np.zeros((initValues.n, initValues.l) , dtype=int)
for j in range(0, initValues.n, 2):
pointer1 = parentNum[j]
pointer2... |
from ..helpers import get_allowed
import os
import subprocess
import web
class DeployCommandR:
"""
This endpoint is for uploading a template file to an machine.
"""
allow_origin, rest_url = get_allowed.get_allowed()
def OPTIONS(self, machine):
return self.POST(machine)
def POST(self, ... |
import unittest
import pyNN.spiNNaker as p
import SpinVision.neuralNet as n
import SpinVision.AEDAT_Handler as f
import SpinVision.networkControl as control
import os
import numpy as np
import paer
import SpinVision.training as tr
basePath = tr.filepath + "resources/DVS Recordings/test/"
class test_networkControlTes... |
# Exercise: Analyse a repeat structure
# ===
#
# We are going to make a repeating DNA sequence and extract some subsequences
# from it.
#
# * Make a short tandem repeat that consists of three "ACGT" units and five
# "TTATT" units.
# * Print all suffixes of the repeat structure.
#
# **Note:** A suffix is an ending. Fo... |
# Generated by Django 2.1.1 on 2018-10-03 14:44
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('regi... |
#Thuat toan BFS
def BFS(matrix,start,end):
path=[]
explored={}
frontier={}
frontier[start]=None
k=start
while True:
if len(frontier)==0:
result='No path'
cost = len(explored)
return cost,0,result
res=list(frontier.keys())[0]
point=front... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 30 14:53:32 2021
@author: hreed
"""
import numpy as np
import matplotlib.pyplot as plt
def plot(y, x):
plt.plot(y, x)
plt.title("Plot")
plt.show()
def say_hi():
print('Hi!')
def example_return(x):
plt.plot(x, 5*x)
plt.title("5x")
pl... |
#!/usr/bin/env python
import json
from pathlib import Path
import math
DATABASE='repayment_user_data.json'
script_location = Path(__file__).absolute().parent
file_location = script_location / DATABASE
bad_keywords = ["is overdue",
"has bounced",
"bounce",
"has not been honoured",
"severely overdue",
"is still pendin... |
from django_news.utils import constants
from users.models import User
def user_to_dict(self):
resp_dict = {
"id": self.id,
"nick_name": self.nick_name,
"avatar_url": constants.QINIU_DOMIN_PREFIX + self.avatar_url if self.avatar_url else "",
"mobile": self.mobile,
"gender": ... |
class Node:
def __init__(self, item, next):
self.item = item
self.next = next
class Stack:
def __init__(self):
self.last = None
def push(self, item):
self.last = Node(item, self.last)
def pop(self):
item = self.last.item
self.last = self.last.next
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from sqlalchemy import create_engine, Table, MetaData, tuple_
from sqlalchemy.sql import select
def to_sql(statement):
return ''.join(str(statement.compile(compile_kwargs={"literal_binds": True})).split('\n'))
eng = create_engine("mysql+pymysql://root:123456@localhost/... |
from datetime import datetime
from enum import Enum
from pydantic import BaseModel
class ServerDataType(str, Enum):
sound = 'sound'
image = 'image'
video = 'video'
text = 'text'
class ServerData(BaseModel):
type: ServerDataType
ts: datetime
content: str
class AllowData(str, Enum):
... |
import pandas as pd
import math
from sklearn.utils import shuffle
dataset = pd.read_csv("text_emotion.csv", encoding='utf-8')
f = open("Jan9-2012-tweets-clean.txt", "r")
i = 0
percentage = 0
print('Combining: 0 %')
emoji_to_change = [':-)', '=)', ':-(', '=(', ':-O', ':-o', '=O', '=o', ';-)', ';-(', ... |
import argparse
# without '--' or '-', the order of arguments are important.
parser = argparse.ArgumentParser()
parser.add_argument('echo', help="echo the string you use here")
parser.add_argument('square', type=int, help="display a square of a given number")
args = parser.parse_args()
print(args.echo)
print(args.squa... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-02 06:00
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operatio... |
from Settings.defaultSettings import *
##Create a unique secret key for the project
try:
from Settings.secret_key import *
except ImportError:
from django.utils.crypto import get_random_string
SETTINGS_DIR=os.path.abspath(os.path.dirname(__file__))
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-... |
def dingyi(a,b,c=100):
return a+b+c
a = int(input('请输入a的值'))
b = int(input('请输入b的值'))
d =dingyi(a,b,c=100)
print(d)
|
import eterna_utils
import strategy_template
from math import log, pow
class Strategy(strategy_template.Strategy):
def __init__(self):
strategy_template.Strategy.__init__(self)
# Title, author of the strategy submission
self.title_ = ("[Strategy Market] [Switch]"
... |
# 安装ggplot,需要numpy, scipy支持,安装过程容易报错
# 升级pip, 以免安装.whl失败。注意 .whl文件名不能修改,不要使用迅雷下载
# pip install --upgrade setuptools
# 安装numpy,scipy,windows下需要编译,可以在http://www.lfd.uci.edu/~gohlke/pythonlibs/ 下载编译包.whl安装。
# pip install .whl
# windows下需要安装VC++ 14.0,http://landinghub.visualstudio.com/visual-cpp-build-tools ,在该网站下载 Visua... |
#!/usr/bin/python
#$Id: $
"""
python lib for reading magstripe card with
3S4YR-MVFW(DL)-0 Series Hybrid Card Reader/Writer
not finished, not tested
written by lifesim.de
donations: btc:14sb3XcNVWuQgqRx5RVE8sLazz82fAWx3j
"""
import serial
_version = "0.0.1"
def hex2(byte):
r = hex(byte)
r = r[2:]
if byte <0x1... |
x = 0
if x < 1 :
print('less that 1')
elif x < 3:
print('less that 2')
else:
print('less that 3')
|
class Calculator:
name = 'Good calculator'
price = 18
def __init__(self, name, price, hight, width, weight):
self.name = name
self.price = price
self.hight = hight
self.width = width
self.weight = weight
def add(self, x, y):
result = x + y
print(... |
from django.shortcuts import render_to_response
from django.template import RequestContext
from django import http
from django.utils import simplejson as json
from core.models import Neighborhood
def index(request):
city_stats = []
for city in Neighborhood.objects.cities():
neighborhoods = sorted(Neig... |
'''
Reads the contents of a git repository and write a DOT graph file to stdout.
'''
import dulwich.repo
import dulwich.index
import dulwich.objects
import pydot
import subprocess
DEFAULT_FONTNAME = 'Monaco'
DEFAULT_FONTSIZE = '8'
BLOB_CONTENT_LIMIT = 200 # show at most this many bytes of blob content
DEFAULT_FONT ... |
# Magic 8ball.
import random
def get_answer(answer_number):
if answer_number == 1:
return 'It is certain'
elif answer_number == 2:
return 'I believe it is'
elif answer_number == 3:
return 'Yes'
elif answer_number == 4:
return 'Try again'
elif answer_number == 5:
... |
# This is an experiment file
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.externals import joblib
import networkx as nx
import numpy as np
from collections import Counter
import torch
import torch.nn as nn
import torch.optim as optim
from embeddings import load_embedding_pkl
import pickle
impo... |
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib.auth.mixins import (
LoginRequiredMixin,
UserPassesTestMixin
)
from django.views.generic import (
ListView,
DetailView,
Crea... |
class A:
def m1(self):
print("Method m1() in A")
class B:
def m1(self):
print("Method m1() in B")
class C(A,B):
def m2(self):
print("Method m1() in C")
obj = C()
print(C.mro())
|
#script para capturar informacion y procedimientos con respecto al usuario del sistema
#modulos asociados a la conexion y procesamiento de informacion a la base de datos
from Modules.CCConnectDB import ConnectDataBase
from Modules.CCCRUD import CrudDataBase
import sys
class ManagerUserSystem(object):
#constructor... |
from django.urls import path
from .views import AddTimeFormView, FinishCurrentTaskFormView, TimingView
app_name = 'timing_website'
urlpatterns = [
path('', TimingView.as_view(), name='timing_view'),
path(
'finish-current-task/',
FinishCurrentTaskFormView.as_view(),
name='finish_curren... |
import turtle
turtle.shape('turtle')
for i in range(72):
turtle.forward(5)
turtle.left(5)
|
def find_needle(haystack):
for word in haystack:
if word == 'needle':
return "found the needle at position " + str(haystack.index('needle'))
|
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
#
# Copyright (c) 2019 Nicolas Iooss
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation ... |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class Category(models.Model):
title = models.CharField(max_length=255)
def __unicode__(self):
return u'%s' % self.title
class Genre(models.Model):
title = models.CharField(max... |
'''
Created on 21.04.2011
@author: Montellese
'''
class WikiUtils(object):
'''
classdocs
'''
@staticmethod
def __xHeading(level, text):
if level < 0:
level = 0
extra = level * "="
return "==%s%s%s==\n" % (extra, text, extra)
@staticmethod
... |
# @Author:langyi
# @Time :2019/4/7
import random
import torch
import numpy as np
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
... |
#File containing all header and data structures needed for processing the NSL-KDD Dataset
import numpy as np
data_headers = [
"duration",
"protocol_type",
"service",
"flag",
"src_bytes",
"dst_bytes",
"land",
"wrong_fragment",
"urgent",
"hot",
"num_failed_logins",
"logged... |
from rasa.nlu.components import Component
from rasa.nlu.training_data import Message
import typing
from typing import Any, Optional, Text, Dict
from rasa_sdk.events import FollowupAction, SlotSet
if typing.TYPE_CHECKING:
from rasa.nlu.model import Metadata
class SpellCorrection(Component):
provides = ["text... |
LISTEN_PORT = 8080
DB_PORT = 27017
DB_NAME = 'etscene'
COOKIE_SECRET = '442428be-3713-4c38-a518-1a9f905d7079'
try:
from local_settings import *
except ImportError:
pass
|
filename = input("Enter a file name:")
wordToReplace = input("Enter the string to be removed:")
inFile = open(filename,"r")
text = inFile.read()
text = text.replace(wordToReplace,"")
outFile = open(filename,"w+")
outFile.write(text)
inFile.close()
outFile.close()
|
# -*- coding: utf-8 -*-
# File generated according to PWSlot14.ui
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_PWSlot14(object):
def setupUi(self, PWSlot14):
PWSlot14.setObjectName("PWSlot14")
PWSlot14.resize(630, 470)
PWSlot... |
# ------------------------------------------------------------------------------
# Lux texture nodes for Maya
#
# by Doug Hammond 05/2008
#
# This file is licensed under the GPL
# http://www.gnu.org/licenses/gpl-3.0.txt
#
# $Id$
#
# ------------------------------------------------------------------------------
#
# Lux ... |
"""
Perception
- Input : x1, x2
- Output : a = (x1 * w1) + (x2 + w2) + b
~~~> y = 0 (a <= 임계값) 또는 1 (a > 임계값)
신경망의 뉴런(Neuron)에서는 입력 신호의 가중치 합을 출력 값으로 변환해주는 함수가 존재.
이 함수를 '활성화 함수(Activation Function)'라고 한다.
"""
import math
import numpy as np
import matplotlib.pyplot as plt
# 1) 계단 함수
def step_function(x):... |
from django.shortcuts import render
from datetime import date
def index(request):
context = {
'slogan':'Супер предложения',
'time' : date.today()
}
return render(request, 'geekshop/index.html', context)
def contacts(request):
return render(request, 'geekshop/contact.html') |
# -*- encoding: utf-8 -*-
#! /usr/bin/env python
#created by @ceapalaciosal
#under code Creative Commons
import os
from excelmatriz import *
from wcsv import *
import json
def listaCSV(direccion):
#Variable para la ruta al directorio
path = os.path.join(direccion,'')
#print direccion
#Lista vacia para inclu... |
from InstagramAPI import InstagramAPI
with open('username') as f:
username = f.read()
with open('password') as f:
password = f.read()
api = InstagramAPI(username, password)
api.login()
followings = api.getTotalSelfFollowings()
favorites = [user for user in followings if user['is_favorite']]
for username in s... |
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
class Device(models.Model):
device_name = models.CharField(max_length=100)
thinger_username = models.CharField(max_length=100)
token = models.CharField(max_length=1000)
is_connected = models.Boolean... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import freq
import Image,ImageDraw
class EntCalc:
data=""
entropy=[]
sample_size=0
avg_entropy=0
def __init__(self):
self.frq = freq.Frequency()
def calculate_sample_size(self):
if self.sample_size!=0:
print("Sam... |
from django.conf import settings
from django.db import models
from django.db.models import Sum
from django.shortcuts import reverse
from django.db.models import Model
from django.db.models.signals import post_save
LABEL_CHOICES = [
('P', 'primary'),
('S', 'secondary'),
('O', 'other')
]
CATEGORY_CHOI... |
import json
user_info_dict={"name":"zhangsan",
"age":20,
"language":["python","java"],
"study":{"AI":"python","bigdata":"hadoop"},
"if_vip":True,
"gender":None}
with open("./user_info.json","w")as f:
json.dump(user_info_dict,f)
|
import logging
import sys
from concurrent import futures
from random import choice
import grpc
from google.protobuf.json_format import MessageToDict, MessageToJson
import tictactoe_pb2
import tictactoe_pb2_grpc
from game import Game
from server_ports import PORTS
logging.basicConfig()
logger = logging.getLogger(__fi... |
"""
This is an example how to switch a crownstone using the crownstone python lib cloud.
Using this library in async context is the recommended way.
Last update by Ricardo Steijn on 31-10-2020
"""
from crownstone_cloud import CrownstoneCloud, create_clientsession
import logging
import asyncio
# Enable logging.
loggin... |
# coding: utf-8
from __future__ import absolute_import
from google.appengine.ext import ndb
from flask.ext import restful
import flask
from api import helpers
import auth
import model
import util
from main import api_v1
@api_v1.resource('/crash/', endpoint='api.crash.list')
class CrashListAPI(restful.Resource):
... |
from django.db import models
from datetime import datetime
class Grafica(models.Model):
nome_da_grafica = models.CharField(max_length=200)
cnpj = models.CharField(max_length=200)
nome_servicos = models.TextField()
endereco = models.CharField(max_length=200)
telefone = models.CharField(max_length=20... |
# coding: utf-8
n = int(input())
left = []
right = []
for i in range(n):
tmp = [int(j) for j in input().split()]
left.append(tmp[0])
right.append(tmp[1])
ans = min(left.count(0),left.count(1)) + min(right.count(0),right.count(1))
print(ans)
|
from address_book.book import indexes
class Repository(object):
def __init__(self, book):
self.book = book
def save(self, obj):
self.book.add(obj)
def find_persons_by_name(self, term):
index = indexes.PersonNameIndex(self.book)
return index.filter(term)
def find_per... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.