text
stringlengths
8
6.05M
import consus c = consus.Client() t = c.begin_transaction() assert t.get('the table', 'the key') is None t.commit() t = c.begin_transaction() assert t.put('the table', 'the key', 'the value') t.commit() t = c.begin_transaction() assert t.get('the table', 'the key') == 'the value' t.commit()
class RecentState: '''Class that maintains a file for marking news posts as old''' def __init__(self, path): '''\ Returns a new RecentState instance the uses the given <path> path -> the path of the state file It will be read on deamand.''' self.path = path self.values = {} def ...
import pandas as pd filename = 'pima-indians-diabetes.data.csv' data = pd.read_csv(filename) output_counts = data.groupby("class").size() print(output_counts)
# coding: utf-8 __author__ = 'flyingpang' """Create at 2017.02.27""" import time import uuid import datetime import requests from polyv.conf import APP_ID, APP_SECRET, USER_ID, MAX_VIEWER from polyv.exceptions import RequestException, MissingParameterException from polyv.utils import make_sign # 创建直播频道 def create_cha...
import sys def usage(): print("Usage: python operations.py <number1> <number2>") print("Example:") print("\tpython operations.py 10 3") quit() if (len(sys.argv) < 3): usage() elif (len(sys.argv) > 3): print("InputError: too many arguments\n") usage() else: try: nb1 = int(sys.argv[1]) nb2 = int(sys.argv[2]...
import random import string from faker import Faker def get_random_low_string(ln: int = 16, with_digits: bool = False): if with_digits: return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(ln)) else: return ''.join(random.choice(string.ascii_lowercase) for _ in ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket def echo(sock): try: while True: data = sock.recv(1024) # 受信できるまでブロック if not data: break sock.sendall(data) # 送信できるまでブロック finally: sock.close() def serve(addr): sock = socket.so...
import pydicom import cv2 import os from tqdm import tqdm path = '/mnt/data/rsna-pneumonia-detection-challenge/stage_2_train_images/' out_path = '/mnt/data/rsna-pneumonia-detection-challenge/stage_2_train_images_jpg/' path_list = os.listdir(path) for pa in tqdm(path_list): ds = pydicom.read_file(path+pa) #读取.dc...
""" This will be the server code. """
import util def ac_dist(instance,kNN,k): acdist=0 for i in range(len(kNN)): acdist+=util.distance_euclidean(instance,kNN[i])*(k+1-i) acdist=(k*k+k)/acdist*2 return acdist def outlier_factors(instances,k): """Compute the factors for each instance in instances. Return: factors """ ...
# -*- coding: future_fstrings -*- # Copyright 2018 Brandon Shelley. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #...
from multiprocessing import Process,Queue import os,time,random def write(q): #写数据进程 print('写进程的PID: {0}'.format(os.getpid())) for value in ['两点水','三点水','四点水']: print('写进Queue 的值为: {0}'.format(value)) q.put(value) time.sleep(random.random()) def read(q): #读取数据进程 print('读进程的...
# 숫자 0 혹은 알파벳 b 여러 개가 알파벳 a 뒤에오는 문자열을 찾는 파이썬 프로그램을 만들어라 import re p = re.compile('(?=[.])0+') m = p.search("123.08.004.69") #m = p.sub("", "123.08.004.69") print(m)
from kaa.reach import ReachSet from kaa.flowpipe import FlowPipePlotter from models.basic.basic import Basic def test_phase_basic(): basic_mod = Basic() basic_reach = ReachSet(basic_mod) flowpipe = basic_reach.computeReachSet(100) FlowPipePlotter(flowpipe).plot2DPhase(0,1)
from org.apache.commons.io import IOUtils from java.nio.charset import StandardCharsets from org.apache.nifi.processor.io import OutputStreamCallback # Define a subclass of OutputStreamCallback for use in session.write() class PyOutputStreamCallback(OutputStreamCallback): def __init__(self): pass def proc...
from django.db import models # Create your models here. class Upload(models.Model): audio = models.FileField(upload_to='audio') video = models.FileField(upload_to='video') def __str__(self): return str(self.pk)
#!/usr/bin/env python # Contributed by Bryan Halfpap <Bryanhalf@gmail.com>, Copyright 2015 #TODO: Reduce the usage of globals import sys import argparse import threading import logging from time import sleep from killerbee import * def create_beacon(panid, coordinator, epanid): '''Raw creation of beacon packet...
# Generated by Django 3.1 on 2020-11-21 00:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('hello_world', '0002_auto_20201115_2120'), ] operations = [ migrations.CreateModel( name='Splendor...
import tensorflow as tf import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' const1 = tf.constant([[2, 2]]) const2 = tf.constant([[4], [4]]) # 矩阵乘法运算matrix mul tf.add() multiple = tf.matmul(const1, const2) print(multiple) sess = tf.Session() result = sess.run(multiple) print(result) if const1.graph is tf.get_defa...
# Find the latest inspection date for the most sanitary restaurants. Assume the highest number of points is the most sanitary. # Only businesses with 'restaurants' in the name should be considered in your analysis. # Output the corresponding facility name, inspection score, latest inspection date, previous inspection ...
import os import sys sys.path.append(os.getenv('cf')) from cartoforum_api.orm_classes import sess from flask import session, render_template, request, jsonify from flask_mail import Message from cartoforum_api.orm_classes import Users, PasswordReset import hashlib import datetime # @cfapp.route('/groupselect', metho...
''' Recursividade Quando uma função chama a si própria ''' def pot(base, exp): # caso base if exp == 0: return 1 return base * pot(base, exp-1) print(pot(2, 10))
from django.contrib import admin from django.contrib.auth.views import LoginView, LogoutView, PasswordChangeView from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from blog_django.views import HomeView urlpatterns = [ path('admin/', admin.site.urls...
# This file is only intended for development purposes from kubeflow.kubeflow.ci import base_runner base_runner.main( component_name="notebook_servers.notebook_server_jupyter_scipy_tests", workflow_name="nb-j-sp-tests")
#!/usr/bin/python import yaml #Print a dictionary with a nice format def PrintDict(d,indent=0): for k,v in d.items(): if type(v)==dict: print ' '*indent,'[',k,']=...' PrintDict(v,indent+1) else: print ' '*indent,'[',k,']=',v if indent==0: print '' #Insert a new dictionary to the base d...
#!/usr/bin/env python2.7 import os from sqlalchemy import * from sqlalchemy.pool import NullPool from flask import Flask, request, render_template, g, redirect, Response tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') app = Flask(__name__, template_folder=tmpl_dir) DATABASEURI = "po...
class paper: name = "" issn = "" searchWord = "" dataSet = "GoolgeScholar" searchConf = "" year = "" publication = "" country = [] typeOfPaper = 0 # 0 paper, 1 app, 2 paper + app, 3 review technology = "" reviewTech = "" comProtocol = "" cooperative = "" comp...
__author__ = 'Yauhen_Mirotsin'
# coding: utf-8 from setuptools import setup, find_packages setup( name='expr-eval-2', version='0.3a', description='Python safe expression eval (experimental)', long_description='Python safe expression eval (experimental)', classifiers=[ 'Development Status :: 3 - Alpha', 'Licens...
""" distutilazy.test ----------------- command classes to help run tests :license: MIT. For more details see LICENSE file or https://opensource.org/licenses/MIT """ from __future__ import absolute_import import os from os.path import abspath, basename, dirname import sys import fnmatch from importlib import import_m...
from random import randint n=randint(0,9) i=0 while(i<5): num=int(input("guess number")) if num == n: print(" correct",n) break else: print("Wrong ") print("Attempt remaining : ",4-i) i=i+1
""" Dynamixel Instructions http://support.robotis.com/en/product/dynamixel/communication/dxl_instruction.htm """ import packet def instructionPing( ser, id ): """ Ping instruction """ p = makePacket(id, 0x01, []) sendPacket(ser, p) p = receivePacket(ser, id) return def instructionWriteData( ser, id, params ):...
## TLS Motion Determination (TLSMD) ## Copyright 2002-2006 by TLSMD Development Group (see AUTHORS file) ## This code is part of the TLSMD distribution and governed by ## its license. Please see the LICENSE file that should have been ## included as part of this package. import sys console_output_enabled = True def s...
from Npc import Npc class Guarda(Npc): #Utilizando () podemos indicar que uma classe herdará de outra #O construtor deve passar os atributos da supeclasse def __init__(self, nome, time): forca = 100 municao = 20 #Agora precisamos do construtor da classe pai super().__in...
from flask import render_template, redirect, url_for from flask_login import login_required, current_user import threading from app import app, forms, user from app import db_lock, db, login_manager import os from flask import request import json @app.route('/') def index(): login_form = forms.LoginForm() regi...
#!/usr/bin/env python3 # Copyright (c) 2016, Robert Escriva, Cornell University # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copy...
# ================================================================================================== # Copyright 2011 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi...
import os import re import tempfile from django import forms from django.conf import settings from django.forms import ModelForm import happyforms import Image from easy_thumbnails import processors from statsd import statsd from tower import ugettext as _, ugettext_lazy as _lazy from phonebook.models import Invite ...
from django.urls import path from . import views urlpatterns = [ path('all/', views.AllStudent.as_view()), path('create/', views.AddStudent.as_view()), path('<int:id>/', views.SpecificStudent.as_view()), ]
import cv2 import numpy as np pic=cv2.imread('image.jpg') cols=pic.shape[1] rows=pic.shape[0] center=(cols/2,rows/2) angle=90 M= cv2.getRotationMatrix2D(center, angle, 1) rotate=cv2.warpAffine(pic, M, (cols, rows)) cv2.imshow('rotated', rotate) cv2.waitKey(0) cv2.destroyAllWindows()
# OpenWeatherMap API Key weather_api_key="6c7fb7b754ae7b8788818eddeb5836a4" g_key="AIzaSyC9KIH5yzDkZGPgqsqiCKuhl8nIkADdpNM"
__version__ = "0.2." import shutil import os import time startTime = time.time() # parameters input_directory = '<input_directory>' output_directory = '<input_directory>' text_file = '<text_file>' f = open(text_file,'r') dst_folder = "" instring = f.read() quad_list =str(instring).split("\n") for q in quad_list: ...
from Paragraphs.GridParagraph import GridParagraph from Paragraphs.TextParagraph import TextParagraph import pytest @pytest.allure.feature('Paragraphs') @pytest.allure.story('Grid paragraph') @pytest.mark.usefixtures('init_page') class TestGridParagraph: @pytest.allure.title('VDM-936 Grid paragraph - creation') ...
#!/usr/bin/python """Compare failed tests in CTS/VTS test_result.xml. Given two test_result.xml's (A and B), this script lists all failed tests in A, and shows result of the same test in B. """ import argparse import collections import csv import xml.etree.ElementTree as ET PASS = 'pass' FAIL = 'fail' NO_DATA = 'no...
from django.db import models # Create your models here. class Lesson(models.Model): name = models.CharField(max_length=100) time = models.DateTimeField(null=True, blank=True) image = models.ImageField(upload_to='images/')
# @Title: 平衡二叉树 (Balanced Binary Tree) # @Author: 2464512446@qq.com # @Date: 2020-10-11 18:37:56 # @Runtime: 44 ms # @Memory: 18.1 MB # 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 ...
def main(): encontrado = False cant_divisores = 0 contador = count(1) while cant_divisores <= 500: triangular = mf.triangular_nro(contador.next()) cant_divisores = len(mf.factores_de(triangular)) print triangular, cant_divisores if __name__ == '__main__': import mis_funciones as mf from itertools import c...
#!/usr/bin/env python # coding: utf-8 from bs4 import BeautifulSoup as bs from selenium import webdriver from selenium.webdriver.firefox.options import Options import json from time import sleep options = Options() options.headless = True myname = "*" mypass = "*" driver_path = "~/Downloads/geckodriver" login_page ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from rest_framework.serializers import ModelSerializer from .models import * from datetime import datetime,date,time class billgroupserializer(ModelSerializer): class Meta: model = BillGroup fields = '__all__' class billgenerateseria...
''' Eric Eckert eric95 ''' import sys from queue import PriorityQueue # DO NOT CHANGE THIS SECTION if sys.argv==[''] or len(sys.argv)<2: import EightPuzzleWithHeuristics as Problem heuristics = lambda s: Problem.HEURISTICS['h_manhattan'](s) else: import importlib Problem = importlib.import_module(s...
''' Check if Linked List is Palindrome or not Given the head of a Singly LinkedList, write a method to check if the LinkedList is a palindrome or not. Your algorithm should use constant space and the input LinkedList should be in the original form once the algorithm is finished. The algorithm should have O(N)O(N) ti...
__author__ = "Dohoon Lee" __copyright__ = "Copyright 2018, Dohoon Lee" __email__ = "dohlee.bioinfo@gmail.com" __license__ = "MIT" from snakemake.shell import shell # Extract log. log = snakemake.log_fmt_shell(stdout=False, stderr=True) def optionify_input(parameter, option): """Return optionified pa...
class BadExecutableError(Exception): def __init__(self, message = ''): print 'Error: ' + message class BadExtensionError(Exception): def __init__(self, message = ''): print 'Error: ' + message class LFSError(Exception): def __init__(self, message = ''): print 'Error: ' + message class ReleaseError(Exception...
import pytest import numpy as np # test the encode and decode funcs black = np.zeros((100, 100, 3)) sum_black = np.sum(black) white = np.ones((100, 100, 3))*255 sum_white = np.sum(white) @pytest.mark.parametrize("img, expected", [ (black, sum_black), (white, sum_white), ]) def test_encode_decode(img, expect...
#!/bin/python3 import math import os import random import re import sys # Complete the queensAttack function below. def queensAttack(n, k, rq, cq, obs): ans=0 for i in range(rq,n+1): if [i,cq] in obs: break ans+=1 for i in range(min(rq-n,cq-n)): if [rq+i+1,cq+i+1] ...
import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np def plot_graph(dataset_name='DEMOAPP/Data/CleanedData.csv'): df = pd.read_csv(dataset_name) #Category front graph plt.figure(figsize=(30, 10)) fig=sns.set_style({'axes.spines.top':False,'axes.spines.right': False...
import numpy as np from matplotlib import pyplot as plt from matplotlib import rc, rcParams import matplotlib.units as units import matplotlib.ticker as ticker #rc('text',usetex=True) #rc('font',**{'family':'serif','serif':['Woods-Saxon potential']}) #font = {'family' : 'serif', # 'color' : 'darkred', # ...
import pytest from src.app.domain import commands from src.app.service import messagebus from src.app.service.messagebus import NotEventOrCommandException from src.app.service.unit_of_work import FakeWarehouseUnitOfWork def test_create_new_warehouse(): uow = FakeWarehouseUnitOfWork() messagebus.handle(command...
from .list import ListCreateSchema from .task import TaskCreateSchema
#!/usr/bin/python import sys import builtins import myModule1.mySubModule1 class myModule1Meta( type ): def __getattr__( self, name ): return getattr( sys.modules[ 'myModule1' ], name ) class mySubModule1Meta( type ): def __getattr__( self, name ): return getattr( sys.modules[ 'my...
import morepath import re from onegov.core import utils from onegov.core.crypto import random_password from onegov.core.templates import render_template from onegov.onboarding import _ from onegov.onboarding.errors import AlreadyExistsError from onegov.onboarding.forms import FinishForm, TownForm from onegov.onboardin...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None """ 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 """ class Solution: def addT...
import json import email from django import forms from django.forms import widgets from django.contrib.postgres import forms as pg_forms from wapipelines.models import Pipeline, Step class HTTPHeaderField(forms.Field): def clean(self, data): if data and ':' not in data: raise forms.Validati...
""" @Author : Laura @File : __init__.py.py @Time : 2020/3/18 14:24 """
class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool foreach ele in s: dic adding for each ele in t: dic2 adding return if same """ def helper(string): dic = {} ...
''' Return the number (count) of vowels in the given string. We will consider a, e, i, o, and u as vowels for this Kata. The input string will only consist of lower case letters and/or spaces. ''' def getCount(inputStr): return sum(x in 'aeiou' for x in inputStr)
import click from mazel.workspace import Workspace def current_workspace() -> Workspace: """Throw exception if not currently in a workspace""" workspace = Workspace.find() if workspace is None: raise click.ClickException("Not in a workspace") return workspace
Users = {"Tony": "luke", "Abrar": "Dheeru", "SreeKanth": "Sirisha"} val1 = input("Enter User Name: ") val2 = input("Enter Password: ") class InvalidUser(Exception): def __init__(self, msg="Invalid User"): Exception.__init__(self, msg) try: for i in Users: if val1[val2] == i: rais...
""" distutilazy.clean ----------------- command classes to help clean temporary files :license: MIT. For more details see LICENSE file or https://opensource.org/licenses/MIT """ from __future__ import absolute_import import os from shutil import rmtree from distutils import log from distutils.core import Command fro...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 9 02:36:52 2019 @author: vishay """ # USAGE # python test_network.py --model santa_not_santa.model --image images/examples/santa_01.png # import the necessary packages from keras.preprocessing.image import img_to_array from keras.models import lo...
from .redis_cache import cache, cache_time # from .db import user_db
import requests import pandas as pd from datetime import datetime,timezone,timedelta import time import os def _get_js_datetime_now(milliseconds=1,microseconds=0,adjust=True): """ JSベースの現在時刻を取得 """ JST = timezone(timedelta(hours=+9),'JST') base = datetime(1970,1,1,0,0,0,0,JST) now = datetime.n...
import csv def read_data(path): read=csv.reader(open(path)) text='' for i,row in enumerate(read): if i>0: # print(row[1:]) text+=str(row[1]) text+=':' text+=str(row[2]) print(text) if __name__ == '__main__': path='F:\\2018年暑假科研\\CNN\\my...
from flask import Flask, render_template import random app = Flask(__name__) @app.route("/") def home(): return render_template("home.html") @app.route("/decisions") def about(): return render_template("decisions.html") @app.route("/decisions/") @app.route("/decisions/<l>") @app.route("/decisions/<l>/") @ap...
#Climbing the Leaderboard num_players = int(input()) player_scores = [int(x) for x in input().split(' ')] player_scores.sort(reverse = True) alice_level = int(input()) alice_scores = [int(x) for x in input().split(' ')] alice_scores.sort() leaderBoard = [] def assign_player_rank(playerScores): ...
from funcs_for_handlers import logging_decorator, cancel from setup_database import open_close_database from telegram.ext import ( ConversationHandler, MessageHandler, CommandHandler, Filters) # consts for conversation handlers STICKER, STICKER_SHORTCUT, PACK_ID = range(3) SET_PACK_NAME = 0 def get_add_to_db_ha...
from django.contrib import admin from .models import Job from daterange_filter.filter import DateRangeFilter from simple_history.admin import SimpleHistoryAdmin from core.actions.export_to_csv import export_to_csv class JobAdmin(SimpleHistoryAdmin): def get_queryset(self, request): """To return all jobs i...
class Solution: # @return a string def countAndSay(self, n): i = 0 string = '1' while i < n-1: strnew ='' count = 0 for j in range(len(string)): if j < len(string)-1 and string[j] == string[j+1]: j += 1 ...
import csv import json networkProtocols = {} with open("protocol-numbers-1.csv", "r") as f: reader = csv.reader(f, delimiter=";", ) for row in reader: if row[0] == "Decimal" or row[0] == "143-252" or row[1] == "": continue print row[0] n = int(row[0]) ...
#!/usr/bin/env python3 """ test for the Log module. """ import os import signal import time import unittest from base_test import PschedTestBase from pscheduler.log import Log class TestLog(PschedTestBase): """ Log tests. """ def test_log(self): """Logging tests""" # Not much to t...
#! /usr/local/bin/python2 # FIXME: This currently only works in python2 due to weird library issues with google. # For now, to hack around this, we're pushing those google imports into the method. If # the results are already pre-cached, which you force by import os.path import cloudpickle import pandas as pd from ...
from django.apps import AppConfig class FlowchartConfig(AppConfig): name = 'flowchart'
#!/usr/bin/python #-*- coding: utf-8 -*- """ This script converts the KSCGR name files and structure folder to VOC structure folder, i.e., convert the structure of folders to a single folder with increasingly sorted names for VOC annotation. KSCGR folders are in the format: KSCGR/ - data1/ - boild-egg/ - 0.jpg ...
#!/usr/bin/env python3 import os import sys from distutils.core import setup import setuptools from projector.version import __version__ if sys.version_info < (3, 3): print("THIS MODULE REQUIRES PYTHON 3.3+. YOU ARE CURRENTLY\ USING PYTHON {0}".format(sys.version)) sys.exit(1) def package_files(dire...
# -*- coding: utf-8 -*- class HtmlGenerator(object): """docstring for HtmlGenerator""" def __init__(self, localhtmlname): self._localhtmlname = localhtmlname def createHtmlFromList(self, movieListGenerator, description): html = '<div class="panel-group" id="accordion">' html += '...
mylist = [6,1,2,4,8] index_min = min(range(len(mylist)), key=mylist.__getitem__) print(index_min)
#!/usr/bin/env python # coding=UTF-8 import socket import json class Client(object): """ A JSON socket client used to communicate with a JSON socket server. All the data is serialized in JSON. How to use it: """ host = None port = None socket = None def __del__(self): se...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 28 12:20:45 2018 @author: opensource """ import glob import cv2 import time import os import paracept as pc while True: try: for (i,image_file) in enumerate(glob.iglob('/home/opensource/1970_01_06-1970_01_10/*.jpg')): # time....
import fitsio import numpy as np import numpy.random as npr from scipy import interpolate from scipy.optimize import minimize from funkyyak import grad, numpy_wrapper as np from redshift_utils import load_data_clean_split, project_to_bands from slicesample import slicesample import matplotlib.pyplot as plt import seabo...
import json import pymongo import tweepy import time import string from collections import Counter from nltk.tokenize import TweetTokenizer from nltk.corpus import stopwords import matplotlib.pyplot as plt from datetime import datetime import matplotlib.pyplot as plt import matplotlib.dates as mdates class CustomStrea...
# -*- coding: utf-8 -*- import pandas as pd data_file = input("Enter file path for csv data: ") print(data_file) test_data = pd.read_csv(data_file, index_col=0) def explore_algorithms(data: pd.DataFrame, supervised: bool = True, y: str = None, pred_type: str = 'class', ...
# normalizes data import pandas as pd import numpy as np file = "data/disk.csv" df = pd.read_csv(file) print(df.columns.values) df['0'] = df['0']/np.linalg.norm(df['0']) df['1'] = df['1']/np.linalg.norm(df['1']) df.to_csv(file.replace("_normal","").replace(".csv", "_normal.csv"), index=False)
"""Plot helper stuff.""" # pylint: disable=invalid-name import matplotlib.colors import matplotlib.pyplot as plt import numpy as np from numpy.random import RandomState from copy import deepcopy try: import lmb.plot CMAP = lmb.plot.CMAP except: CMAP = matplotlib.colors.ListedColormap(RandomState(0).rand(256...
print('Testando pela ultima vez')
#isnumeric a=u'this56' b=u'65156' c=u'51wef53' d=u'656.653' print a.isnumeric() print b.isnumeric() print c.isnumeric() print d.isnumeric()
import webbrowser #importing the webbrowser module to work with browser class Movies(): #defining the class def __init__(self, movie_title, movie_storyline, movie_poster_url, movie_trailer_url): #defining constructor function using __init__ self.title = movie_title #assign...
import torch import numpy as np def SGHMC(data, y, bayes_nn, eta=0.00002, L=5, alpha=0.01, V=1): current_ps = [] beta = 0.5 * V * eta parameters = [parameter for parameter in bayes_nn.parameters()] for parameter in parameters: p = torch.cuda.FloatTensor(parameter.data.size()).normal_() * np.sq...
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2018-12-23 16:33 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Item',...
# Read, clean, and validate!! # The first step of almost any data project is to read the data, check for errors and special cases, and prepare data for analysis. This is exactly what you'll do in this chapter, while working with a dataset obtained from the National Survey of Family Growth. # Exploring the NSFG data # ...
#!/usr/bin/python3 import os import os.path as path import subprocess from pyhocon import ConfigFactory import argparse RAW_DATA = [ "customer", "lineitem", "nation", "orders", "partsupp", "part", "region", "supplier"] #DST = {'hao-ml-1': ['lineitem', 'supplier'], # 'hoa-ml-7': ...