text stringlengths 38 1.54M |
|---|
# ------------------------ location ----------------------------------------
# PROJECT LOCATION
PROJECT_LOCATION = '/Users/sheetansh.kumar/PycharmProjects/TesVi/'
# MEDIA LOCATION
MEDIA_LOCATION = PROJECT_LOCATION + 'media/'
# video
VIDEO_LOCATION = MEDIA_LOCATION + 'video/'
VIDEO_LOCATION_STOCK = VIDEO_LOCATION +... |
import numpy as np
import matplotlib.pyplot as plt
import sys
fig = plt.figure()
file = "wyniki_2_"+sys.argv[1]+".txt"
data = np.loadtxt(file)
x=data[:,0]
y=data[:,1]
plt.plot(x, y, linewidth=1)
plt.axis([0,100,-100,600])
plt.title("k=10, transformata Fouriera")
plt.xlabel("$\omega$")
#plt.show()
plt.savefig("char... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 20 20:31:36 2020
@author: daihu
"""
import pandas as pd
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
# =============================================================================
# Dat... |
from model_DDDQN import select_action_for_evaluation, load_checkpoint
import gym
import torch
from itertools import count
# IMPORTANT: Set value for i_episode to indicate which checkpoint you want to use
# for evaluation.
i_episode = 1200
ckpt_dir = "DDDQN_SGD_CartPoleV1_obs_checkpoints/"
input_size = 4
output_size... |
import argparse
import logging
from typing import Set, Dict, Union
import requests
from bs4 import BeautifulSoup
from bs4.element import NavigableString
from tqdm import tqdm
IMDB_ADDRESS = 'https://www.imdb.com/'
SEARCH_ADDRESS = IMDB_ADDRESS + 'search/title'
MAX_FILMS = 1000
FILM_INFO_ROOT_ADDRESS = IMDB_ADDRESS + ... |
data = []
count = 0
with open('reviews.txt', 'r') as f:
for line in f:
data.append(line)
count += 1
if count % 1000 == 0:
print(len(data))
print('Total', count,'data')
sum_len = 0
for dat in data:
length = len(dat)
sum_len = length + sum_len #也可以直接寫成 sum_len += len(dat)
print('average length =', sum_l... |
from mcpi.minecraft import Minecraft
mc = Minecraft.create()
x, y,z = mc.player.getPos()
mc.setSign(x,y,z,63,0,"第一行","第二行","第三行","第四行")
|
#Ultrapassando Z
x = int(input())
z = int(input())
while x >= z:
z = int(input())
cont = 0
somaX = 0
while somaX < z:
somaX = somaX + x
x = x + 1
cont = cont + 1
print(cont)
|
import os
from selenium import webdriver
user = os.environ["BROWSERSTACK_USERNAME"]
key = os.environ["BROWSERSTACK_KEY"]
desired_cap = {
'browser': 'IE',
'browser_version': '8.0',
'os': 'Windows',
'os_version': '7',
'browserstack.local': True,
"browserstack.debug": True,
}
driver = webdriver.Remote(
c... |
"""
Log-likelihood comparison between online and offline EM.
"""
from copy import deepcopy
from global_utils import dump_results, get_num_true_clusters
from src.data_config import DataConfigs
from src.helpers.data_manager import DataManager
from src.parsers.multinomial_mixture_online import MultinomialMixtureOnline
d... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
#código filtro dados
#extrair todos os arquivos na mesma pasta que python estiver rodando.
#trocar o ano no nome do arquivo csv
#o procedimento pode ser feito para cada mês também.
#importando módulos
import pandas as pd
import glob
#criar lista com os arquivos do ano... |
from flask import Flask, request
from flask_restful import Api, Resource
from flask_restful import reqparse, abort
from mark_parser import mark_parser
from flask_cors import CORS
import uuid
import json
import os
env_dist = os.environ
import sys
sys.path.append("..")
from web_backend.common.util import *
projec... |
from django.conf import settings
from django.contrib.auth import get_user_model
from rest_framework import serializers
from versatileimagefield.serializers import VersatileImageFieldSerializer
from account.models import Result
User = get_user_model()
class ResultSerializer(serializers.ModelSerializer):
competit... |
import collections
import logging
import re
import arrow
import requests
import untangle
from citeomatic.utils import flatten
date_parser = re.compile(r'[^\d](?:19|20)\d\d[^\d]')
CURRENT_YEAR = arrow.now().year
EARLIEST_YEAR = 1970
def _all_text(doc):
child_text = [_all_text(c) for c in doc.children]
cdata_... |
import crc8
import sys
import json
from caesar_encryption import encriptar
inputValue = sys.argv[1]
ultimCRC = int(sys.argv[2])
dic = "abcdefghijklmnopqrstuvwxyz"
n = len(dic)
inputValueL = inputValue.lower()
hash = crc8.crc8()
hash.update(inputValue.encode('utf-8'))
s = int(hash.hexdigest(),16)
#Funcio encriptar d... |
class Factura:
def __init__(self,id_factura,fecha,dniEmisor,dniReceptor):
self.id_factura=id_factura
self.fecha=fecha
self.dniEmisor=dniEmisor
self.dniReceptor=dniReceptor
self.pagada=False
self.base=0.0
self.iva=21
self.total=0
self.lineasFact... |
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize("greeter.pyx"))
|
# Source: https://www.reddit.com/r/dailyprogrammer/comments/4jom3a/20160516_challenge_267_easy_all_the_places_your/?ref=search_posts
place = str(input("What place did your dog get: "))
while not place.isdigit():
place = input("Not a valid input, try again: ")
break
total = str(input("How many dogs competed: "... |
# Представьте, что вы работаете на заводе (с программистами такое тоже случается)
# по производству пирожков. Вас попросили написать программу, которая принимает
# на вход цену одного пирожка в рублях и копейках, а затем количество пирожков — целое число.
# Вывести нужно итоговую стоимость пирожков в рублях и копейках ... |
# Machine Learning/Data Science Precourse Work
# ###
# LAMBDA SCHOOL
# ###
# MIT LICENSE
# ###
# Free example function definition
# This function passes one of the 11 tests contained inside of test.py. Write the rest, defined in README.md, here, and execute python test.py to test. Passing this precourse work will gre... |
import pygame
pygame.init()
screen_dimensions = (640, 480)
BLUE = (0,0,255)
YELLOW = (250,230,140)
screen = pygame.display.set_mode((screen_dimensions))
x = 50
y = 50
w = 100
h = w
CIRCLE_RADIUS = int(w / 10)
square_rect = pygame.Rect(x, y, w, h)
pygame.draw.rect(screen, BLUE, square_rect)
pygame.draw.circle(scree... |
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from watchlist import db
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
username = db.Column(db.String(50))
password_hash = db.Colu... |
#
# License: BSD
# https://raw.github.com/yujinrobot/yujin_ocs/license/LICENSE
#
import threading
import rospy
import actionlib
import dynamic_reconfigure.client
from yocs_navigator import BasicMoveController
import std_msgs.msg as std_msgs
import vending_machine_msgs.msg as vending_machine_msgs
VM_INTERACTOR_ACTIO... |
# Generated by Django 3.1.7 on 2021-04-06 04:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('simple_project_app', '0002_auto_20210406_0429'),
]
operations = [
migrations.AlterField(
model_name='car_owner',
nam... |
class DistPar:
def __init__(self, pv, d):
self.distance = d
self.parent = pv
class Vertex:
def __init__(self, label):
self.label = label
self.isInTree = False
class Graph:
def __init__(self):
self.MAX = 20
self.INFINITY = 100000000
self.vertexes = []... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 31 11:47:39 2017
@author: Chris
"""
import pickle
import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def undist(img, calib_filename):
## load calibration data
calibration = pickle.load... |
# Generated by Django 3.0.5 on 2020-11-30 08:44
from django.db import migrations, models
import multiselectfield.db.fields
class Migration(migrations.Migration):
dependencies = [
('palak', '0012_auto_20201129_0006'),
]
operations = [
migrations.CreateModel(
name='Character_e... |
from datetime import datetime
from django.db import models
from time import strftime
# Create your models here.
class Fichier(models.Model):
name = models.CharField(max_length=30)
verdict = models.CharField(max_length=30)
created = models.DateTimeField()
jour = models.CharField(max_length=30)
de... |
try:
from unittest import mock
except ImportError:
import mock
from rest_social_email_auth import serializers
def test_create(user_factory):
"""
Test creating a new email address from the serializer.
Creating a new email address should also send a confirmation email
for the provided address. If the user does ... |
import json
import os
import random
from typing import List
import yaml
from log_setup import log
# -----------------------------------------------
from models.waypoint import Waypoint
from services import configuration_reader
cfg = configuration_reader.get_config()
waypoint_directory_path = f"{cfg['data_dir']}{cfg... |
import numpy as np
# library for plotting arrays
import matplotlib.pyplot as plt
from NeuralNetwork import NeuralNetwork
if __name__ == '__main__':
# number of input, hidden and output nodes
input_nodes = 784
hidden_nodes = 200
output_nodes = 10
# learning rate
learning_rate = 0.1
# creat... |
# Copyright 2020 Xilinx 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 writing, ... |
class MemcacheQueue(object):
def __init__(self, name, memcache_client):
self.name = name
self.mc_client = memcache_client
self.last_read = '_mcq_%s_last_read' % name
lr = self.mc_client.get(self.last_read)
if not lr:
self.mc_client.set(sel... |
import sys
sys.path.append(r"C:\local_software\HEC-DSSVue-v4.0.00.345\jar\sys\jythonUtils.jar")
sys.path.append(r"C:\local_software\HEC-DSSVue-v4.0.00.345\jar\hec.jar")
sys.path.append(r"C:\local_software\HEC-DSSVue-v4.0.00.345\jar\jython-standalone-2.7.0.jar")
sys.path.append(r"C:\local_software\HEC-DSSVue-v4.0.00.345... |
# Generated by Django 2.1.2 on 2018-11-12 16:42
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),
]
ope... |
from db.config import SQLiteConfig
from helpers.token.config import TokenConfig
from transport.sanic.config import SanicConfig
class ApplicationConfig:
sanic: SanicConfig
token: TokenConfig
database: SQLiteConfig
def __init__(self):
self.sanic = SanicConfig()
self.database = SQLiteCon... |
import tensorflow as tf
import numpy as np
class BiLSTMAttention(object):
def __init__(self, layers, max_length, n_classes, vocab_size, embedding_size=300, batch_size = 64, l2_reg_lambda=1e-5, gamma=2.0, mp=2.5, mn=0.5, use_ranking_loss=False):
self.input_text = tf.placeholder(tf.int32, shape=[None, max_length], na... |
from discord.ext import commands
class Info(commands.Cog):
"""Basic info about the bot. Includes ping command and stuff idk"""
def __init__(self, bot):
self.bot = bot
self.atext = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
self.charmap = {}
al = 97
... |
"""first_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cla... |
# -*- coding: utf-8 -*-
import re
# s1 = "Boeing has unveiled its newest line of business jets, which the company says will allow VIP travelers to fly nonstop between any two cities on Earth."
s1 = "Boeing is a USA company. USA has many giant companies, including Boeing"
print(re.findall('Boeing$', s1))
|
from chainer.links.caffe.protobuf3 import caffe_pb2 as caffe_pb
from chainer.function_hooks import timer
from chainer.links.caffe import CaffeFunction
from chainer import cuda
from chainer import function
import chainer.links as L
import chainer.functions as F
from chainer import link
from chainer import function
impo... |
# -*- coding:utf-8 -*-
import xlrd
import os
import json
#path = os.getcwd()+r'\excel'
path = r'D:\Python\pytest'
targetPath = r'D:\Python\pytest\json'
os.chdir(path)
def readExcel(path):
#open_workbook打开一个excel文件
workBook = xlrd.open_workbook(path)
#遍历所有的sheet
for sheet in workBook.sheet_names():
... |
from django.shortcuts import render
from .models import Message
from .utils import send_results
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
@api_view(['GET'])
d... |
import pickle
import os.path
from os import path
import pandas as pd
from datetime import datetime, date, timedelta
if path.exists('transactions.pickle'):
exists = True
with open('transactions.pickle', 'rb') as f:
transactions = pickle.load(f)
else:
exists = False
transactions = pd.DataFrame... |
# encoding: utf-8
print cmp(42, 32)
print cmp(99, 100)
print cmp(10, 10)
numbers = [5, 2, 9, 7]
numbers.sort(cmp)
print numbers
x = ['aardvark', 'abalone', 'acme', 'add', 'aerate']
x.sort(key=len)
print x
x = [4, 6, 2, 1, 7, 9]
x.sort(reverse=True)
print x
|
import numpy as np
import pandas as pd
from tqdm import tqdm as tqdm
import os
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
from core.attacks import create_attack
from core.metrics import accuracy
from core.models import create_model
from .context import ctx_noparamgrad_and_eval
fro... |
import cv2
import numpy as np
import os
MAX_MATCHES = 500
GOOD_MATCH_PERCENT = 0.15
CWD_PATH = os.getcwd()
IMAGE_NAME = 'test_images/000448.jpg'
PATH_TO_IMAGE = os.path.join(CWD_PATH,IMAGE_NAME)
PATH_TO_OUTPUT = os.path.join(CWD_PATH,'output')
def alignImages(im1, im2):
# convert image to grayscale
im1Gray =... |
metadata = """
summary @ Ontologies necessary for the Nepomuk semantic desktop
homepage @ http://sourceforge.net/apps/trac/oscaf/
license @ GPL
src_url @ http://downloads.sourceforge.net/oscaf/$fullname.tar.bz2
arch @ ~x86_64
"""
depends = """
build @ dev-util/cmake
"""
get("main/cmake_utils")
|
# MIT License
#
# Copyright (c) 2016 Sam Holden
#
# 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, modify,... |
#version 0.0
print('不知道如何便捷的运行ruby代码或者是转换成其他语言,如有知道的请联系')
print('未完成,如需要请参见原作者代码:.\\Library\\rrencode\\rrencode.rb')
print('原作者网站已经404,在时光机可以找到当时的信息:')
print('https://web.archive.org/web/20090801052909/http://www.lab2.kuis.kyoto-u.ac.jp/~yyoshida/rrencode.html') |
# -*- coding:utf-8 -*-
from pages.base_page import BasePage
from time import sleep
class InventoryManageDeviceListPage(BasePage):
'''库存管理-设备列表页面'''
inventory=[u'业务管理',u'渠道资源管理',u'库存管理']
def open_inventory_manage(self,open_list=inventory):
'''打开库存管理'''
self.click_button_for_one(open_list... |
import requests
import json
from ..exceptions import AMSNotAvailable, OwnerNameNotFound
from ..config import AMS_URL
def get_owner_id_by_name(owner_name):
request_url = '%s/accounts/%s' % (AMS_URL.strip('/'), owner_name)
try:
r = requests.get(request_url)
except:
raise AMSNotAvailable('AMS... |
list1 = [23, 44, 55, "Testing", 32]
list2 = [34,23, 34, 45, "Testing"]
list3 = list1 + list2
# length of list
print(len(list1))
list1.insert(4, "www.gmail.com")
print(len(list1))
# Compare 2 list are same or not
# cmp (list1, list2) # cmp will work only on python2 not on python 3 hence ignore
# concatenate the list
p... |
# coding: utf-8
from __future__ import division, print_function
import tensorflow as tf
import numpy as np
import argparse
import cv2
import math
import os
from utils.misc_utils import parse_anchors, read_class_names
from utils.nms_utils import gpu_nms
from utils.plot_utils import get_color_table, plot_one_box
from ... |
#!/usr/bin/env python
import numpy as np
def add_yborder(img,
matchbg=True):
# get img dimensions
height, width = np.shape(img)
# amount of padding
padd = int((width - height) / 2)
# make square canvas
canvas = np.zeros((height + padd * 2, height + padd * 2))
if matchbg:... |
#!/usr/bin/env python
def hcf(int1, int2):
'''calculate the highest common factor of two integers'''
for i in range(1, min(int1, int2) + 1):
if min(int1, int2) % i == 0:
if max(int1, int2) % i == 0:
hcf = i
return hcf
def lcm(int1, int2):
'''calculate the least common multiple of two intergers'''
... |
#coding:utf-8
from collections import namedtuple
from collections import OrderedDict
price_str = '30.14,29.58,26.36,32.56,32.82'
# 数组,有序
price_array = price_str.split(',')
date_base = 20170118
date_array = [str(date_base + ind) for ind, _ in enumerate(price_array)]
# print(date_array)
stock_tuple_list = [(date, pri... |
import pyglet
import pyglet.gl as gl
import pyglet.window.key as key
import theatre
#basic settings
class Settings(object):
width = 640
height = 480
dim = 640,480
class Position(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
class Velocity(object):
def __init__(s... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import copy
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
fr... |
from matplotlib import pyplot as plt
def build_schedule(data_frame, name_list, by_sett):
for name in name_list:
if type(data_frame[name][1]) is str:
plt.scatter(data_frame[by_sett], data_frame[name], label=name + ' direction', color='green')
plt.xlabel(by_sett, fontsize=20)
... |
# coding: utf-8
import turtle as t
def draw_body():
"""
画小猪佩奇的身体
:return: null
"""
t.color((255, 99, 71), "red")
t.pu()
t.seth(90)
t.fd(-20)
t.seth(0)
t.fd(-78)
t.pd()
t.begin_fill()
t.seth(-130)
t.circle(100, 10)
t.circle(300, 30)
... |
import numpy as np
import matplotlib.pyplot as plt
import LatticeDefinitions as ld
import GeometryFunctions as gf
import GeneralLattice as gl
import LAMMPSTool as LT
import copy as cp
import sys
import os
strDirIn = sys.argv[1]
strTemplate = sys.argv[2]
for j in os.listdir(strDirIn):
if j.endswith('.dmp'):
... |
# Copyright (c) 2014 Mirantis 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 ... |
import pprint
from enricher import add_or_update_most_likely_correct, add_median_cooccurrence, combine_fields
from enricher import add_is_a_place_frequency
from marge.config import config
from marge.utils import to_dicts
from marge.models import Model
pp = pprint.PrettyPrinter(indent=4)
m1 = Model("first_pass")
m1.... |
import pyowm, json, datetime
from pytz import timezone
from geopy import geocoders
owm = pyowm.OWM('aa16d2e6e3a3c13b30140edfb4a81b9c', language='ru')
all_locations = ['Severodonetsk', 'Kiev', 'Kharkov', 'Lvov', 'Odessa', 'Barcelona', 'London', 'Madrid', 'Paris', 'Berlin', 'Lissabon']
def weather_at_any_city(located... |
# Generated by Django 2.1.5 on 2019-02-01 00:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('service20', '0006_auto_20190201_0018'),
]
operations = [
migrations.AlterField(
model_name='ms_apl',
name='gen',
... |
# Generated by Django 3.0.12 on 2021-08-11 12:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0019_auto_20210811_1253'),
]
operations = [
migrations.AlterField(
model_name='articleitems',
name='name',
... |
from character.masteries.Masteries import Masteries
from game_objects.battlefield_objects import BaseType, Unit
from game_objects.monsters.MonsterEquipment import MonsterEquipment
import copy
class Monster:
def __init__(self, base_type: BaseType, items = None, masteries : Masteries = None ):
if items:
... |
import numpy as np
import sys
import FluidGeo
def pair_sort(a,b):
return (a,b) if a < b else (b,a)
def node_type(n):
'''
return node type
:param n: node id for bumpy wing mesh
:return: 0:lead edge
1:top
2:trialing edge
3:bottom
'''
if(n>=484 and n <... |
from iotrain.api import utils
from iotrain.api.entities import Direction, Speed
from iotrain.api.usecases import IMotorGateway
class MotorGateway(IMotorGateway):
def __init__(self, motor):
self.motor = motor
@utils.logging
def control(self, direction: Direction, speed: Speed):
if directio... |
def perfectScore(number):
out = 0
for num in range(1,number):
if number % num == 0:
out+=num
return out
if __name__ == '__main__':
num1, num2 = tuple([int(_) for _ in input('').split(' ')])
out = [0,0,0]
for num in range(num1, num2+1):
if num < perfectScore(num):
... |
"""
This script creates a file with one line per image size. Each line has the
height, width, and total number of pixels followed by the number of bits that
should be embedded in the experiments. These numbers are O(1), O(sqrt(n)),
O(sqrt(n)*log(n)), and O(n) in the total number n of pixels in each image size.
The fil... |
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.feature_selection imp... |
import urllib
import os, sys
class GIT:
api_uri = 'https://api.github.com'
user_name = ''
user_data = {}
verbose = False
def __init__(self, user, verbosity):
self.user_name = user
self.verbose = verbosity
self.user_data = self.check_user_exists()
self.user_data['r... |
items = [1, 2, 3]
# Get the iterator
it = iter(items) # Invokes items.__iter__()
"""
# Run the iterator
print(next(it)) # Invokes it.__next__()
print(next(it))
print(next(it))
print(next(it))
Traceback (most recent call last):
File "c:/Users/XiaoBinDai/Documents/GitHub/learn-python/Basis/test_iter.py", line 11,... |
#!/usr/bin/python3
"""Unittest for state
"""
import unittest
from models.base_model import BaseModel
from models.amenity import Amenity
import os
import uuid
import datetime
from models.engine.file_storage import FileStorage
from models import storage
class Test_Amenity_class(unittest.TestCase):
"""
Defines... |
num = int(input())
d = 0
for c in range(1, num + 1):
x = input().split()
a, b, = x
s = 0
a = int(a)
b = int(b)
if a > b:
for d in range(int(b)+1, int(a)):
if d % 2 != 0:
s = s + d
if a < b:
for d in range(int(a)+1, int(b)):
if d % 2 !... |
import pandas as pd
import numpy as np
### Importing aggregated data
df = pd.read_csv('/Users/kunal/Documents/RIC/crude oil price /NewsData/Classification/newdata.csv',encoding='ISO-8859-1')
#### Basic feature extraction from text data
#Dropping unnessary columns
list(df)
df.drop(['Unnamed: 0','uuid','Date','ti... |
# Copyright 2019 Glen Harmon
# inetnum Object Description
# https://www.ripe.net/manage-ips-and-asns/db/support/documentation/ripe-database-documentation/rpsl-object-types/4-2-descriptions-of-primary-objects/4-2-4-description-of-the-inetnum-object
from .rpsl import Rpsl
class INetNum(Rpsl):
def __init__(self):... |
from pyForms.PageClasses import Page
from pyForms.controlManager import registerControl
from pyForms.ControlBase import Base as CustomControl
from pyForms.PageControllerClasses import PageController
from pyForms.PageControllerClasses import TemplateController
from pyForms.servers.tornado import tornadoHandler
impor... |
# #Plotting the line of best fit the hard way
#
# import pandas as pd
# import numpy as np
# import matplotlib.pyplot as plt
# %matplotlib inline
# # x = [0,1,2,3,4,5]
# # y = [0,1,2,3,4,5]
# #
# #
# # x = np.asarray([0,1,2,3,4,5])
# # y = -2*x
# # plt.plot(x,y, color = 'indigo', alpha = 0.6)
# # plt.show()
#
# xs = ra... |
#This code designed to fetch all the trajectory data from the alfred folder in an organized fashion
import os
import sys
os.environ['ALFRED_ROOT'] = '/alfred'
sys.path.append(os.path.join(os.environ['ALFRED_ROOT']))
sys.path.append(os.path.join(os.environ['ALFRED_ROOT'], 'gen'))
sys.path.append(os.path.join(os.environ... |
#!/usr/bin/env python3
"""Initialize and forward prop for a bidirectional rnn cell"""
import numpy as np
class BidirectionalCell:
"""Bidirectional cell class"""
def __init__(self, i, h, o):
self.Whf = np.random.normal(size=(i + h, h))
self.Whb = np.random.normal(size=(i + h, h))
... |
"""
Detect peaks for GMRF nanocuvette spectra.
Code by emiho.
2018-06-16 emiho
"""
import numpy as np
import matplotlib.pyplot as plt
from _modules.detect_peaks import *
def detect_peaks_valleys_gmrf(spectrum):
idx_p = detect_peaks(spectrum, mph=0.2, mpd=5, threshold=0.0001, edge=None)
idx_v = detect_pe... |
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you ma... |
# import the necessary packages
import numpy as np
import cv2
import imutils
class ColorDescriptor:
def __init__(self, bins):
# store the number of bins for the 3D histogram
self.bins = bins
def describe(self, image):
# convert the image to the HSV color space and initialize
# ... |
from examples_shared import init_client, init_parser, print_response
def list_price_lists(client):
"""
List domain price lists.
"""
return client.domain.price_lists.all()
if __name__ == "__main__":
parser = init_parser(description='Domain pricing example.')
args = parser.parse_args()
cl... |
# -*- coding: utf-8 -*-
import logging
import os
import re
from collections import namedtuple
logging.basicConfig(filename="./convert.log", level=logging.DEBUG)
Header = namedtuple('Header', ['title', 'date', 'tags', 'status', 'category'])
fname_re = re.compile(r'\.rst$')
class ErrorBlog(Exception):
def __init_... |
import pandas as pd
from sklearn.base import TransformerMixin
class DateDummy(TransformerMixin):
def __init__(self, *args):
self.args = args
def fit(self, X, y=None):
return self
def _get_dummy_variables(self, X):
for arg in self.args:
date_feature = getattr(X.inde... |
"""По данной непустой строке ss длины не более 104104,
состоящей из строчных букв латинского алфавита, постройте оптимальный беспрефиксный код.
В первой строке выведите количество различных букв kk, встречающихся в строке, и размер получившейся закодированной строки.
В следующих kk строках запишите коды букв в формате ... |
import os
from shutil import copyfile
def img2iddir(src_dir, dst_dir):
if not os.path.exists(src_dir):
return
if not os.path.isdir(dst_dir):
os.mkdir(dst_dir)
for root, dirs, files in os.walk(src_dir, topdown=True):
for name in files:
if name.split('.')[-1] not in ['jpg... |
import random
from time import sleep
print('=+'*30)
print(' JOGO DA MEGA SENA ')
print('=+'*30)
quant=(int(input('Quantos jogos você quer sortear? : ')))
lista=[]
jogos=[]
cont=tot=0
l=0
while tot<= quant-1:
cont = 0
while True:
numeros = random.randint(1, 60)
... |
import time
import torch
import torch.nn as nn
from torch.autograd import Variable
from core.const import ALL_CATEGORIES, N_CATEGORIES, N_HIDDEN, N_LETTERS
from core.model import RNN
from core.utils import line_to_tensor, load_categories, random_choice, time_since
N_EPOCHS = 100000
PRINT_EVERY = 5000
PLOT_EVERY = 10... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
import tvshows.urls
import movies.urls
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'tomatoPy_admin.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),... |
# Write your code here
import random
print("H A N G M A N")
choice = input('Type "play" to play the game, "exit" to quit: ')
lis = ['python', 'java', 'kotlin', 'javascript']
c_word = random.choice(lis)
w_lis = list(c_word)
b_lis = list(c_word)
count = 0
check = []
for i in range(len(b_lis)):
b_lis[i] = '... |
#!/usr/bin/python
#this program calculates the difference in lengths of
#regions given in each row of csv file for all variants
#given at command line
import sys
import csv
import re
inputlist= sys.argv
inputlist.pop(0)
#Open file with windows,
win = open('windows.csv', 'r')
wincsv = csv.reader(win, delimiter='\t... |
# Copyright (c) 2011 - 2017, 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
#
# Unless required by applicable law or agre... |
sentences = {
'Kim': 'Nutmeg rolled in a bed of flowers. ',
'Tijuan': 'Nutmeg jumped over the moon. ',
'Allison': 'Nutmeg patrols the neighborhood for gremlins. ',
'Chris': 'Nutmeg races for pink slips against Dominic Torreto. ',
}
# for name, sentence in sentences.items():
# print(name + ': ' + se... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import re
import math
import random
import collections
from decimal import Decimal
from typing import List, Dict, Tuple, Pattern, Match, Type
import mojimoji
class DiceCommandProcessorException(Exception):
pass
class InvalidFormulaException(... |
##############################################################################
# Australian Public Licence B (OZPLB)
#
# Version 1-0
#
# Copyright (c) 2007, Open Kernel Labs, Inc.
#
# All rights reserved.
#
# Developed by: Embedded, Real-time and Operating Systems Program (ERTOS)
# National ICT Austr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.