text stringlengths 8 6.05M |
|---|
import torch
from torch_geometric.datasets.molecule_net import x_map as x_map_default
from torch_geometric.datasets.molecule_net import e_map as e_map_default
def get_atom_feature_dims():
allowable_features = x_map_default
return list(map(len, [
allowable_features['atomic_num'],
allowable_fea... |
a = [0]
memo = {}
memo[0] = 1
for x in xrange(1,500001):
test = a[x-1] - x
if test > 0 and test not in memo:
memo[test] = 1
a.append(test)
else:
memo[test + 2*x] = 1
a.append(test + 2*x)
k = int(raw_input())
while k != -1:
print a[k]
k = int(raw_input()) |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'LotteryCountryDivision'
db.create_table(u'lottery_country... |
import numpy as np
import cv2
import imutils
from collections import deque
red_lower_bound = np.array([0, 100, 100]) # HSV format
red_upper_bound = np.array([20, 255, 255])
lower_bound = red_lower_bound
upper_bound = red_upper_bound
# BGR format
# Blue Red Green ... |
import json
import os
import warnings
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from skimage.transform import downscale_local_mean
from skimage import io, img_as_uint
from tqdm import tqdm_notebook, tqdm
from zipfile import... |
from .trainer import Trainer
from .make_optimizer import make_optimizer,make_scheduler |
from typing import Dict
import logging
import os
import random
from overrides import overrides
from allennlp.data.instance import Instance
from allennlp.data.tokenizers.tokenizer import Tokenizer
from allennlp.data.tokenizers import WordTokenizer
from allennlp.data.dataset_readers.dataset_reader import DatasetReader
... |
"""
Something goes here right?
"""
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.utils.html import escape
from django.http import JsonResponse
import datetime
from django.contrib.auth.decorators import login_required
from django.template import RequestContext... |
# -*- coding: utf-8 -*-
from jinja2 import Environment, FileSystemLoader
from modules.httpcore import HttpRequest, HttpException
from models.demo import say_hello
from config import *
j2_env = Environment(loader=FileSystemLoader(TEMPLATES), trim_blocks=True, autoescape=True)
class Index(HttpRequest):
def get(sel... |
def merge_sort(arr, left, right):
if left < right:
mid = int((left + right) / 2)
merge_sort(arr, left, mid)
merge_sort(arr, mid+1, right)
merge(arr, left, mid, right)
def merge(arr, left, mid, right):
n1 = mid - left + 1
n2 = right - mid
# create temp arrays
larr ... |
#Grading students
n = int(input().strip())
res = []
def get5(num):
while num % 5:
num += 1
return num
for i in range(n):
grade = int(input().strip())
if grade < 38:
res.append(grade)
else:
mul = get5(grade)
... |
# Generated by Django 3.0.7 on 2020-07-27 00:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Risk_project_ufps', '0005_auto_20200701_2149'),
]
operations = [
migrations.CreateModel(
name='... |
import os, sys, random, time
import enum
from random import choice
from baseClasses import genders, Countries, fileName
voices = {
Countries.Australian : {
genders.male:["Lee"],
genders.female:["Karen"]
},
Countries.Indian : {
genders.male:["Rishi"],
genders.female:["Veena"... |
import pygame
import random
pygame.init()
# ----- Gera tela principal
WIDTH = 800
HEIGHT = 400
janela_jogo = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption('Catch em` all ')
white = (255,255,255)
color_dark = (0,0,0)
#===TELA DE INICIO===
tela_inicio=False
instrucoes = True
game... |
def test_sample():
print("BUILD")
|
#!/usr/bin/python3
""" Does deployment"""
from fabric.api import *
import os
from datetime import datetime
import tarfile
env.hosts = ["35.237.254.224", "34.73.109.66"]
env.user = "ubuntu"
def deploy():
""" Calls all tasks to deploy archive to webservers"""
tar = do_pack()
if not tar:
return Fal... |
from flask import render_template, redirect, url_for,request
from . import main
from ..models import Sources
from ..request import get_sources, get_articles, topheadlines, everything
@main.route('/')
def index():
'''
message = 'Hello World'
'''
cat_general = get_sources('general')
cat_business = get_so... |
import flask
import json
import requests
import settings
import scraper
app = flask.Flask(__name__)
@app.route("/")
def route():
# s = scraper.Scraper()
wins = []
# windows = s.scrape()
with open('windows.json', 'r') as f:
windows = json.load(f)
for window in windows:
w = json.load... |
wort = "unverändertes Wort"
zahl = 10
liste = [10, 20, 25, 35]
# bonus
dicte = {"a": "1"}
inner_print = "Innerhalb der Funktion: "
outer_print = "Außerhalb der Funktion: "
def parameteruebergabe(_):
wort = "verändertes Wort"
print(f"{inner_print}{wort}")
def parameteruebergabeInt(_):
zahl = 5
print(... |
import numpy
import struct
import pyaudio
import threading
import struct
from collections import deque
from bibliopixel import LEDMatrix
from bibliopixel.animation import BaseMatrixAnim
import bibliopixel.colors as colors
class Recorder:
"""Simple, cross-platform class to record from the microphone."""
def ... |
from queries.base import Base
from queries.message import Message
class QueryTypePagination(Base):
def __init__(self, sdk):
super().__init__(sdk)
self.limit_per_page = 5
@staticmethod
def name():
return 'pagination'
async def create(self, payload, data):
"""
... |
#coding:utf-8
import tornado.web
import tornado.ioloop
import hashlib
class htmlHandle(tornado.web.RequestHandler):
def get(self):
print('html ----> start 0')
self.render('index.html',list_info = [11,22,33])
settings = {
'template_path': 'template',
'static_path': 'static',
... |
from django.contrib import admin
from explorer.models import Query
from explorer.actions import generate_report_action
class QueryAdmin(admin.ModelAdmin):
list_display = ('title', 'description', 'created_by_user',)
list_filter = ('title',)
raw_id_fields = ('created_by_user',)
actions = [generate_... |
from stemming.porter2 import stem
import sys
import numpy as np
vocab = {}
foobar = [".", ",", "(", ")", '"', "'"]
with open("sentiment.txt") as f:
lines = f.readlines()
for line in lines:
line = line[:-1].lower().strip()
words = line.split(" ")[1:]
words = [word.strip() for word in wo... |
import unittest
class MyTestCase(unittest.TestCase):
def test_readme_example1(self):
from rdflib import RDFS, OWL, Namespace
from funowl import OntologyDocument, Ontology
EX = Namespace("http://www.example.com/ontology1#")
o = Ontology("http://www.example.com/ontology1")
o... |
import requests
import json
from django.http import HttpResponse
def getEdgeinfo():
name1 = "扎克伯格"
name2 = "文继荣"
url = "http://websensor.playbigdata.com/fss3/service.svc/GetSearchResults"
querystring = {"query": name1 + " " + name2, "num": "5", "start": "1"}
headers = {
'user-agent': "M... |
import csv
import sys
import collections
import operator
import datetime
today = datetime.date.today()
sunday = today - datetime.timedelta(today.weekday()+1)
ifile = open(sys.argv[1],"rb")
reader = csv.reader(ifile)
rownum = 0
low = 0
high = 0
datelist = []
datelistDict = {}
datelistDict['Monday'] = 0
datelistDict[... |
'''
Created on Dec 10, 2013
@author: Raul
'''
class UserType():
'''
User Type
'''
visitor="Visitor"
student="Student"
tutor="Tutor"
admin="Admin"
Value={0:"Visitor",1:"Student",2:"Tutor",3:"Admin"}
#----------------------------------------------------------------- ... |
"""
Code by Matteo Zanotto and Riccardo Volpi on top of
CRBM code (by Graham Taylor).
Theano CRBM implementation.
For details, see:
http://www.uoguelph.ca/~gwtaylor/publications/nips2006mhmublv
Sample data:
http://www.uoguelph.ca/~gwtaylor/publications/nips2006mhmublv/motion.mat
"""
import numpy
import numpy as np
im... |
from cnn.lstm import add
import pytest
@pytest.fixture
def test_init():
# assert add(2, 3) == 5
print('init test mock')
def test_add():
assert add(2, 10) == 12
|
# -*- coding: utf-8 -*-
from django.apps import AppConfig as BaseAppConfig
from django.utils.translation import ugettext_lazy as _
class AppConfig(BaseAppConfig):
name = 'knowledge'
verbose_name = _('База знаний')
def ready(self):
from knowledge import signals # flake8: NOQA
|
from datetime import date
from onegov.ballot import Election
from onegov.ballot import ElectionCompound
from onegov.ballot import Vote
from onegov.core.utils import Bunch
from onegov.election_day.models import Notification
from onegov.election_day.models import WebsocketNotification
from onegov.election_day.utils impor... |
#!/usr/bin/env python3
langs = {"Perl", "Python", "Java", "Go", "C++", "Rust"}
for l in langs:
print(l)
|
#!/usr/bin/python
from lwr_incr2 import *
#from lwr_incr3 import *
def ToStr(*lists):
s= ''
delim= ''
for v in lists:
s+= delim+' '.join(map(str,list(v)))
delim= ' '
return s
def ToList(x):
if x==None: return []
elif isinstance(x,list): return x
elif isinstance(x,(np.ndarray,np.matrix)):
i... |
"""
VMWare Backup Internals
Some References that might of been used (or not)
VMWare Command Line
https://www.vmware.com/support/ws5/doc/ws_learning_cli_vmrun.html
Linux Scheduler:
http://stackoverflow.com/questions/1603109/how-to-make-a-python-script-run-like-a-service-or-daemon-in-linux
http://unix.stackexchange.com... |
from ED6ScenarioHelper import *
def main():
# 封印区域 第四层
CreateScenaFile(
FileName = 'C4311 ._SN',
MapName = 'Grancel',
Location = 'C4311.x',
MapIndex = 1,
MapDefaultBGM = "ed60035",
Flags = 0,
... |
#========================================================================#
# Submit LSWT L3U processing job to lotus
# (To be run from cron server)
#------------------------------------------------------------------------#
# This script invokes L3U processing, automatically followed by L3C-daily
# and L3C-dekadal proce... |
"""
#------------------------------------------------------------------------------
# Create ZV-IC Shaper
#
# This script will take a generalized input from an undamped second order system subject
# to nonzero initial conditions and solve the minimum-time ZV shaper using optimization
#
# Created: 6/20/17 - Daniel Newm... |
import torch
import torch.nn as nn
import numpy as np
from edflow.util import retrieve, get_obj_from_str
class Shuffle(nn.Module):
def __init__(self, in_channels, **kwargs):
super(Shuffle, self).__init__()
self.in_channels = in_channels
idx = torch.randperm(in_channels)
self.regist... |
from django.contrib import admin
from member.models import Profile, Organisation, Competition, Ticket
import logging
g_logger = logging.getLogger(__name__)
class TicketInline(admin.TabularInline):
model = Ticket
extra = 0
readonly_fields = ('used', 'token')
def has_delete_permission(self, request, o... |
import numpy as np
import pprint
import pandas as pd
import datetime as dt
from collections import defaultdict
import matplotlib.pyplot as plt
from investagram_data_loader.repository.sqlite_dao import SqliteDao
STOCK_CODE = '2GO'
BROKERS = ['BDO', 'ATR']
START_DATE, END_DATE = dt.date(2021, 1, 1), dt.date(2021, 2, 24)... |
N = int(input())
K = int(input())
X = list( map( int, input().split()))
ans = 0
for i in range(N):
ans += min(abs(X[i]),abs(X[i]-K))*2
print(ans)
|
#!/usr/bin/env python
import sys
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-i", "--file", dest="inputFileName",
help="path to input file")
parser.add_option("-o", "--output", dest="outputFileName",
help="output file name (without extension)")
parse... |
import random
class Environment(object):
def __init__(self, size):
self.agent_pos = 0
self.agent_reward = 0
self.agent_step = 0
self.size = size
self.map = [False] * self.size
def add_random_dirt(self):
for i in range(int(self.size / 5) + 1):
index =... |
def isSelfCrossing(self, x):
return any(d >= b > 0 and (a >= c or a >= c-e >= 0 and f >= d-b)
for a, b, c, d, e, f in ((x[i:i+6] + [0] * 6)[:6]
for i in xrange(len(x))))
class Solution:
def isSelfCrossing(self, x):
b = c = d = e = 0
for a ... |
"""
kullanıcıdan 3 basamaklı bir sayı okuyup sayının bas tersten yazılımı ile
elde edilecek sayının okunan sayıya eşit olup olmadığını kontrol eden bir algo
ÖRN: girdi 575 ise algo "eşit" çıktısını, 134 olduğunda ise "eşit değil" çıktısını vermelidir
"""
sayi=int(input("3 Basamaklı Bir Sayi Giriniz: "))
a=sayi%10 #... |
#!/usr/bin/python
import os
import subprocess
import sipconfig
import PyQt5.QtCore
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
class BuildExt(build_ext):
def run(self):
for path in files_to_moc:
moc = path_of_moc_file(path)
cmd = 'mo... |
"""Login urls."""
from django.urls import path
from django.conf.urls import url
from . import views
urlpatterns = [
path('signup', views.signup, name='signup'),
url('account_activation_sent/$', views.account_activation_sent,
name='account_activation_sent'),
path('activate/<uidb64>/<token>/', vie... |
from __future__ import absolute_import, unicode_literals
from celery import shared_task
from datetime import datetime, date
from django.utils import timezone
from product.models import Product
from amdtelecom.celery import app
# @shared_task
# def new_prod_published_date():
# products = Product.objects.filter(is... |
from django import forms
import datetime
from django.forms.fields import ChoiceField, IntegerField
from django.utils.text import slugify
import datetime
class InputDataForm(forms.Form):
ph = forms.FloatField()
hardness = forms.FloatField()
solids = forms.FloatField()
chloramines = forms.FloatFie... |
#!/usr/bin/env python
import os
import sys
from text_template import TextTemplate as view
youtube_link = sys.argv[1]
image_name = sys.argv[2]
url_name = sys.argv[3]
dir_path = os.path.dirname(os.path.realpath(__file__))
rendered = view.render(
template=dir_path + '/youtube_template.txt',
image_name=image_name,
yout... |
a=int(input())
b=input().split()
c=[]
s=''
for i in range(a):
if i%2==0 and int(b[i])%2==1:
c.append(b[i])
if i%2==1 and int(b[i])%2==0:
c.append(b[i])
for i in range(len(c)-1):
s+=c[i]+" "
print(s+c[-1])
|
"""
Module that runs the Flask app in either development or production
mode, after setting up environment variables appropriately.
"""
import argparse
import os
import shlex
import subprocess
import sys
import hyperschedule.util as util
def exec_cmd(cmd):
print(" ".join(map(shlex.quote, cmd)))
try:
... |
class Dog():
def __init__(self, type, name, color):
print(self, "class")
self.name = name
self.type = type
self.color = color
dog1 = Dog("Alabai", "Sharik", "brown")
print(dog1, "code")
dog2 = Dog("Alabai", "Simba", "black")
print(dog2, "simba") |
# -*- coding: utf-8 -*-
# @Date : 2018-02-28 11:19:48
# @Author : jym
# @Description:
# @Version : v0.0
import datetime
import functools
import itertools
import time
import tornado
from tornado import gen
from tornado import web
from math import *
def distance(lat1,lng1,lat2,lng2):
#计算两点之间的距离(km)
radlat1=ra... |
from typing import TYPE_CHECKING
from django import forms
from budget.models import Pattern
if TYPE_CHECKING:
from budget.models import Category
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
class CategoryClassChoiceField(forms.ModelChoiceField):
... |
import argparse
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--cuda", default=1, type=int, help="Which GPU to train.")
parser.add_argument("--batch_size", default=8, type=int, help="Batch size to use during training.")
parser.add_argument("--size", default=512, type=int, hel... |
import discord
import os
from discord.ext import tasks
from discord.ext import commands
class checkmsg(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print("Checkmsg.py Cog has loaded Succesfully")
... |
import sys, collections
from numpy import *
from matplotlib import pyplot as plt
fn="../data/data_provinces.csv"
# loading file with 3 columns
name=loadtxt(fn, unpack=True, delimiter=',', skiprows=1, dtype='a', usecols=arange(1))
# array defined for the first column
region=loadtxt(fn, unpack=True, delimiter=',', skipr... |
########################
# the default config should work out of the box with minimal change
# Under the '## User specific parameter' line need to be changed to make the config correctly
########################
from WMCore.Configuration import Configuration
from os import environ, path
import WMCore.WMInit
config = ... |
print ("questao 1")
a = float(input("Digite a altura:CM"))
b = float(input("Digite o peso "))
imc = b/a**2
print ("seu imc é:",imc)
if imc <= 18.5:
print ("abaixo do peso")
elif imc >25:
print ("acima do peso ")
else :
print ("peso ideal")
|
# Generated by Django 2.1.5 on 2019-03-15 18:31
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userprogress', '0011_userattemptedchallenge'),
]
operations = [
migrations.AddField(
model_name='userattemptedch... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class TDNN(nn.Module):
def __init__(
self,
input_dim=23,
output_dim=512,
context_size=5,
stride=1,
dilation=1,
... |
import os
import maya.cmds as cmds
import maya.mel as mel
import pb.general.assets as assets
def create_export_skeleton():
rigs = cmds.ls("*:RIG")
character_rig = None
weapon_rig = None
for rig in rigs:
if rig.startswith('ch'):
character_rig = rig
elif rig.startswith('wp... |
cpf = input("CPF(xxx.xxx.xxx-xx) :")
while (cpf[3] !=".") or (cpf[7] !=".") or (cpf[11] !="-"):
cpf = input("O formato deve ser: (xxx.xxx.xxx-xx) :")
else: print("O formato está correto")
|
class CredentialSet:
def __init__(self):
self.Password = "default"
self.UserName = "default" |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: cg
# time : 2017-12-04
import pymysql.cursors
class DoMysql:
# 连接数据库,返回一条连接
def __init__(self, dictMsgForMysql):
# 构造函数
self.strHost = dictMsgForMysql.get('host')
self.strPort = dictMsgForMysql.get('por... |
import random
from onegov.core.collection import Pagination
from onegov.ticket import handlers as global_handlers
from onegov.ticket.model import Ticket
from sqlalchemy import desc, distinct, func
from sqlalchemy.orm import joinedload, undefer
from uuid import UUID
from typing import Any, Literal, NamedTuple, TYPE_C... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.load_dashboard, name='home-page'),
path('predictor/', views.PredictorView.as_view(), name='predictor'),
]
|
def preorder(self, root: 'Node') -> List[int]:
res = []
# def recursion(root):
# if not root:
# return
# res.append(root.val)
# for child in root.children:
# recursion(child)
# recursion(root)
# return res
"""
迭代法:参考二叉树前序遍历的迭代法
O(N), O(N)
... |
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2005-2006 CamptoCamp
# Copyright (c) 2006-2010 OpenERP S.A
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all po... |
print("program to reverse the given words")
message=input("enter the string")
list=[]
list=message.split(" ")
print(len(list))
for i in range(len(list)-1,-1,-1):
print(list[i],end=" ")
|
#!/usr/bin/python3
import time
from threading import Thread
NUMBER_OF_THREADS = 1
def process_line(in_line):
#swapcase
out_line = in_line.swapcase()
#process numbers
for i in range(0, len(out_line)):
if out_line[i].isdigit():
d = int(out_line[i])
if d<9:
... |
import pandas as pd
import random
## The missing linkes should be extracted from the previous snapshot of the
## network which you want to predict links for. (if you want to have a negative
## dataset for your predictions)
## for example if you want to have a list of links which were not present
## in 2016 and also is... |
from handControl.axis import Axis
from handControl.communication.serial_connection import SerialConnection
import time
class Hand(object):
def __init__(self, port):
self._axis = []
for i in range(0, 4):
self._axis.append(Axis())
self._axis[i].set_angle(90)
self._se... |
from selenium import webdriver
import time
import os
driver = webdriver.Chrome()
file_path = 'file:///'+os.path.abspath("C:/课件/我的课件/测试/selenium2/locateElement/selenium2html/send.html")
driver.get(file_path)
time.sleep(3)
driver.maximize_window()
driver.find_element_by_xpath("//html//body//input").click()
time.sleep(3)
... |
import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = 'BigRig',
version = '0.1-pre',
license = 'BSD',
description = 'A pure Python ECMAScript 5.1 engine.',
long_description = read('README.rst'),
... |
import sympy as sp
import numpy as np
from kaa.bundle import Bundle, BundleTransformer
from kaa.model import Model
def test_bund_trans_1():
x,y = sp.Symbol('x'), sp.Symbol('y')
dx = x + 1
dy = y + 1
dyns =[dx, dy]
vars = [x, y]
L = np.empty([2,2])
T = np.empty(2)
L[0] = [1, 0]
L... |
from .data_processor import DataProcessor
from torch import nn
class SourceTargetDataProcessor(nn.Module):
"""
Abstract class used for preprocessing and embedding
It basically contains two DataProcessors (one for the source and one for the target)
Preprocessing: from ? -> (source, target, metadata... |
class Objeto:
def __init__(self):
self.x=0
self.y=0
self.orientation=0
class Frame:
def __init__(self):
self.robots_blue = [Objeto(), Objeto(), Objeto()]
self.robots_yellow = [Objeto(), Objeto(), Objeto()]
self.ball=Objeto() |
import os
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import itertools
import statsmodels.api as sm
import streamlit as st
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
from pylab impor... |
from tile import Tile
class Item(Tile):
"""Contains all the items functions"""
itemscollected = 0
def __init__(self, img, text):
Tile.__init__(self, img, text)
self.collected = False
self.invx = -100
self.invy = -100
def set_inventory_pos(self, x, y):
"""Set t... |
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
def index(request):
return render_to_response('index.html', {})
def index500(request):
return render_to_response('500.html', {})
def trac(request):
return HttpResponseRedirect('http://ericol... |
import click
from utilities import decorators
from contacts.controller import ContactsController
@click.group()
def cli():
""" Manage my directory """
pass
@cli.command(name="list", help="Show my contact list")
@decorators.title
def list_contacts():
""" Show my contact list """
contact_list = Contac... |
def get_triangles(n):
return [i*(i+1)/2 for i in range(n+1)]
def value(word):
return sum([ord(c)-ord('A')+1 for c in word])
if __name__ == "__main__":
f = open("../../problem_inputs/p042_words.txt", "r")
triangles = get_triangles(50)
names = f.readline().split(",")
names = [s[1:-1] for s in na... |
import alyssa
import valentina
import peppermint
import json
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/PATE-01/', methods = ['POST'])
def postJsonHandler():
if request.is_json:
peppermint.ascii_art()
content = request.get_json()
#print(conte... |
#
#
# Server side image processing
# Adding PCA dimensionality reduction
#
from __future__ import print_function
from time import time
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.svm import SVC
from sklearn.externals import joblib
from sklearn.deco... |
# -*- coding: utf-8 -*-
import os
from StringIO import StringIO
import pycurl
from . import ForeignDataWrapper
from .utils import log_to_postgres
from logging import WARNING
import csv
import chardet
import os
class WebCsvFdw(ForeignDataWrapper):
def __init__(self, fdw_options, fdw_columns):
super(WebCsvFd... |
# Databricks notebook source
# MAGIC %md # Introduction to Deep Learning Frameworks
# MAGIC
# MAGIC In this notebook, we're going to experiment with image classification using a variant of logistic regression.
# MAGIC
# MAGIC We're not going to do any deep learning quite yet; we're going to use this as an opportunity... |
#!/usr/bin/env python3
from subprocess import Popen, PIPE
import os
import sys
import urllib.parse
import urllib.request
params = {
"count_active": "on",
"count_enabled": "on",
}
query = urllib.parse.urlencode(params)
url = "https://myosg.grid.iu.edu/miscproject/xml?count_sg_1&%s" % query
with urllib.requ... |
import numpy as np
import matplotlib.pyplot as plt
pentadecathlon = np.zeros( ( 24,24 ) )
pentadecathlon[ 10:20,10 ] = 1
pentadecathlon[ 12, 9 ] = 1
pentadecathlon[ 12,10 ] = 0
pentadecathlon[ 12,11 ] = 1
pentadecathlon[ 17, 9 ] = 1
pentadecathlon[ 17,10 ] = 0
pentadecathlon[ 17,11 ] = 1
pd_list = [pentadecathlon]
nt... |
from django.conf import settings
from osgeo import gdal,osr
from osgeo.gdalnumeric import *
from osgeo.gdalconst import *
import numpy as np
import os
import sys
def to_rgb(bandarray):
print(bandarray)
maxvalue = np.amax(bandarray)
#minvalue = np.amin(bandarray)
#print("from RGB",maxvalue,minvalue, ban... |
#!/usr/bin/python
#\file head2.py
#\brief Baxter: head control 2
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Oct.09, 2015
import roslib
import rospy
import actionlib
import control_msgs.msg
import baxter_interface
import time, math, sys
if __name__=='__main__':
rospy.init_node('baxte... |
from ED6ScenarioHelper import *
def main():
# 蔡斯
CreateScenaFile(
FileName = 'T3222 ._SN',
MapName = 'Zeiss',
Location = 'T3222.x',
MapIndex = 1,
MapDefaultBGM = "ed60084",
Flags = 0,
En... |
import requests
import logging
import re
from bs4 import BeautifulSoup
import hashlib
import sqlite3
import os
from unfurl.util import timeit
LOG = logging.getLogger(__name__)
def get_page(url):
LOG.debug('fetching page: %s' % url)
try:
page = requests.get(url)
except requests.exceptions.MissingSc... |
from Data import Data
def main():
data = Data()
data.createVectors()
data.createClassifier()
data.printResults()
data.kmeansClustering()
if __name__ == "__main__":
main() |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 17 19:40:26 2018
@author: cmdrlias
"""
class Cliente:
def __init__(self, nm_cliente, id_telegram):
self.nm_cliente = nm_cliente
self.id_telegram = id_telegram
self.lista_compra_produto = []
def getNm_cl... |
# -*- 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 GaowenboItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
from scrapy.item import Item, Fi... |
import math
import torch
import numpy
from scipy.optimize import fsolve
inf = [[-368461.739, 26534822.568, -517664.322, 21966984.2427, -0.000104647296],
[10002180.758, 12040222.131, 21796269.831, 23447022.1136, -0.000308443058],
[-7036480.928, 22592611.906, 11809485.040, 20154521.4618, -0.000038172460]]
... |
if __name__ == "__main__":
import AssetReader
docx_reader = AssetReader.DocXReader()
print docx_reader.find_images("GestaltBoxDemo.docx")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.