text
stringlengths
38
1.54M
# -*- coding: utf-8 -*- from pyspark import SparkContext,SparkConf from pyspark.sql import SQLContext from pyspark.sql.types import * import json if __name__ == "__main__": # if len(sys.argv) > 2: # host = sys.argv[1] # hbase_table_read = sys.argv[2] # hbase_table_save = sys.argv[3] #...
# package com.gwittit.client.test import java from java import * from junit.framework.Assert import Assert from com.google.gwt.core.client.JavaScriptObject import JavaScriptObject from com.google.gwt.junit.client.GWTTestCase import GWTTestCase from gwittit.client.facebook.entities import ApplicationPublicInfo class ...
from setuptools import setup def readme(): with open('README.rst') as f: return f.read() setup(name='hcpdlstat', version='0.1', description='Tools for HCP XNAT/Aspera download analytics', long_description=readme(), url='http://github.com/karchie/hcpdlstat', author='Kevin A. A...
import string import numpy as np import math import pandas as pd from sklearn.linear_model import LinearRegression, ElasticNet from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split, RandomizedSearchCV, GridSearchCV from scipy.stats import pearsonr from scipy.stats impor...
from instabot import Bot import os import sys sys.path.append(os.path.join(sys.path[0], "../../")) def getUsersFollowers(bot, userId): try: followersByUsers = bot.get_user_followers(userId, nfollows=10000) return followersByUsers except: return False def getUserFollowing(bot, userId...
import objects from structures import Variable from llvm import * from llvm.core import * import subprocess import tempfile import cffi import ctypes ty_char = Type.int(8) ty_int = Type.int() ty_void = Type.void() ty_long = Type.int(64) cell_types = { ctypes.c_ulong: Type.int(64), ctypes.c_long: ty_long, ...
import requests import smtplib, ssl import string from bs4 import BeautifulSoup import webbrowser from twilio.rest import Client import getpass account_sid = "ACcf4157aa5ff6399764b81d6044fdfb65" auth_token = "b4df4f4963402380dc5d1dc4678fdde5" client = Client(account_sid, auth_token) uppers = string.ascii_uppercase ha...
# Generated by Django 3.0.6 on 2020-05-28 12:36 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('blog', '0007_auto_20200528_1833'), ] operations = [ migrations.RemoveField( model_name='post', name='image', ), ...
# ############################################################ # # Filename: # # Description: # # Version: 1.0 # Python Version: 3.x # # Author: Paul Robin , paul.robin@etu.unistra.fr # Amarin Hutt, amarinhutt@hotmail.fr # ###############################################...
import tia.trad.tools.ipc.naming_conventions as names import tia.trad.tools.arithm.floatArithm as fl import tia.trad.market.orders as orders; reload(orders) from tia.trad.tools.dicDiff import DictDiff import tia.trad.market.events as event; reload(event) import logging import tia.trad.tools.ipc.processLogger as pl LOGG...
#!/usr/bin/env python import mapper import backtrack b = backtrack.Backtrack("doid", "filter.tsv") m = mapper.Mapper(b, "doid", "omim", 120.3) pages = set() type_page_text = {} type_page_text["title"] = {} type_page_text["text"] = {} for line in open("omim_corpus.tsv"): page, block, text = line[:-1].split("\t") ...
import pygame import sys from classes.bullet import Bullet from classes.alien import Alien from time import sleep #飞船开火 def fire_bullet(bullets,setting,screen,ship): # 创建新子弹,限制最大子弹数 if len(bullets) < setting.bullet_allow: new_bullet = Bullet(setting, screen, ship) bullets.add(new_bul...
import pint from utils.unitUtilities import Unit ur = pint.UnitRegistry() Q_ = ur.Quantity length = ['millimeter', 'centimeter', 'foot', 'parsec', 'meter', 'light_year', 'astronomical_unit'] velocity = ['meter/second', 'speed_of_light', ...
#!/usr/bin/env python # coding: utf-8 # In[44]: import pandas as pd from pathlib import Path #display charts inline #get_ipython().run_line_magic('matplotlib', 'inline') #path to file file_to_open = "survey_results_public.csv" df = pd.read_csv(file_to_open) #find the number of answers and columns in our data s...
''' 문제분석 : 문자열 길이, isnumeric ''' ''' pseudo code def solution(s): len() if len 4 or 6 if isnum return True else ret False ret False ''' def solution(s): length = len(s) if length == 4 or length == 6: if s.isnumeric(): return True else: ...
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import print_function from __future__ import division from __future__ import absolute_import import unittest from dashboard.api import util...
import random from typing import List import numpy as np import matplotlib.pyplot as plt from ch6.toolbox import ( crossover_blend, mutation_random_deviation, selection_tournament, crossover_operation, mutation_operation, ) def func(x): return np.sin(x) - .2 * abs(x) class Individual: counter = 0 ...
#!/usr/bin/python3 import pandas as pd b= pd.read_csv('b.csv', sep=',',dtype={'id':str}) # print('shape:',b.shape) #行访问 print('show a row:\n',b.iloc[0],'\nshow row end\n*************\n' ) #减一行 print('befor drop row2 \n',b,'\n**********\n') b=b.drop(2) #b=b.drop(3) print('after drop row2 \n',b,'\n**********\n') #...
#!/usr/bin/python # -*- coding: utf-8 -*- import urllib import json import os import requests import datetime #import twilio.twiml from flask import Flask from flask import jsonify from flask import url_for from flask import request from flask import make_response from flask_ask import Ask, request, session, question, ...
# Generated by Django 3.1.8 on 2021-04-27 22:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("zerver", "0320_realm_move_messages_between_streams_policy"), ] operations = [ migrations.AddField( model_name="userprofile", ...
# -*- coding: utf-8 -*- """ This module provides HUD specializations of viewport nodes. """ from kousen.scenegraph import ViewportNode from kousen.scenegraph.quadric import QuadricGnomonNode class CameraHUDNode(ViewportNode): """ The Camera HUD Node provides a Camera Data HUD implementation of a AbstractSceneG...
#......................... Sending information using GET method # Import modules for CGI handling import cgi, cgitb # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fields first_name = form.getvalue('first_name') last_name = form.getvalue('last_name') print "Content-type:text/html\r\...
#! /bin/python3 from rb_tree import RbTree def case_a(): tree = RbTree() tree.insert(2, 'M') tree.insert(1, 'S') tree.insert(3, 'L') tree.root.add_dummy_leaves('a') tree.dot('case_a.dot', 'case_a') case_a()
from report.models.common import * from report.models.canada import * from report.models.us import *
1.pickle.dump以二进制保存文件 2.pickle.load以二进制打开文件 3.sorted(self.items(),key=_itemgetter(1),reverse=True) 对self.item()的元素的第1项降序排列 4.<< (位运算符号) x=4 <<1 x=8 是将x的二进制表示左移一位,相当于原数x乘2 5.list1 = ['Google', 'Runoob', 'Taobao'] list_pop=list1.pop(1) print("删除的项为 :", list_pop) ----'Runoob', list.pop(obj) 参数 obj -- 可选...
import speech_recognition as sr from os import system as cmd import time import sys upperAlphabet="ABCDEFGHIJKLMNOPRSTUVWXYZ" lowerAlphabet="abcdefghijklmnoprstuvwxyz" def GetLower(text:str): #To be sure if given text has lowercases newText=str() for i in text: if i in upperAlphabet: index...
import network import utime class WiFi: def __init__(self): self.ap_ip_addr = None self.sta_ip_addr = None self.ap = network.WLAN(network.AP_IF) # Start AP mode self.sta = network.WLAN(network.STA_IF) # Start STA mode utime.sleep_ms(200) self.sta.active(True) ...
import os # pip install tweepy import tweepy # 환경변수에서 인증 정보를 추출합니다. CONSUMER_KEY = os.environ['CONSUMER_KEY'] CONSUMER_SECRET = os.environ['CONSUMER_SECRET'] ACCESS_TOKEN = os.environ['ACCESS_TOKEN'] ACCESS_TOKEN_SECRET = os.environ['ACCESS_TOKEN_SECRET'] # 인증 정보를 설정합니다. auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSU...
#Réponse à l'exercice 2.2 # Programme testant si une année, saisie par l'utilisateur, # est bissextile ou non annee = input("Entrer une année : ") # On attend que l'utilisateur saisisse l'année qu'il désire tester annee = int(annee) # Risque d'erreur si l'utilisateur n'a pas saisi un nombre bissextile = False # On cr...
import re def translate_fno_to_sql(functions): sql = "" for tm in functions: #if 'query' in functions[tm] for func in functions[tm]: parameters = func["params"] # print('**********************************') # print(str(parameters).replace("'", '"')) ...
#!/usr/bin/env python # IMPORT import sys AVAILABLE_TASKS = [ 'system', 'dev', 'gnome', 'internet' ] # List task def list_tasks(): print ''' - system : task to configure the system (ntp, shell, ...) on the host. - dev : task to install development software (python, nodejs, ...) on the hos...
import numpy as np from scipy.interpolate import RectBivariateSpline def InverseCompositionAffine(It, It1, threshold, num_iters): """ :param It: template image :param It1: Current image :param threshold: if the length of dp is smaller than the threshold, terminate the optimization :param num_iters...
from github_poster.utils import interpolate_color, make_key_times, parse_years def test_interpolate_color(): assert interpolate_color("#000000", "#ffffff", 0) == "#000000" assert interpolate_color("#000000", "#ffffff", 1) == "#ffffff" assert interpolate_color("#000000", "#ffffff", 0.5) == "#7f7f7f" as...
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-09-22 17:10 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('cms', '0020_old_tree_cleanup'), ('custom_plugins',...
from collections import deque H, W = map(int, input().split()) S = [input() for i in range(H)] C = sum(s.count('.') for s in S) dd = ((-1, 0), (0, -1), (1, 0), (0, 1)) que = deque([(0, 0, 0)]) used = {(0, 0)} res = None while que: s, t, cost = que.popleft() if s == H-1 and t == W-1: res = cost ...
import os import history.server_util app = history.server_util.create_app() def start(): os.system("gunicorn --bind 0.0.0.0:15055 server:app")
from django.shortcuts import render from rest_framework import viewsets from books.models import * from api.serializers import * class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer
from kwwidgets import vtkKWCheckButton from kwwidgets import vtkKWCheckButtonWithLabel from kwwidgets import vtkKWCheckButtonSet from kwwidgets import vtkKWApplication from kwwidgets import vtkKWWindow from kwwidgets import vtkKWIcon def vtkKWCheckButtonEntryPoint(parent, win): app = parent.GetApplication() ...
#!/usr/bin/env python import os import sys import web PWD = os.path.dirname(os.path.realpath(__file__)) parent_path = os.path.dirname(PWD) if parent_path not in sys.path: sys.path.insert(0, parent_path) from zbox_wiki import default_conf as conf def req_path_to_full_path(req_path, pages_path = conf.pages_p...
# -*- coding: utf-8 -*- from odoo import models, fields, api import logging class ProjectExt(models.Model): _inherit = 'sale.order' def data_for_order_report_bl(self): data = [] ids_category = [] for i in self.order_line: if i.product_id.categ_id not in ids_category: ...
import json import logging import os import pickle from collections import defaultdict import offsetbasedgraph import stream from pyvg import vg_pb2 class IntervalNotInGraphException(Exception): pass class Position(object): def __init__(self, node_id, offset, is_reverse=False): self.node_id = node_id...
from typing import Any, Dict, Optional, Union from ..types import InlineKeyboardMarkup, Message from .base import Request, TelegramMethod class EditMessageReplyMarkup(TelegramMethod[Union[Message, bool]]): """ Use this method to edit only the reply markup of messages. On success, if edited message is sen...
import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("summary", "0004_datapivotquery_export_format"), ] operations = [ migrations.AddField( model_name="datapivotquery", name="pref...
import os from flask_script import Manager from app import create_app, db from commands.seed_command import SeedCommand env = os.getenv("FLASK_ENV") or "test" print(f"Active environment: * {env} *") app = create_app(env) manager = Manager(app) app.app_context().push() manager.add_command("seed_db", SeedCommand) @m...
class Solution { public static boolean checkForPalindrome(String s, int index){ /*int n = s.length(); for(int i = 0; i < n; i++){ char c = s.charAt(i); char d = s.charAt(n-i-1); if(c != d) return false; } return true;*/ ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ######################################################################## # # Copyright (c) 2021 tencent.com, Inc. All Rights Reserved # ######################################################################## import torch from torch import nn #def contraction_block(in, ...
"""Show how to write a custom OpenGL view. This is for advanced users only.""" import numpy as np from phy.utils.color import selected_cluster_color from phy import IPlugin from phy.cluster.views import ManualClusteringView from phy.plot.visuals import PlotVisual class MyOpenGLView(ManualClusteringView): """Al...
from math import fmod from rlib.float import float_to_str from som.vm.globals import trueObject, falseObject from som.vmobjects.abstract_object import AbstractObject class Double(AbstractObject): _immutable_fields_ = ["_embedded_double"] def __init__(self, value): AbstractObject.__init__(self) ...
# coding: utf-8 import os import abc history = [] class Command(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def execute(self): pass @abc.abstractmethod def undo(self): pass class LSCommand(Command): def __init__(self, receiver): self.receiver = receiv...
# # Copyright 2013 Infinidat Ltd. All rights reserved. # Use is subject to license terms. # import sys import zerorpc import zmq import gevent from zerorpc.channel import BufferedChannel from .. import base from .. import errors LOCALHOST = "127.0.0.1" CLIENT_TIMEOUT_IN_SECONDS = 10.0 class _ZeroRPCClient(zerorpc....
import tensorflow as tf from tensorflow.contrib.layers import conv2d from tensorflow.contrib.layers import max_pool2d from tensorflow.contrib.layers import avg_pool2d from tensorflow.contrib.layers import flatten from tensorflow.contrib.layers import fully_connected def create_model(): input = tf.placeholder(tf.fl...
# Thanks to ankthon from geeks for geeks for this module # Python program to validate an Email # import re module # re module provides support # for regular expressions import re # Make a regular expression # for validating an Email regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' # for custom mails...
#!/usr/bin/env python """ Reads chip file, chunk size Returns file with chromosome chunk_start chunk_end """ import argparse,sys,time,random parser = argparse.ArgumentParser() parser.add_argument("--subset_map", default="${subset_map}", help="") parser.add_argument("--out_chip", default="${out_chip}", help="") args =...
import scrapy from spiders.items import SpidersItem from scrapy.selector import Selector class MoviesSpider(scrapy.Spider): name = 'movies' allowed_domains = ['maoyan.com'] start_urls = ['https://maoyan.com/films?showType=3'] def parse(self, response): # movie_list = response.xpath('//div[@cl...
# Python的内建模块itertools提供了非常有用的用于操作迭代对象的函数。 # itertools模块提供的全部是处理迭代功能的函数,它们的返回值不是list,而是Iterator,只有用for循环迭代的时候才真正计算。 import itertools if __name__ == '__main__': # count()会创建一个无限的迭代器 nature = itertools.count(1) # 自然数迭代 for i in nature: print(i) if i >= 10000: break # cycle()会...
# -*- coding: utf-8 -*- """ Created on Wed Jul 15 20:48:16 2020 @author: shivj """ import numpy as np import pandas as pd import streamlit as st import matplotlib.pyplot as plt import base64 import seaborn as sns from PIL import Image image=Image.open(r"numpy_altered.jpg") st.image(image, format="JPEG", use_column_...
# -*- coding: utf-8 -*- # author = minjie from django.urls import path, re_path from .views import OrgListView, UserAskView, OrgHomeView, OrgCourseView, OrgDescView, OrgTeacherView, AddFavView from .views import TeacherListView, TeacherDetailView urlpatterns = [ # 课程机构列表页 path('list', OrgListView.as_view(), n...
#!/usr/bin/env python # -*- coding: UTF-8 -*- import re import json from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.http import Request,FormRequest from tracker.items import * class Spider(C...
# # # from django.db import models # # # # # # class File(models.Model): # # # file = models.FileField(blank=False, null=False) # # # remark = models.CharField(max_length=20) # # # timestamp = models.DateTimeField(auto_now_add=True) # # # # from django.db import models # # from probably.users.models import ...
# for i in range(1, 100, 2): # print(i) # arr = [3, 6, 1, 0] # sortedArr = sorted(arr) # print(sortedArr) # # reversedArr = reversed(arr) # # print(reversedArr) # for item in reversed(arr): # print(item) def calc(a, b, c, d): return a/b+d*c param = [1, 2, 3, 4, 4] print(calc(2, 3, 4, 5)) print(c...
def reflect__(Demo,White,Black): ref=[] for i in range(len(Demo)): if(abs(White[i]-Black[i]))>10: each_ref=float((Demo[i]-Black[i]))/(White[i]-Black[i]) round(each_ref,2) ref.append(each_ref) else: each_ref=0 ref.append(each_ref) r...
# WPCC # basicEx5.py # Let's look at how to generate random numbers in Python # We will have to import a Python library for this functionality import random # This will import the "random" library so we can use it's functions # in this file. Whenever we use functions that has been defined in # the random library, we...
import fnmatch import os def walk_on_py_files(folder): """ Walk through each python files in a directory """ for dir_path, _, files in os.walk(folder): for filename in fnmatch.filter(files, '*.py'): yield os.path.abspath(os.path.join(dir_path, filename))
# -*- coding: utf-8 -*- import json import time # import random import uuid import requests import datetime import os from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.desired_capabiliti...
from pyspark import SparkConf, SparkContext #sc = SparkContext('local') from flask import Flask, request app = Flask(__name__) #sc = SparkContext('local') APP_NAME = " Querying PCMD files" #filename = "hdfs://ec2-52-207-247-64.compute-1.amazonaws.com:9000/user/15061021.PCMD" filename = "file:///tmp/mme1/2015-07-07.14...
from metar import Metar import iemdb IEM = iemdb.connect("iem", bypass=True) icursor = IEM.cursor() icursor2 = IEM.cursor() icursor.execute(""" select valid, c.iemid, raw from current_log c JOIN stations s on (s.iemid = c.iemid) and s.network ~* 'ASOS' """) total = 0 for row in icursor: try: mtr = M...
import pandas as pd import numpy as np import matplotlib.pyplot as plt data = pd.read_csv("./pokemon.csv") print(data) print("#" * 80) namedView = data.set_index("Name") print(namedView[["HP", "Attack", "Defense"]]) #print(namedView[["HP", "Attack", "Defense"]][namedView["HP"] > 100]) print("#" * 80) data["Offensive...
import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('city2.jpg',0) img = cv2.medianBlur(img,5) ret,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY) th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\ cv2.THRESH_BINARY,11,2) th3 = cv2.adaptiveThreshold(img,255...
import math import os import time import sys import warnings from urllib import quote import urllib2 with warnings.catch_warnings(): warnings.simplefilter("ignore") from scikits.audiolab import Sndfile, Format import contextlib import numpy as np from a2pyutils.logger import Logger import a2pyutils.storage from...
from django.shortcuts import render,HttpResponse,redirect # 导入ACME类 from cert.ACME_API import ACME_cll import json,os import time from django.http import FileResponse # Create your views here. from login.AuthLogin import check_login from cert.FreeSLL_API import TrustAsia from django.core.paginator import Pagin...
from ctypes import c_char_p, cdll hello_lib = cdll.LoadLibrary("hello.so") hello = hello_lib.hello print hello("world") # this won't work! # ==> need to set return type... hello.restype = c_char_p assert hello("world") == "hello, world"
#!/usr/bin/env python # Title: Turtlebot Navigation Stack # File: config.py # Date: 2017-02-13 # Author: Preben Jensen Hoel and Paul-Edouard Sarlin # Description: Configuration file containing static parameters used by several # modules for map building, path planning, or lo...
from flask import Flask, jsonify, request from products import products from app import app @app.route('/test') def test(): return jsonify({"mensaje": "Prueba de script"}) #Petición de general de productos @app.route('/products') def get_products(): return jsonify({"products": products, "message":"List of pro...
import gym import gym_cog_ml_tasks from LSTM.LSTM_model import Agent_LSTM from common.utils import train, test env = gym.make('Simple_Copy_Repeat-v0', n_char=5, size=3, repeat=3) N_tr = 1000 N_tst = 100 n_hidden = 100 lr = 0.01 agent = Agent_LSTM(env.observation_space.n, env.action_space.n, n_hidden, lr) train(env...
# package # 初始化包的文件 目前不使用 # 可以认为是一个文件夹,只不过该文件夹默认有一个__init__.py文件 # 解决问题:防止文件名称冲突 # 只要整个项目下包名不冲突,不同包的文件名是否一致就不重要了。 # 只要导入包,会立即执行该包下的__init__.py中的内容 # 引入包下的模块 # 格式:包名.模块名 import newPackage.module1 import new1.pyc # 使用包下的模块中的内容 # 格式:包名.模块名.变量名/函数名 newPackage.module1.run() # from 包名 import 模块 from newPackage import ...
#!/usr/bin/env python from bottle import Bottle, route, run, request, redirect import re HASH_RE = re.compile(".+xt=urn:btih:([^&]+).*") TOR_CACHE = "https://itorrents.org/torrent/{}.torrent" app = application = Bottle() HTMLBLOB = """ <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="tex...
# Orange ist Trainingsperformance in abhänigkeit von n_Neighbors (x) # Y-Achse ist Score # Dunkelblau ist Mittelwert von Crossvalidation # Hellblau ist Konifidenzintervall (Standardabweichung). Sagt aus wie Aussagekräftig ist Mittelwert ist (Je geringer Standardabweichung desto besser ist Mittelwertaussage) # Imports ...
import os import sys import argparse from setup_app.static import InstallTypes def get_setup_options(): parser_description='''Use setup.py to configure your Gluu Server and to add initial data required for oxAuth and oxTrust to start. If setup.properties is found in this folder, these properties will aut...
np=int(input()) a=np s=0 while(np!=0): temp=np%10 s=s+temp*temp*temp np=int(np/10) if(s==a): print("yes") else: print("no")
from flask import Blueprint, request, current_app from functools import wraps from tracker_api.user import User from .err_msgs import * auth_bp = Blueprint("auth", __name__) def json_data_required(f): """route decorator requiring json data in request body""" @wraps(f) def decorated_function(*args, **kwa...
# -*-coding:utf-8 -*- import itchat import sys defaultencoding = 'utf-8' if sys.getdefaultencoding() != defaultencoding: reload(sys) sys.setdefaultencoding(defaultencoding) def lc(): print("登陆成功!") def ec(): print("exit") itchat.auto_login(hotReload=True,loginCallback=lc, exitCallback=ec) friends = it...
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-04 15:26 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Crea...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (c) 2011 OpenERP S.A. <http://openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GN...
def quicksort(lista, inicio=0, fim=None): if fim is None: fim = len(lista) - 1 if inicio < fim: p = partition(lista,inicio,fim) quicksort(lista, inicio, p-1) quicksort(lista, p+1, fim) def partition(lista, inicio, fim): pivot = lista[fim] i = inicio for j in range (i...
import numpy as np from sisyphus.mdp import ModelFree from sisyphus.envs._base import GraphWorld from sisyphus.tests.common import test_world def test_model_free(): """Test model free temporal difference learning algorithm.""" np.random.seed(47404) ## Generate test gym. gym = GraphWorld(*test_world())...
# -*- coding: utf-8 -*- from django.shortcuts import render_to_response, redirect from django.core.context_processors import csrf from django.contrib import auth from forms import * from django.contrib import messages import datetime from django.contrib.auth.forms import UserCreationForm from django.template.response i...
import os import cv2 import argparse ''' Model files can be downloaded from the Tensorflow Object Detection Model Zoo https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md Once you download the model, extract the files and run the tf_text_graph_ssd.py file with input...
class WorkflowLister: "Get a listing of workflows from a source of workflow metadata." # Eventually, this data structure should come from some sort of online registry. For now, just define it in code. _workflows= { 'HelloWorld_1.0-SNAPSHOT': { 'full_name':'Workf...
import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm # r = np.random.randn(10000) r = 10*np.random.randn(10000) + 5 plt.hist(r, bins=100) plt.show()
import json from builtins import str as text from past.builtins import basestring from rest_framework import serializers class JsonField(serializers.Field): def to_representation(self, value): if isinstance(value, basestring): return json.loads(value) return value def to_internal...
from flask import Flask, render_template,request import numpy as np import re import base64 import os import tensorflow as tf from PIL import Image app = Flask(__name__) app.config['UPLOADED_PHOTOS_DEST'] = '/Upload' sess= tf.Session() saver= tf.train.import_meta_graph('Model/saved_model.meta') saver.restore(sess,tf...
# Generated by Django 2.2 on 2019-04-16 12:34 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Car', fields=[ ('id', models.AutoField(auto_c...
import Entities.treasure as treasure class TreasureBulletsList(object): """description of class""" def __init__(self, gameStateManager): self.gameStateManager = gameStateManager self.treasure_bullets_list = [] def fill_treasure_bullets_list(self): treasure_bullets = self.gameStateM...
t=int(input()) for I in range(t): flag=0 s1=input() s2=input() for i in range(len(s1)): if(s1[i]!=s2[i] and (s1[i]!='?' and s2[i]!='?')): flag=1 break if(flag==0): print('Yes') else: print('No')
### # # Created by Holden on 12/17/2015 # # SOLVED on 12/17/2015 # # Problem 4 - Largest Palindrome Product # ### def palindrome_product(digits): palindrome = 0 for i in range((10 ** (digits - 1)), (10 ** digits)): for j in range((10 ** (digits - 1)), (10 ** digits)): if str(i * j) == ...
#list print("LISTS: ") courses = ['history', 'math', 'physics', 'compsci'] #use[] courses2 = ['art', 'PE'] courses2.extend(courses) #add courses2 then courses print(courses) print(courses2) print() #empty space for item in courses: print(item) print() #empty space courses.sort() #abc order for item in courses: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: JohnnySG # @Date: 2017-04-15 14:55:45 # @Email: sg19910914@gmail.com # @Last Modified by: JohnnySG # @Last Modified time: 2017-04-22 23:43:09 # ---------------------------------------- import numpy as np import pandas as pd class ShearLag(object): """...
from mockito import * import os, sys def _rel2abspath(fname): appdir=os.path.abspath(os.path.dirname(sys.argv[0])) return os.path.join(appdir,fname) sys.path.insert(0,_rel2abspath("../codes")) from io import IO from irq import Irq import unittest class IOTest(unittest.TestCase): def setUp(self): ...
# worldgenlib.py # Cepheus Engine world generation data and rules library # v1.1, March 31st, 2018 # This is open source code, feel free to use it for any purpose. # Contact the author at golan2072@gmail.com. #import modules import random import string import stellagama def size_gen(): """ generates th...
""" 2nd order Runge-Kutta method We can semplify the procedure by deviding it into 3 steps K1 = hy'(x,y) K2 = hy'(x+h/2,y+1\2K1) y(x+h) = y(x) + K2 Let's solve the problem y' = xy Analytical solution = e^(x^2) At the end we will also compare is with the solution obtained using the Euler method. """ ...