text
stringlengths
38
1.54M
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right #recursive solution class Solution: def helper(self, node, in_order): #traverse to the left most leaf if ...
# -*- coding: utf-8 -*- import random import math import statistics random.seed() done = False area_square = 4 needles = 1000 while (not done): estimates = [] for i in range(100): needles_in_circle = 0 needles_in_square = needles for i in range(needles): # ...
""" U-Net from https://github.com/tdeboissiere/DeepLearningImplementations/tree/master/pix2pix Changes : - added init='glorot_uniform' to Convolution2D, Deconvolution2D - changed the final layers to get a number of channels equal to number of classes of a semantic segmentation problem. Limitations: - number of ...
import numpy as np # a=np.array([1,2,3]) # print(a) #创建数组 ar1=np.array(range(10)) ar2=np.arange(10) ar3=np.array([[1,2,3,5],['a','b','c']]) print(ar1) print(ar2) print(ar3) #生成随机数,先生成数字,再生成形状 print(np.random.rand(10).reshape(2,5)) #创建数组arange类似range print("="*30) print(np.arange(10)) print(np.arange(10.0)) print(np.ar...
# -*- coding:utf-8 -*- from web_.spider_web_allLink import html_download from web_.spider_web_allLink import html_parse from web_.spider_web_allLink import link_manage from web_.spider_web_allLink import results_print class Spider_Main(object): def __init__(self): self.links = link_manage.LinkManager() ...
#!/usr/bin/env python # coding: utf-8 # In[ ]: import numpy as np import pandas as pd train_dataset = pd.read_csv('../input/train.csv') test_dataset = pd.read_csv('../input/test.csv') # In[ ]: train_dataset.describe() # In[ ]: train_dataset.info() # In[ ]: import matplotlib as plt #Bar graph Surived Vs...
# iterate through float # ask user for float item_name =("What is the item name? ") error = "your item name got number in it" has_errors = "" # look at each character in float and if it number,complain for letter in item_name: if letter.isdigit()== True: print(error) has_errors = "yes" ...
import scipy.io as sio import numpy as np from sklearn.metrics import accuracy_score from sklearn.multiclass import OneVsRestClassifier from sklearn.svm import LinearSVC from sklearn import svm from sklearn import tree from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.grid_search import GridSearchCV fr...
import RPi.GPIO as GPIO import time import numpy as np import cv2 import datetime import os import glob GPIO.setmode(GPIO.BOARD) GPIO.setup(36,GPIO.OUT) pwm = GPIO.PWM(36,50) #opens completely pwm.start(7.7) time.sleep(0.5) # # fully closes at 3.4% duty cycle # pwm.ChangeDutyCycle(3.4) # time.sleep(0.5) os.system(...
from django import forms from .models import * class CompeticionForm(forms.ModelForm): class Meta: model= Competicion fields =['nombre', 'equipo', 'torneo','descripcion',] class EquipoForm(forms.ModelForm): class Meta: model= Equipo fields =['nombre', 'lugar_origen', 'ColorPrim...
import numpy as np import matplotlib.pyplot as plt x = [1.0, 2.0, 4.0, 3.0, 5.0] y = [1.0, 3.0, 3.0, 2.0, 5.0] print ("X values:", x) print ("Y values:", y) avgx = sum(x)/len(x) print ("x mean:", avgx) avgy = sum(y)/len(y) print ("y mean:", avgy) slope = 0 bias = 0 for i in range(len(x)): s...
""" python -m venv venv cd .. create a virtual environment python -m venv . web_server/bin/activate pip list deactivate EXPORT FLASK_APP=server.py EXPORT FLASK_ENV=development flask run pip freeze > requirements.txt # put current deps in a requirements.txt file captures in env pythonanywhere """
from django import forms class SearchUser(forms.Form): name1 = forms.CharField( label='Username1', error_messages={'required': 'Introdueix un usuari'}, widget=forms.TextInput( attrs={ 'class':'form-control form-control-lg', 'placeholder':'productes_capell'} ...
from blog.extend.UrlsHelper import url from blog import blog from blog.views import views blog.add_url_rule('/', view_func=views.index, methods=['GET', 'POST']) blog.add_url_rule('/index', view_func=views.index, methods=['GET', 'POST']) blog.add_url_rule('/<string:categoryname>/<string:month>/<int:page>', ...
#!/usr/bin/env python ''' twoprime: analysis of twoprime-seq data ''' from ez_setup import use_setuptools use_setuptools() from setuptools import find_packages, setup __version__ = '0.01a' entry_points = """ [console_scripts] twoprime-process-signals = twoprime.process_signals:main """ install_requires = ["genom...
#!/usr/bin/python3 # Falsely assumes all months have 31 days line = input().split() month = line[1] M = [ 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC' ] assert month in M days = -1 # days since 1 JAN # add days in previous months: days += 31 * M.index(month) # add days in t...
import cv2 import numpy as np import matplotlib.pyplot as plt # THRESH_BINARY # THRESH_BINARY_INV # THRESH_MASK # THRESH_OTSU # THRESH_TOZERO # THRESH_TOZERO_INV # THRESH_TRIANGLE # THRESH_TRUNC img=cv2.imread('1.jpg',0) ret,binThreshold=cv2.threshold(img, 168, 255, cv2.THRESH_TRUNC) cv2.imshow("Binary",binThreshold)...
import util def display_board(board, player): for elem in board: for i in elem: print(i, end='') print('\n',end='') print(f"health: {player['current_health']} armor: {player['base_armor']}") def display_stats(player): line_selected = 0 while True: util.clear...
__author__ = 'Rushil' #0.123456789101112131415161718192021... num_list = [] for i in range(1000000): num_list += str(i) m_list = ''.join(num_list)[1:] print(len(m_list)) print(m_list[1]) n = 1 prod = 1 while n != 1000000: prod *= int(m_list[n-1]) print(int(m_list[n-1]) , n) n *= 10 ...
''' Implementation of realtional coherence my thesis basically hardcoded to work on the output from Nitish's model. ''' from collections import defaultdict from create_wned_tas import init_view, init_constituent, serialize_tas from ccg_nlpy import core, local_pipeline from ccg_nlpy.core import view import numpy as np...
from baseop import BaseOp from funcs import has_parity, to_hex_digits, to_signed from memory.memory import fetch_signed_byte class OpRlca(BaseOp): def __init__(self, processor): BaseOp.__init__(self) self.processor = processor def execute(self, processor, memory, pc): result = _rlc_va...
from django.conf.urls import url from education.views import ClassList, CreateStudent, CreateTeacher, UserClassList, sign_up_for_class urlpatterns = [ url('^class_list/$', ClassList.as_view()), url('^user_class_list/$', UserClassList.as_view()), url('^create_student/$', CreateStudent.as_view()), url('...
#! -*- coding:utf-8 -*- from django.shortcuts import render from app_shop.models import Product, Catalog def index(request): latest_product_list = Product.objects.all().order_by('-name')#[:5] latest_catalog_list = Catalog.objects.all().order_by('-name')#[:5] context = {'latest_product_list': latest_product...
import luigi import os import luigi.contrib.postgres import json from app.utils.helper import derive_current_timestamp from app.helpers.subreddit_ingestion import SubredditIngestion class IngestSubreddit(luigi.Task): """ Task to individually ingest the Subreddit data and store as separate output targets ...
import numpy as np import pandas as pd class TranslatingCordinateSystem: def __init__(self, r_a = None, v_a = None, a_a = None): self.r_a = r_a self.v_a = v_a self.a_a = a_a def translations(self): r_b = self.r_a
from googletrans import Translator tr = Translator() from telegram import Update, KeyboardButton, ReplyKeyboardMarkup from telegram.ext import CallbackContext, Updater, ConversationHandler, CommandHandler, MessageHandler, Filters, \ CallbackQueryHandler import globals from database import Database from datetime im...
import numpy as np # Numpy is an array processing library with support for n-dimensional arrays and a number of mathematical operations # How numpy handles arrays of varying shapes is common to a lot of mathematical processing done in python, # most relevantly TensorFlow. # Suppose we have a list of numbers l = [] fo...
import random from card import Card values = list(Card.VALUES) suits = list(Card.SUITS) class Deck: ''' Deck of cards supporting common operations of shuffling and drawing. ''' def __init__(self): self.cards = [] self.index = 0 for i in range(0, len(values)): for j in ran...
# #Step 1 : Understand the problem statement #step 2 : Write the Algorithm #Step 3 : Decide the programming language #Step 4 : Write the Program #Step 5 : Test the Written Program #program statement: # accept number from user and return addition of digits in that number ################################...
from django.shortcuts import render from django.shortcuts import render, redirect, HttpResponse from django.contrib import messages from django.db.models import Count from .models import User, Wish from django.core.exceptions import ObjectDoesNotExist import time import re import datetime EMAIL_REGEX = re.compile(r'^[a...
import StarLAB StarLAB.version() myStarLAB = StarLAB.Connect(IP="192.168.86.104") tempdata = myStarLAB.atmos.getTempC() print("Temperature", tempdata) myStarLAB.enableRover() run = myStarLAB.motors.setMotorPower(60,60)
import abc from interfaces import Point3D from typing import Sequence, Tuple class Triangulator(abc.ABC): @abc.abstractmethod def __init__(self, file_paths): pass @abc.abstractmethod def localize(self, known_points: Sequence[Tuple[Point3D, Point3D]], unkown_points: Sequence[Point3D]) ->Sequenc...
#!/usr/bin/env python3 ''' Created on Jul 23, 2017 @author: Daniel Sela, Arnon Sela Example parameters: -e 10 --w-ref -c “J242117.88+355328.8” -f ../../../smu/dat/000901_sky0001_1a_match.datc ../../../smu/dat/000901_sky0001_1b_match.datc ../../../smu/dat/000901_sky0001_1c_match.datc ../../../smu/dat/000901_sky0...
import requests import json import re def get_greater_30(v_id): url = "http://s.video.qq.com/get_playsource?id=" + v_id + "&type=4&range=1-10000&otype=json" session = requests.session() res = session.get(url).text json_re = re.match("QZOutputJson=(.*)", res).groups() if len(json_re): json...
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 expandtab number """ 题目描述 给定一个会议时间安排的数组,每个会议时间都会包括开始和结束的时间 [[s1,e1],[s2,e2],…] (si < ei),为避免会议冲突,同时要考虑充分利用会议室资源,请你计算至少需要多少间会议室,才能满足这些会议安排。 tag 贪心 堆 样例 1 2 输入: [[0, 30],[5, 10],[15, 20]] 输出: 2 http://shaocheng.me/2019/07/18/LeetCode-253-Meeti...
#keras51_homework.py import numpy as np y = np.array([1,2,3,4,5,1,2,3,4,5]) y = np.array([0,1,2,3,4,0,1,2,3,4]) from keras.utils import np_utils y = np_utils.to_categorical(y) # y = y - 1 ''' print(y) [[0. 1. 0. 0. 0. 0.] [0. 0. 1. 0. 0. 0.] [0. 0. 0. 1. 0. 0.] [0. 0. 0. 0. 1. 0.] [0. 0. 0. 0. 0. 1.] ...
import gin import pytest import numpy.testing as npt import tensorflow as tf import math def test_get_angles(): coordinates = tf.constant( [ [0, 0, 0], [0, 0, 1], [0, 0, -1], [0, 1, 0], ], dtype=tf.float32) angle_idxs = tf.constant( ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-11-14 21:20 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('usuarioAdministrador', '0008_auto_20171113_1533'), ] operations = [ migrations.Remo...
#!/usr/bin/env python # coding: utf-8 """pRESTo The program uses `curl` conventions when appropriate, but compatibility with `curl` is not a priority. Usage: presto-url.py [options] <url> presto-url.py -h | --help presto-url.py --version Options: -a Use authentication. It will use the default aut...
from zope.interface import Interface class IChildsDictLike(Interface): def __getitem__(child_key): """Get the object traversal child object"""
import torch import torch.nn as nn import numpy as np import cv2 from torch.nn import functional as F from collections import OrderedDict global glb_spatial_grad # dictionary saving gradient of intermediate feature global glb_feature global glb_c_grad global img_index # TODO: How about batch_size > 1 ??? def save...
import torch import numpy as np import numbers import random class Compose(object): def __init__(self, transforms): self.transforms = transforms def __call__(self, *img): for t in self.transforms: img = t(*img) return img class ToTensor(object): def __call__(self, *i...
class cal2: def setdata(self, radius): self.radius = radius print("Radius Set Succesfully! ") def area(self): radius = self.radius self.result = 3.14 * (radius**2) def display(self): self.area() print(f"Area of A Circle with {self.radius} is: {self.result}")...
# -*- coding: utf-8 -*- """ Created on Sun Jun 24 10:44:44 2018 @author: Ian """ import torch import torch.nn as nn import torch.nn.functional as F from torchvision import transforms, datasets, models import numpy as np import matplotlib.pyplot as plt if __name__ == "__main__": #define model classes clas...
class Solution: def subarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ dd, ss, count = {0:1}, 0, 0 for x in nums: ss += x c = dd.get(ss-k, None) if c != None: count += c ...
''' 矩阵中的路径 题目:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个 格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路 径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含 "abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。 ''' ''' 思路:优化版回溯法 1.将matrix字符串模拟映射为一个字符矩阵(但并不实际创建一个矩阵) 2.取一个boolean[matrix.len...
from experiments.classification import Classification from dataloaders.fer_loader import FERDataset from models.alex_net import AlexNet import pickle from scipy.misc import imread from utils.face_detector import FRDetector import matplotlib.pyplot as plt if __name__ == '__main__': # Training and saving classi...
import math import collections def getRoots(aNeigh): def findRoot(aNode,aRoot): while aNode != aRoot[aNode][0]: aNode = aRoot[aNode][0] return (aNode,aRoot[aNode][1]) myRoot = {} for myNode in aNeigh.keys(): myRoot[myNode] = (myNode,0) for myI in aNeigh: for ...
import json import logging from urllib.request import Request, urlopen from django.utils.functional import cached_property from reviewboard.admin.server import build_server_url from rbintegrations.basechat.forms import BaseChatIntegrationConfigForm from rbintegrations.basechat.integration import BaseChatIntegration ...
""" Script: util.py =============== Description: ------------ utilities for dealing with data Usage: ------ python preprocess.py -i $DATA_DIR -o data.df ################## Jay Hack jhack@stanford.edu Fall 2014 ################## """ import os import pickle as pkl import pandas as pd def load_data(num_...
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-19 14:36 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('df_shouye', '0012_pesticide'), ] operations = [ ...
#!/usr/bin/env python3 import argparse import csv import datetime import makegraph as mg import numpy as np import os import random import sys import tensorflow as tf from tensorflow.keras import backend as K from tensorflow.keras.layers import Layer from tensorflow.python.keras import activations from tensorflow.pyth...
lista = [] n = int(input()) for i in range(0, n): x, y = input().split(' ') n1 = int(x) n2 = int(y) if n2 == 0: lista.append('divisao impossivel') else: divisao = n1 / n2 lista.append(divisao) for c in range(0, len(lista)): print(lista[c])
#!/usr/bin/python import datetime, os, sys from pyasn1.codec.der import decoder # $ sudo apt-get install python-crypto sys.path = sys.path[1:] # removes script directory from aes.py search path from Crypto.Cipher import AES # https://www.dlitz.net/software/pycrypto/api/current/Crypto.Cipher.AES-module.html f...
# Normalna klasa # Przykład zastosowania class Stack2: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def __len__(self): return len(self.items) if __name__ == '__main__': import example2 ...
import pandas as pd import os import warnings warnings.filterwarnings('ignore') from sklearn.tree import DecisionTreeClassifier, export_graphviz from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score import numpy as np import ...
#!/usr/bin/python import re import sys import NER import subprocess a = NER.states() b = NER.dupli() c = NER.readFile() args = [] args.insert(0,a) args.insert(1,b) args.insert(2,c) file=open(sys.argv[1],'r') input = file.read() a = NER.find(input,'en',args) #print a
from django.shortcuts import render, redirect from .forms import NewReviewerForm, ReviewForm from django.contrib import messages from django.conf import settings from django.http import HttpResponse from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login as auth_login from postapp...
from clients import * from contracts import * from devices import * from reports import * from scans import * from schedules import * from vulnerabilities import *
# -*- coding: utf-8 -*- __author__ = 'lufo' import requests import json import os import subprocess from multiprocessing.dummy import Pool as ThreadPool def face_detection(img_path): """ 传入图片路径,判断图片中有没有人脸,使用YOLO :return: 有返回True,没有返回False """ path = '/Users/lufo/Downloads/darknet/' os.chdir(p...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import datetime class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='PKGame', fields=[ ('id', models...
"""Define vanilla CNNs with torch backbones, mainly for patch classification.""" import numpy as np import torch import torchvision.models as torch_models from torch import nn from torchvision.models import WeightsEnum from tiatoolbox.models.models_abc import ModelABC from tiatoolbox.utils.misc import select_device ...
import datetime import time from functools import wraps import logging logger = logging.getLogger(__name__) def time_consumed(func): @wraps(func) def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() elaps = str(datetime.timedelta(s...
import jax from jax import numpy as jnp, random import sys sys.path.append(".") from survae.nn.nets import MLP import survae from flax import linen as nn import numpy as np from survae.transforms import Abs from survae.distributions import Bernoulli rng = random.PRNGKey(0) rng, key = random.split(rng) x = random.unifo...
class A(): def test(self): print("AAAAAAAAAAA") class B(A): pass b = B() b.test()# 这样写子类继承AAAAAAA class A(): def test(self): print("AAAAAAAAAAA") class B(A): def test(self): print("BBBBBBBBBBBB") b = B() b.test()#这样写子类执行BBBBBB
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from .forms import ContactsForm from django.shortcuts import render from django.contrib import messages from django.shortcuts import render import logging l...
""" Implement an autocomplete system. That is, given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix. For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal]. Hint: Try preprocessing the dictionary into a more...
import FWCore.ParameterSet.Config as cms from EventFilter.HcalRawToDigi.hcallaserhbhehffilter2012_cfi import * hcallLaser2012Filter = cms.Sequence(hcallaserhbhehffilter2012)
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class MovieItem(scrapy.Item): mname = scrapy.Field() mdesc = scrapy.Field() mimg = scrapy.Field() mlink = scrapy.Field()
#! /usr/bin/env python import sys import random import time # data = sys.stdin.readlines() nums = random.sample(xrange(10000), 10000) def q_sort(nums, left, right): i, j = left, right pivot = int(nums[i] + nums[j]) / 2 while i < j: while nums[i] < pivot: i += 1 while nums[...
# -*- coding: utf-8 -*- #import unittest # 1. llamar libreria #import probando # 2. llamar la clase a probar # https://cgoldberg.github.io/python-unittest-tutorial/ # Todos los métodos que comiencen con el nombre test serán ejecutados. # probando testing #class TestUM(unittest.TestCase): # 3. heredar esto # ...
#!/usr/bin/env python import logging import signal from tornado.ioloop import IOLoop from client import BetelbotClientConnection from config import JsonConfig from topic import getTopics from util import Client, signalHandler def onTopicPublished(topic, data=None): # Callback function that prints the name of t...
import sys import math import datetime #dirname =sys.argv[1] subject=sys.argv[1] tstart=sys.argv[2] tstart=datetime.datetime.strptime(tstart,"%Y%m%d%H%M"); dirname='/srv/gsfs0/projects/ashley/common/device_validation/subject'+subject walk=open(dirname+'/samsung_walk_'+subject+'.tsv','r').read().replace(' ','').s...
import paramiko from sshtunnel import SSHTunnelForwarder import json import io import os import sys from base64 import b64decode from sqlbag import S, load_sql_from_file, temporary_database as temporary_db, sql_from_folder, raw_execute, DB_ERROR_TUPLE from migra import Migration from contextlib import contextmanager ...
## ## Lambda function to automatically remediate Evident signature: AWS:EC2 - default_vpc_check ## ## PROVIDED AS IS WITH NO WARRANTY OR GUARANTEES ## Copyright (c) 2016 Evident.io, Inc., All Rights Reserved ## ## ************************** !! W A R N I N G !! ************************** ## * Deleting the de...
base = 2 power = 1000 result = base**power s = 0 for digit in str(result): s += int(digit) print(s)
#This script will audit switchports to make sure access ports have portfast turned on. #It will also output cmd files which are remediation scripts that can later be run against all devices. from trigger.netdevices import NetDevices from ciscoconfparse import CiscoConfParse dataDir = '/var/data/network-backups/...
#通过用户输入三角形的边长 ,来计算三角形的面积 a = float(input("请输入第一边的长度 : ")) b = float(input("请输入第二边的长度 : ")) c = float(input("请输入第三边的长度 : ")) #判断三条线是否能组成三角形 if a+b+c-max(a,b,c)>max(a,b,c): #计算三角形的周长 p = (a + b + c)/2 #计算三角形面积 用了海伦公式 s = (p*(p-a)*(p-b)*(p-c))**0.5 print('三角形的面积是',s) else: print("上述三条边不满足构成三角形的条件...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2018 Intel Corporation # # 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 # # Un...
"""The 'Model' object will be used to configure and run a simulation for one islet. Instances are intended to be run in parallel and update a database file upon completion""" import pickle import configparser import ast import sys import os import sqlite3 import datetime import numpy as np import re from matp...
# Corrigido print('Exercício 006') print() # Recebe um número real n1 = float(input('Informe um número: ')) print() # Bloco de cálculos com o valor informado d = n1*2 t = n1*3 q = n1**0.5 # Fim dos cálculos # Retorna o resultado dos cálculos print('O dobro de {} é : {} \nO triplo de {} é: {} \nA raiz quadrada de {}...
#!/usr/bin/env python # coding: utf-8 # In[ ]: # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load in import numpy as np # linear algebra i...
from django.conf.urls import url, include from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from rest_framework import routers from places.apis_views import PlaceViewSet, GeoJsonViewSet from vocabs import api_views router = routers.DefaultRouter() router.regi...
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import json import pymysql from elasticsearch import Elasticsearch from twisted.enterprise import adbapi from tencentComment...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('twitter', '0026_auto_20160619_1941'), ] operations = [ migrations.RemoveField( model_name='tweet', n...
def isValidCommand(command): command = command.lower() parsed = command.split(" ") if(parsed[0] == "eat"): return True if(parsed[0] == "examine"): return True def processCommand(command, area): command = command.lower() parsed = command.split(" ") if(parsed[0] == "examine"): print("This room contains: ");...
DESKTOP = 'C:\\Users\\andre\\Desktop\\' # File Locations # ================================================== # Generated through get_from_twitter STREAM_DATA_TXT = DESKTOP + 'tweepy_output\\blizzard_stream_data.txt' STREAM_DATAFRAME_CSV = DESKTOP + 'blizzard_stream_dataframe.csv' # UPDATE AFTER PROTOTYP...
import json from chargebee.model import Model from chargebee import request from chargebee import APIError class Customer(Model): class BillingAddress(Model): fields = ["first_name", "last_name", "email", "company", "phone", "line1", "line2", "line3", "city", "state_code", "state", "country", "zip", "validat...
# Ao testar sua solução, não se limite ao caso de exemplo. e = float(input("numero de horas extras:")) f = float(input("numero de faltas: ")) h = e-(1/4*f) z = round(h,2) print(e,"extras e",f,"de falta") if(z > 400): print("R$ 500.0") else: print("R$ 100.0")
import sys sys.path.append('.') from enum import Enum from implementation.hash_table.hash_table import HashTable class CollisionHandler(Enum): LINEAR_PROBE = 1 QUADRATIC_PROBE = 2 DOUBLE_HASH = 3 """ Hash Table implementation using Open Addressing as its collision handling technique There are 3 available optio...
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> a = 12 >>> b = 33 >>> c = a + b >>> type(a) <class 'int'> >>> type(b) <class 'int'> >>> c 45 >>> a = "hello" >>> type(a) <class 'str'> >...
# ML hw4 problem 3. import numpy as np import matplotlib.pyplot as plt from sys import argv def elu(arr): return np.where(arr > 0, arr, np.exp(arr) - 1) def make_layer(in_size, out_size): w = np.random.normal(scale=0.5, size=(in_size, out_size)) b = np.random.normal(scale=0.5, size=out_size) return (w, b) def...
upperBound=355000 start=2 selected=[] for i in range(start,upperBound): number=str(i) tot=0 for digit in number: tot+=(int(digit)**5) if tot==i: selected.append(i) print(selected) output=0 for i in selected: output+=i print(output)
from datetime import datetime as dt from django.contrib.syndication.feeds import Feed as RssFeed from django.contrib.sites.models import Site from django.contrib.auth.models import User from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.http import Http404 from django.te...
class Array: def __init__(self, capacity=10): self._capacity = capacity self._length = 0 self._array = self._make_array(capacity) def _make_array(self, capacity): self._capacity = capacity return [None] * capacity def append(self, ele): if self._capacity == ...
from .nystrom_attention import NystromAttention from .nystromformer import Nystromformer from .version import __version__
import sys import yaml if __name__ == "__main__": sys.path.append("..") sys.path.append("./Tensorflow/models/research") from data.GUI.GUI import * with open(r'config.yml') as file: config = yaml.load(file, Loader=yaml.FullLoader) config['loader']['image_size'] = (config['loader']['default_...
import joblib import numpy as np import re from multiprocessing import Pool class ScikitClassifier: """ Adapted from https://nlpforhackers.io/training-ner-large-dataset/ """ def __init__(self, word2vec=None, clf=None, search=None): self.word2vec = word2vec self.clf = clf self....
""" 每行数据重复N次合并生成新文件 题目来源 http://www.bathome.net/thread-38017-2-1.html 依山居 0:54 2015/11/14 这个版本可以使用来处理实际数据。。。6百万行,大约17秒。。。 总结:几百万行数据真不算多。不需要逐行读取处理。python列表解析是个好东西~ 使用重复列表中元素更好的方法 http://www.oschina.net/question/96078_2141454 python笔记_列表解析 http://www.jianshu.com/p/c635d3c798c2 """ import time start=time.time() an=6 w...
import uuid import pandas from alpha_vantage.timeseries import TimeSeries from alpha_vantage.foreignexchange import ForeignExchange from confluent_kafka import Producer, Consumer from flask import jsonify class AlphaKafka(object): def __init__(self, host, ckey, csecret, akey): self.host = host se...