text
stringlengths
38
1.54M
# -*- coding: utf-8 -*- """ author SparkByExamples.com """ import pyspark from pyspark.sql import SparkSession from pyspark.sql.functions import split, col spark=SparkSession.builder.appName("sparkbyexamples").getOrCreate() data=data = [('James','','Smith','1991-04-01'), ('Michael','Rose','','2000-05-19'), ('Robe...
from bisect import bisect_right from logging import getLogger from typing import Any, Dict, List, Optional, Union from dgl import BatchedDGLGraph, unbatch from pytorch_lightning import data_loader, LightningModule from torch import stack as torch_stack, Tensor from torch.nn import LogSoftmax, Module, NLLLoss from torc...
from pathlib import Path import re import torchaudio def remove_non_alphanumeric(text): return re.sub(r'[\W_]+', '', text) def load_data(path_str: str): """ Yields waveform and text from a given transcription folder """ path = Path(path_str) with open(path / "metadata.csv") as f: li...
# Generated by Django 2.1 on 2018-09-30 13:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('election', '0003_candidate_election_id'), ] operations = [ migrations.AddField( model_name='election', name='election_...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
#!/usr/bin/python # ~~~~~============== HOW TO RUN ==============~~~~~ # 1) Configure things in CONFIGURATION section # 2) Change permissions: chmod +x bot.py # 3) Run in loop: while true; do ./bot.py; sleep 1; done from __future__ import print_function import sys import socket import json # ~~~~~==============...
#!/usr/bin/env python import argparse import pathlib from collections import defaultdict DEFAULT_CPP_VERSION = '20' SRC_CMAKE_NAME = 'CMakeLists-default' DEST_CMAKE_NAME = 'CMakeLists.txt' SRC_MAIN_NAME = 'main-default' DEST_MAIN_NAME = 'main.cpp' def create_directories(proj): p = pathlib.Path(__file__).paren...
# -*- coding: utf-8 -*- """ Created on Tue May 19 22:28:09 2020 @author: lansf """ from __future__ import absolute_import, division, print_function import os import pkg_resources import numpy as np from ase.io import read from .vasp_dos import VASP_DOS from .coordination import Coordination import itertools from scip...
# coding: utf-8 # # Copyright 2018 The Oppia Authors. 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 # # Unless requi...
from search_engine_parser import GoogleSearch import asyncio def google(query): asyncio.set_event_loop(asyncio.new_event_loop()) final_result = '' try: linkIndex = 0 search_args = (query, 2) gsearch = GoogleSearch() gresults = gsearch.search(*search_args) queryRes...
from itertools import accumulate as ac N, K = map(int, input().split()) *S, = map(int, input()) l = [] c = 0 if N==1: l.append(S[0]) else: for i in range(N-1): c += 1 if S[i]!=S[i+1]: l.append(c) c = 0 if c: l.append(c+1) if S[0]==0: l = [0]+l if S[-1]...
from django.shortcuts import render from django.http import HttpResponse # Create your views here. posts = [ { 'author' : 'Sayan Manik', 'title' : 'Blog post 1', 'content' : 'First Post Content', 'date_posted' : 'May 25, 2019' }, { 'author' : 'Corey MS', 't...
#coding:utf-8 import win_unicode_console import math import random win_unicode_console.enable() w_list = [] w_score = [] w_dict = [] c = 0 def lis_2_dic(key_list, val_list): return dict(zip(key_list, val_list)) #step幅決めてrange指定 def drange(begin, end, step): n = begin while n + step < end: yield n ...
# -* encoding:utf-8 *- from appium import webdriver import time import unittest import os import math class AutoTest(unittest.TestCase): def test_setUp(self): desired_caps = { 'platformName' : 'Android', #测试平台的名称 'deviceName' : '192.168.56.101:5555', #连接的设备号,通过adb devices查看所...
from numpy import* from numpy.linalg import* x=array(eval(input(""))) a=zeros(x.shape[1], dtype=int) for j in range(x.shape[1]): a[j]=sum(x[:,j]) for j in range(x.shape[1]): if a[j]==max(a): if j+1==1: print("1") if j+1==2: print("2") if j+1==3: print("3") if j+1==4: print("4") if j+1==5: ...
tabla = int (input("Que tabla?:")) for v in range (1 ,11 ,1 ): print(f"{tabla} x {v} = {tabla*v}")
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class ExpenseCtrlEmployeeRuleInfo(object): def __init__(self): self._effective = None self._effective_end_date = None self._effective_start_date = None self._owner_type ...
#!/usr/bin/python import sys import csv import serial import os from itertools import izip from ctypes import * from struct import pack, unpack import struct import binascii # Test_branch changes # Test_bracnh changes 2 # add string t = 0 f = open('/home/kalach/workfile.csv', 'wb') ser = serial.Serial('/dev/rfcomm0'...
# The knows API is already defined for you. # return a bool, whether a knows b def knows(a: int, b: int) -> bool: return True class Solution: def findCelebrity(self, n: int) -> int: # find candidate for celebrity # when left and right meet at a point, this person is a potential celebrity ...
# -*- coding: utf-8 -*- """Tests for pybaselines._compat. @author: Donald Erb Created on March 20, 2021 """ from numpy.testing import assert_array_equal import pytest from pybaselines import _compat from .conftest import _HAS_PENTAPY def test_pentapy_installation(): """Ensure proper setup with pentapy.""" ...
from snovault import upgrade_step from . import _get_biofeat_for_target as getbf4t @upgrade_step('experiment_repliseq', '1', '2') def experiment_repliseq_1_2(value, system): if value['experiment_type'] == 'repliseq': value['experiment_type'] = 'Repli-seq' @upgrade_step('experiment_repliseq', '2', '3') d...
# -*- coding: utf-8 -*- # @Time : 2019/9/7 18:09 # @Author : LI Dongdong # @FileName: lc 208.py class TrieNode: def __init__(self): # 是否构成一个完成的单词 self.is_end = False self.children = [None] * 26 class Trie: def __init__(self): """ Initialize your data structure here...
import tensorflow as tf import numpy as np import load_cifer10 import random np.random.seed(20160612) tf.set_random_seed(20160612) # ネットワーク構成 class layer: def __init__(self): with tf.Graph().as_default(): self.prepare_model() self.prepare_session() def prepare_model(self): ...
import sys from random import randint from PyQt5 import uic, QtCore, QtWidgets from PyQt5.QtGui import QPainter, QColor from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets import QMainWindow from UI import Ui_MainWindow class YellowEllipses(QMainWindow, Ui_MainWindow): def __init__(self): super...
# 1 # name = input("What is your name?: \n") # print("Hello " + name) # 2 # x = 10 # print(x) #3 # personNumber = int(input("Choose any whole number: \n")) # if personNumber > 10: # print("Your number is greater than 10") # elif personNumber < 10: # print("Your number is less than 10") # else: # print("Your n...
# Load libraries import pandas from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt from sklearn import model_selection from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score from sklearn.linear_model import Percept...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('basic', '0029_auto_20160317_2257'), ] operations = [ migrations.CreateModel( name='Base', fields=[ ...
# -*- coding: utf-8 -*- import unittest import datetime from pyboleto.bank.bradesco import BoletoBradesco from testutils import BoletoTestCase class TestBancoBradesco(BoletoTestCase): def setUp(self): self.dados = [] for i in range(3): d = BoletoBradesco() d.carteira = '0...
#!/usr/bin/env python import logging from ProdAgentCore.Codes import errors from ProdCommon.Database import Session from ProdMgrInterface import MessageQueue from ProdMgrInterface.Registry import registerHandler from ProdMgrInterface.States.StateInterface import StateInterface from ProdMgrInterface.States.Aux impor...
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt from flask_login import LoginManager app = Flask(__name__) app.config['SECRET_KEY']='57ba628bb0b13ce0c676dfde280ba245' app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///site2.db' app.config['SQLALCHEMY_TRACK_MODIFICATION...
# class A: # def __init__(self): # print "enter A" # print "leave A" # class B(A): # def __init__(self): # print "enter B" # A.__init__(self) # print "leave B" class A(object): def __init__(self): print "enter A" print "leave A" class C(object): def __init__(self): print "enter C" print "le...
import json import numpy as np import datetime import pandas as pd name = "Paul Millsap" with open("./../data/player_monthly_PER.json") as fp: data = json.load(fp) date = list() pers = list() mt = range(1 , 13) mt = map(lambda x : "%02d" % x , mt) yt = range(2006 , 2017) yt = map(str , yt) result = dict() fo...
#coding:utf8 import downloader from translator import tr_ from utils import Soup, Session, query_url, get_max_range, Downloader, clean_title, update_url_query, get_print, get_ext, LazyUrl, urljoin, check_alive import ree as re import errors from ratelimit import limits, sleep_and_retry from error_printer import print_e...
from django.shortcuts import render from .forms import ViewAvailableCourse # Create your views here. def view_course(request): if request.method=="POST": form=ViewAvailableCourse(request.POST) if form.is_valid(): form.save() else: print(form.errors...
# -*- coding:utf-8 -*- __author__ = 'gzs2473' from PyQt4 import QtCore from PyQt4 import QtGui from ui.Ui_room import Ui_room_window from table_widget import TableWidget from play_window import PlayWindow from custom_dialog import CustomDialog class RoomWindow(CustomDialog, Ui_room_window): send_signal = QtCore...
def diagonalDifference(arr: list[list], size: int) -> int: """[summary] Args: arr (list[list]): [description] size (int): [description] Returns: int: [description] """ d1 = 0 d2 = 0 for i in range(size): for j in range(size): if i == j: ...
import unittest from migrator import main class TestMain(unittest.TestCase): def test_parse_uri(self): testcases = [ { 'uri': 'localhost', 'host': 'localhost', 'port': 6379, 'db': 0, }, { ...
from os.path import join import numpy as np import matplotlib.pyplot as plt import seaborn as sns from matplotlib.colors import ListedColormap from .settings import * class Figure: """ Base class for figures providing some common methods. Attributes: name (str) - figure name directory ...
# Author: Jaemin Jo <jmjo@hcil.snu.ac.kr> import numpy as np from pynene import Index class KNNKernelDensity(): SQRT2PI = np.sqrt(2 * np.pi) def __init__(self, X, online=False): self.X = X self.index = Index(X, w=(0.8, 0.2), reconstruction_weight=5) if not online: # if offlin...
from instapy import InstaPy session = InstaPy(username='XXXXXXX', password='XXXXXXX', headless_browser=False) session.login() session.unfollow_users(amount=1000, allFollowing=True, unfollow_after=0, sleep_delay=601) ...
# -*- coding:utf-8 -*- # @Time : 2020/7/29 # @Author : Stephev # @Site : # @File : Payment.py # @Software: import pymysql import csv import datetime #D:\workpalce\csv_file now_time_r = datetime.datetime.now() now_time = datetime.datetime.strftime(now_time_r,'%Y-%m-%d_%H_%M') class cnMySQL: def __init...
from abc import abstractmethod class Detector(object): def __init__(self, data_train, data_test, labels_train, extra_parameter): assert len(data_train) == len(labels_train), "Mismatch size" self.data_train = data_train self.data_test = data_test self.labels_train = labels_train ...
#!/usr/bin/python from matplotlib import pyplot if __name__ == '__main__': with open('walk-record.txt') as f: lines = f.readlines() score = [float(k) for k in [_[:-1].split(',')[-1] for _ in lines]] pyplot.plot(score, '.') pyplot.title('walk score as times') pyplot.xlabel('try times') ...
APPINFO_JSON = {u'sdkVersion': u'3', u'uuid': u'b3578af5-8a89-4a1d-9437-060a0b481c9e', u'appKeys': {u'AppKeyReady': 0, u'AppKeyUrl': 2}, u'companyName': u'Andrea Cerra', u'enableMultiJS': True, u'versionLabel': u'1.0', u'targetPlatforms': [u'aplite', u'basalt', u'chalk'], u'longName': u'PebbleHttp List', u'shortName': ...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': "SO - Product Price Check", 'version': '10.0.1.0.0', 'category': 'Sales Management', 'description': """ This module restricts a user from confirming a Sale Order/Quotation if it ...
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)): if i != len(nums): for j in range(i+1, len(nums)): if nums[i]+nums[j] ...
from definitions import PIS_OUTPUT_INTERACTIONS import logging import json import requests import gzip import pandas as pd import re from io import BytesIO from .DownloadResource import DownloadResource import python_jsonschema_objects as pjo from .common import replace_suffix logger = logging.getLogger(__name__) cl...
# -*- coding: utf-8 -*- """ Created on Sat Dec 22 21:10:18 2018 @author: Gehad """ import pandas as pd from itertools import combinations def calc_p_class(trainingData,Class): count=0 for i in range(0,len(trainingData)): for j in range(0,7): if trainingData[i][j]==Class: c...
from netmiko import ConnectHandler from netmiko.ssh_exception import NetMikoTimeoutException from netmiko.ssh_exception import AuthenticationException from paramiko.ssh_exception import SSHException import sys host1 = { 'device_type': 'cisco_ios', 'ip': '10.4.0.17', 'username': 'Admin', 'password': 'NterOne1!', } hos...
import os import re import logging from lxml import etree from blogilainen.plugins import BasePlugin class Plugin(BasePlugin): def run(self, source, resource): target_meta = etree.Element('target-meta') for ext,t in source.targets.iteritems(): target = etree.Element('target', type=ext...
# -*- coding: utf-8 -*- from django.db import models from django.conf import settings from django.core.urlresolvers import reverse_lazy class Entry(models.Model): name = models.CharField(verbose_name=u'Заголовок', max_length=255) date_create = models.DateTimeField(verbose_name=u'Дата создания', ...
""" ASGI entrypoint. Configures Django and then runs the application defined in the ASGI_APPLICATION setting. """ import os # Fetch Django ASGI application early to ensure AppRegistry is populated # before importing consumers and AuthMiddlewareStack that may import ORM # models. from django.core.asgi import get_asgi_a...
# -*- coding: cp936 -*- # 绪论案例:Boston房价 # %matplotlib inline import matplotlib.pyplot as plt from sklearn import datasets from sklearn.feature_selection import SelectKBest,f_regression from sklearn.linear_model import LinearRegression from sklearn.svm import SVR from sklearn.ensemble import RandomForestRegressor bos...
# Dependencies from bs4 import BeautifulSoup import requests from splinter import Browser from selenium import webdriver import pandas as pd import time def init_browser(): executable_path = {"executable_path": "/usr/local/bin/chromedriver"} return Browser("chrome", **executable_path, headless=False) def...
import random def calcBayes(priorA, probBifA, probB): """priorA:A独立于B时的初始概率估计值 probBifA:A为真时,B的概率估计值 probB:B的概率估计值 返回priorA*probBifA/probB""" return priorA*probBifA/probB # priorA = 1/3 priorA = 0.9 prob6ifA = 1/5 prob6 = (1/5 + 1/6 + 1/7)/3 # postA = calcBayes(priorA, prob6ifA, prob6) # ...
from sardana.macroserver.macro import Macro, macro, Type @macro() def altOn(self): """Macro altOn""" acqConf = self.getEnv('acqConf') acqConf['altOn'] = True self.setEnv('acqConf', acqConf) self.info('switching altOn') @macro() def altOff(self): """Macro altOff""" acqConf = self.getEnv...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import traceback from .auth import braintree from .managers import CustomerManager # from .tasks import send_funds from model_utils.models import TimeStampedModel from delorean import Delorean from jsonfield.fields import JSONField from django.conf impo...
import json from django.contrib.auth import get_user_model from django.core.cache import cache from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from rest_framework import viewsets...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render,redirect,HttpResponse from models import * def index(request): return render(request,'users/index.html') def show(request): context = {"User":User.objects.all()} print User.objects.all() return...
def insertionSort(alist): for index in range(1,len(alist)): currentvalue = alist[index] position = index while position>0 and alist[position-1]>currentvalue: alist[position]=alist[position-1] position = position-1 alist[position]=currentvalue print " ".join(map(str, alis...
import torch import torch.utils.data import torchvision import numpy as np def make_weights_for_balanced_classes(labels,classes): labels = np.array(labels) #print(labels) weights=[] outs=[] weight = 1./ len(labels) for ic in range(classes): weights.append(weight/(labels==ic).sum()) ...
''' 2573번 빙산 ''' import sys from collections import deque input=sys.stdin.readline n, m=map(int, input().split()) board=[] for _ in range(n): board.append(list(map(int, input().split()))) q=deque() q2=deque() for y in range(n): for x in range(m): if board[y][x]!=0: q.append((x,y)) year=0...
#!/usr/bin/env python """Write a reduced lammpstrj file by skipping frames.""" import pathlib import sys import re import io import mmap from tqdm import tqdm def read_lammpstrj(lmp): """Iterate frames in a lammpstrj file.""" raw = [] with open(lmp, 'r') as infile: for lines in infile: ...
''' Created on 2011-9-24 ARG1: FILE NAME ARG2: YEAR ARG3: MONTH SAMPLE: d:\dp21 2011 SEP USAGE: JIE XI BAO GAO @author: caspar32 ''' import sys initialDay=17 endDay=21 startTime=20 endTime=05 specialBeginDay=20 specialEndDay=21 if __name__ == '__main__': fileName=sys.argv[1] year=sys.argv[2] month=...
# Chapter 04-01 # 시퀀스형 ''' < 자료구조 구분 기준> 1-1. 컨테이너(Container) - 서로다른 자료형 구성 가능 => list, tuple, collections.deque 1-2. Flat - 한 개의 자료형으로 구성 => str, bytes, bytes array, array.array, memoryview 2-1. 가변 자료구조 => list, bytes array, array.array, memoryview, deque 2-2. 불변 자료구조 => tuple, str, bytes ''' # ord(st...
import os import sys import dlib import glob import csv import pickle as pp from sklearn.neighbors import KNeighborsClassifier import pandas as pd from sklearn import preprocessing # from sklearn.model_selection import train_test_split import webbrowser from timeit import Timer from keras.preprocessing.image import img...
import pandas as pd from keras.models import Sequential from keras.layers import Dense, Activation from keras.optimizers import SGD from keras.layers.advanced_activations import ParametricSoftExponential, ParametricSoftplus from keras.regularizers import l1, activity_l1, l1l2 M = 30000 N = 1 nb_epoch = 100 num_experi...
from Calc import * a= int(input("Enter The First no:")) b= int(input("Enter Seccond no:")) char=(input("Choose The Operation..\nAdd= a,A\nSub=s,S\nmul=M,m\ndiv=d,D\n")) if char =='a'and'A': c=add(a,b) print("Addition:",c) elif char =='s'and 'S': c=sub(a,b) print("Substraction",c) elif char =='m'and 'M':...
import time def selection_sort(data, drawData, tick): for i in range(len(data) - 1): minIndex = i for j in range(i + 1, len(data)): if(data[j] < data[minIndex]): drawData(data, ['blue' if x == minIndex else 'gray' for x in range(len(data))]) time.sleep(tick) minIndex = j drawData(...
class Videogame: def __init__(self,id,name,year,price,category1,category2,category3,picture,banner,description): self.id = id self.name = name self.year = year self.price = price self.category1 = category1 self.category2 = category2 self.category3 = category3 ...
import os import json import sys import shutil import uuid import datetime import uuid from urllib.parse import unquote_plus import pandas as pd import torch from botocore.exceptions import ClientError from torch.utils.data import DataLoader, SequentialSampler, TensorDataset from transformers import BertModel, BertTok...
print("Demonstration of List") batches = ["PPA","LB","Angular","Python"] print(batches) print(batches[0]) print(batches[1]) print(batches[-1]) print(batches[1:]) print(batches[:3]) # We can store Heterogenious data data1 = [11,"Shri Swami Samarth",3.14] print(data1) data2 = [23,"Om Shiv Shankara",22.48...
from transaction import Transaction class Response(Transaction): RESPONSE_ACCOUNT_BALANCE= "Account balance" RESPONSE_MEMBERSHIP_NUM= "Membership number" def __init__(self, date_time, token): super().__init__(date_time, token) self._input = input @staticmethod def _validate_s...
import requests, json HEADER = "http://127.0.0.1:5000" def get_all_flights(): get_request = requests.get(HEADER + f'/dbInfo') response = get_request.text jsons = json.loads(response) string_to_return = "" for flight in jsons: flight_string = f"ID: {flight['id']}, From: {flight['city_f...
import sys import ply.yacc as yacc from parameter import * def p_document(p): """ document : document : token_list """ if len(p) == 1: p[0] = [] else: p[0] = p[1] def p_token_list(p): """ token_list : token_list : STRING token_list token_list : parameter...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import random import torch import argparse import torch.nn as nn import torch.utils.data as data import torchvision.transforms as transforms #from src.feat_model import * #from src.featset import * from src.rank_model import * from src.rankset import * import nu...
import FWCore.ParameterSet.Config as cms allConversions = cms.EDProducer('ConversionProducer', AlgorithmName = cms.string('mixed'), #src = cms.VInputTag(cms.InputTag("generalTracks")), src = cms.InputTag("gsfGeneralInOutOutInConversionTrackMerger"), convertedPhotonCollection = cms.string(''), ## or emp...
# -*- coding: utf-8 -*- """ Tests for the tensor transform functions. Run with pytest. Created on Sat May 9 00:09:00 2020 @author: aripekka """ import sys import os.path import numpy as np sys.path.insert(1, os.path.join(os.path.dirname(__file__),'..')) from tbcalc.transverse_deformation import * from tbcalc impo...
import sys for _ in[0]*int(input()): input() f=1 a=list(map(int,input().split())) for x in a: if a.count(x)>2:f=0 print("Yes" if f else "No")
def get_php(keyword: int = 4, passwd: str = "", salt: str = ""): return """<?php function dept($data,$salt="%s",$change=0x80){$data=base64_decode($data);$saltm = md5($salt);$len = strlen($data);$pass=strrev(str_rot13(substr(strrev($data^str_repeat($saltm,ceil($len / 32)) ^ str_repeat(chr($change),$len)),0,-32)));re...
from sys import version from Nodo import Nodo from AutoNuevo import AutoNuevo from AutoUsado import AutoUsado from zope.interface import implementer class Lista: __comienzo=None __actual=None __index=0 __tope=0 def __init__(self): self.__comienzo=None self.__actual=...
# readline 함수로 모든 내용을 읽어보기 f = open("C:/Users/chasu/OneDrive/바탕 화면/doit/새파일.txt", "r") while True: line = f.readline() if not line: break print(line) f.close() # while True: 무한 루프 안에서 f.readline()을 사용해 파일을 계속해서 한 줄씩 읽어 들인다. # 만약 더 읽을 줄이 없으면 break를 수행한다. # readline은 더 읽을 줄이 없다면 None을 출력한다.
''' simulation_parameters.py -> created to ensure consistency throughout ALL other files ''' ########################################################## #Data parameters #From the data, do not change unless you played with the preprocessing part data_file = '../data_preprocessing/data_processed/final_table' data_dow...
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompan...
# 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, software # distributed under t...
# Fagprojekt # mTRF in Python # Load dependencies import numpy as np import matplotlib.pyplot as plt from scipy.io import loadmat from os.path import join import mne from mne.decoding import ReceptiveField from sklearn.model_selection import KFold from sklearn.preprocessing import scale # The following is from examp...
from django.shortcuts import render from rest_framework.decorators import api_view from rest_framework.response import Response import sys #from django.http import JsonResponse from .serializers import StudentrecordsSerializer from .models import Studentrecord @api_view(['GET']) def apiInfo(request): api_urls = {...
def encryptionMode(encryptionAlgorithm): modeInput = input("What would you like to do? ") return modeInput def shiftSelect(shift): shiftInput = -26 #initalize shift input to an invalid input while shiftInput > 25 or shiftInput < -25: #I have cast here instead as in this case I only have to do #it once ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # File Name: 练习4_红包 # Description : # Author : SanYapeng # date: 2019-05-01 # Change Activity: 2019-05-01: import random """ 基本单位 0.01 获取到的金额必须大于这个数,才能生效 金额和红包个数整除为基本数,那么金额就位0.01 第一个红包金额随机,但是必须得小于输入金额 """ import random # s...
#!/usr/bin/env python import cPickle, sys, shutil, time, os, magic def unpickler(): unpic_file = open('myPickle', 'r') cPickle.Unpickler(unpic_file) temp = cPickle.load(unpic_file) unpic_file.close() printer(temp) return temp def printer(tmp_file): print '%-50s%-30s%-30s%-10s%-15s\n'%('Fil...
#!/usr/bin/env runaiida # -*- coding: utf-8 -*- import os import click @click.command('cli') @click.argument('codelabel') @click.option('--submit', is_flag=True, help='Actually submit calculation') def main(codelabel, submit): """Command line interface for testing and submitting calculations. This script ext...
#nvidia-smi #~/.keras/keras.json #import keras #print keras.__version__ #1.2.2 #https://faroit.github.io/keras-docs/1.2.2/ from keras.models import Sequential from keras.layers.pooling import MaxPooling2D from keras.layers.core import Dense from keras.layers.core import Flatten from keras.layers.core import Dropout ...
#!/usr/bin/python3.6 import os import sys import argparse from subprocess import call parser = argparse.ArgumentParser(description='Use inkscape to convert a file from svg to png.') parser.add_argument('file', type=argparse.FileType('r'), nargs='+', default=None, help='SVG file') args = parser.parse_args() # print(...
# To-Do List from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, Date from sqlalchemy.orm import sessionmaker from datetime import datetime, timedelta class DBCon: Base = declarative_base() def db_session(self): ...
__author__ = 'sonic-server' from handler import * handlers = [ (r'/', home_handler), (r'/api/dataChannel', data_handler), (r'/api/ctrl', ctrl_handler) ] modules = { }
#!/usr/bin/env python import json from solidfire.common import ApiServerError from tests.base_test import SolidFireBaseTest class TestApiServerError(SolidFireBaseTest): def test_should_provide_defaults_with_empty_string(self): api_error = ApiServerError('aMethod', '') self.assertEqual(api_error...
#!/usr/bin/env python3 from argparse import ArgumentParser def calc_fizzbuzz(n, rules=None): string = '' for divisor, result in rules.items(): if n % divisor == 0: string += result if string == '': string += str(n) return string def create_rules(): print('Welcome to...
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import Email, DataRequired class SignUpForm(FlaskForm): email = StringField('Email', validators=[DataRequired(), Email()]) CourseName = StringField('CourseName', validators=[Dat...
import os.path def python(): namethefile = input("INPUT THE NAME OF THE FILE \n") if os.path.isfile(namethefile+".py"): files = open(namethefile+".py","r+") else: files = open(namethefile+".py","x") files.close() files = open(namethefile+".py","r+") files.wri...
import cv2 import pathlib face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') list = [] namelist = [] currentDirectory = pathlib.Path('./TrainedFaces/') for currentFile in currentDirectory.iterdir(): model = cv2.face.LBPHFaceRecognizer_create() model.read(str(currentFile)) nameli...