text
stringlengths
38
1.54M
''' Write a python function, encrypt_sentence() which accepts a message and encrypts it based on rules given below and returns the encrypted message. Words at odd position -> Reverse It Words at even position -> Rearrange the characters so that all consonants appear before the vowels and their order should not change ...
# class Air: # __brand = '' # __price = 0 # __time = 0 # # def setBrand(self, brand): # self.__brand = brand # # def getBrand(self): # return self.__brand # # def setPrice(self, price): # if price <= 0: # print('价格不能为零为负!') # else: # self....
import json import pytest from fakeredis import FakeRedis from petisco import Command from petisco.extra.redis import RedisCommandBus from tests.modules.extra.rabbitmq.mother.command_persist_user_mother import ( CommandPersistUserMother, ) from tests.modules.extra.redis.mother.redis_command_bus_mother import ( ...
#! /usr/bin/python import os import sys import re import l1cmnd import fkocmnd (IFKOdir,fko) = fkocmnd.GetFKOinfo() (ATLdir, ARCH) = fkocmnd.FindAtlas(IFKOdir) print ARCH print "ATLdir='%s', ARCH='%s'" % (ATLdir, ARCH) # [time,mflop] = l1cmnd.l1time(ATLdir, ARCH, 'd', 'dot', 80000, 'dot1_x1y1.c') # print "time=%f, ...
#소인수 분해 print("소인수 분해 > 숫자 입력") x = int(input("?")) d = 2 while d <= x: if x % d == 0: print(d) x = x / d else: d = d + 1 #주사위 import random print("주사위 게임") total = 1000000 ev = 0 for i in range(total): if random.randint(1, 6) == 2: ev = ev + 1 print(ev / total * 100, "...
# -*- coding: utf-8 -*- """ Created on Fri Sep 15 09:01:52 2017 @author: Santosh Bag reads NSE bhavcopy file in zip format and puts into database format is "cmDDMMMYYYYbhav.csv.zip" """ import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import datetime #import date, timedelta import pandas a...
""" RNN for Time series prediction: It did not perform as autoregressive linear model This is because RNN has too many parameters and hence flexibility Linear regression: * input shape: 2D array: NxT, output-shape: NxK * i = Input(shape=(T,)) # input layer of shape T * model.predict(x.reshape(1, -1))[0, 0...
#Ingresar los datos del sueldo mensual, codigo de estado civil (1soltero-2casado con hijos-3casado sin h) y el nombnre del empleado. # Se debe descontar el 3% de obra social y el 11% de aportes jubilatorios y se debe incrementar $500 si es casado, $ 900 con hijos. # ENTRADAS: n(nombre) - c(codigo estado civil) - s(sue...
from pandas import DataFrame def pd_index(df: DataFrame, name: str): return df.columns.get_loc(name)
""" course Class definitions for Course and Instructor. """ import ccutils class Instructor: """ Instructor class. For available fields see __init__ """ def __init__(self, fini, lname, andrew): # string initial letter of first name, capitalized e.g. "J" self.first_initial = fini ...
from piepline.monitoring.monitors import AbstractMonitor from piepline import events_container from piepline.train import Trainer from piepline.train_config.metrics_processor import MetricsProcessor __all__ = ['MonitorHub'] class MonitorHub: """ Aggregator of monitors. This class collect monitors and provide...
# -*- coding: utf-8 -*- ## Copyright 2012 Peter Halliday ## ## 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 requir...
import inspect import types from typing import cast from tensorflow.keras import Input, Model, regularizers from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, BatchNormalization, \ GlobalMaxPooling2D def SingleOutputCNN( input_shape, output_shape, cnns_per_...
from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm from .form import * #from . import loaddata from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user,authenticate,login from django.contrib.auth.models import User from django.co...
import torch import torch.nn as nn from .styled_conv2d import * from .multichannel_image import * from .modulated_conv2d import * from .idwt_upsample import * class MobileSynthesisBlock(nn.Module): def __init__( self, channels_in, channels_out, style_dim, ...
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'MFC' __time__ = '2020-04-27 09:50' """ leetcode探索:在 FIFO 数据结构中,将首先处理添加到队列中的第一个元素。 队列是典型的 FIFO 数据结构。 插入(insert)操作也称作入队(enqueue),新元素始终被添加在队列的末尾。 删除(delete)操作也被称为出队(dequeue)。 你只能移除第一个元素。 同栈一样,队列也可以用顺序表或者链表实现。 Queue() 创建一个空的队列 enqueue(item) 往队列中添加一个item元素 dequ...
from math import * from numpy import * from matplotlib import * from pylab import * import MDAnalysis import numpy as np import numpy.linalg import matplotlib.pyplot as plt from MDAnalysis.analysis.rms import RMSF from MDAnalysis.analysis import align ############################################### # USAGE notes ######...
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import multiprocessing import sys import rumps rumps.debug_mode(True) from voiceplay import __title__ as vp_title from voiceplay.cli.argparser.argparser import MyArgumentParser, Help from voiceplay.logger import logger from voiceplay.utils.updatecheck import check_up...
from invoke import task, run from subprocess import call @task def build(c): call("docker-compose down", shell=True) call("docker-compose build", shell=True) call("docker-compose run server python3 manage.py db_setup", shell=True) call("docker-compose up -d", shell=True)
import position pospx = position.getCurrentPositionPx(5, 200) heading = position.getHeading(5, 200, 1) angle = position.getTurnAngle(pospx, 1) print "position: ",pospx print "heading: ",heading print "angle: ",angle position.draw(pospx, 1)
''' Created on Aug 20, 2012 @author: Naved ''' from django.contrib import admin class BaseModelMinAdmin(admin.ModelAdmin): list_filter = ['is_active', 'added', ] list_display = ['is_active', 'added', ] class BaseModelAdmin(BaseModelMinAdmin): list_display = ['name', 'page_header', 'pa...
import pygame import itertools import random import tracer class Board: def __init__(self, cols, rows, size): self._cols = cols self._rows = rows self._size = size self._surface = pygame.Surface([self.get_width(), self.get_height()]) self._board = [[(0, 0, 0) for i in rang...
#!/usr/bin/python # -*- coding: utf-8 -*- ''' 【程序3】 题目:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少? 1.程序分析:在10万以内判断,先将该数加上100后再开方,再将该数加上268后再开方,如果开方后       的结果满足如下条件,即是结果。 ''' import math for i in range(0,100000): x = int(math.sqrt(i+100)) y = int(math.sqrt(i+268)) if(x * x == i+100) and (y * y...
import json import multiprocessing as mp import traceback import time from dp.backend.base import get_kafka_client, get_kafka_messages from dp.config import TEST_CONFIG from dp.env import KAFKA_TOPIC_INGEST from dp import log from dp.backend.base import get_kafka_messages_multi_topic def test_ingestion_async(batch_...
import spacy import numpy as np from sklearn.neural_network import MLPClassifier import pickle from sklearn.metrics import confusion_matrix import os, sys class DataProc(): ''' Class for handling data processing, by extracting features and splitting into training and test data. ''' def __init__(sel...
import lib import theano import numpy as np def Embedding(name, n_symbols, output_dim, inputs): vectors = lib.param( name, np.random.randn( n_symbols, output_dim ).astype(theano.config.floatX) ) output_shape = [ inputs.shape[i] for i in xra...
# Adapted from https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly import os os.environ["CUDA_VISIBLE_DEVICES"] = "1" import numpy as np import keras from utils import * import random import pickle from scipy import ndimage image_size = [160, 160, 128] spacing = [1.2, 1.2, 1.5] organs_names = [...
import re from tensorflow.keras.datasets import imdb from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, GRU, Embedding from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint from tensorflow.keras.mode...
import matplotlib.pyplot as plt import random balls = 100 # number of balls p = 0.5 def distribution(p): choice = random.uniform(0, 1) if choice < p: choice = 1 else: choice = 0 return choice def galton(balls, p): result = [] for i in range(0, balls): course = 0 ...
import math import argparse import string import os from multiprocessing import Process global wordMap wordMap = {} def main(): #Parsing the command line arguments to run the wordCount parser = argparse.ArgumentParser(description = "Word Frequency") parser.add_argument('-o', '--outputFile', required=True) parser...
class Node: def __init__(self, data): self.left = None self.right = None self.data = data def insert(root, node): if root == None: root = node elif root.data > node.data: if root.left == None: root.left = node else: insert(root.left,...
import json from urllib.request import urlopen import re def saveData(json_url): json_object = urlopen(json_url) #gets the json object from the http request data = json.loads(json_object.read()) #creates a local file where we can write the information from the json object file = open("local.txt","...
from django.db import models class GraphicValue(models.Model): min = models.CharField(null=True, blank=True, verbose_name="Minimum Değer", max_length=250) max = models.CharField(null=True, blank=True, verbose_name="Maksimum Değer", max_length=250) middle = models.CharField(null=True, blank=True, verbose_n...
"""nnlib activation layers """ import numpy as np from .core import Layer from ..activations import get_activation from ..activations import ActivationFunction from ..initializers import get_initializer from ..initializers import Initializer class _Activation(Layer): """Activation layer abstract base class - al...
# -*- coding: utf-8 -*- """ Created on Mon Jun 23 10:46:38 2014 @author: MPsaris Script using salinity and conductivity to classify estuary stations """ import arcpy #import numpy import pandas as pd from arcpy import env import os.path import subprocess from IR2012_Functions import renameField arcpy.env.overwriteO...
""" This file implements the slowinput function. """ from src.core.utils.slowprint import slowprint def slowinput(text: str, # pylint: disable=R0913 interval: float = 0.03, end: str = "", end_interval: float = 0, fast: bool = False, char_count_in...
class Node: def __init__(self, data): self.data = data self.left = None self.right = None class Tree: def __init__(self, root): self.root = Node(root) def Successor(self, root, key): node = root large = None small = None while node: if node.data >= key: node = node.left else: ...
from flask import Blueprint, request, jsonify, g from flask.ext.login import login_required, current_user from .. import db from ..models.device import Device from . import csrf_protect, get_json_params, APIException bp = Blueprint("api_devices", __name__) @bp.route('/', methods=['GET']) @login_required def index()...
#!/usr/bin/env python import time from impacket.examples import logger from impacket import smb class lotsSMB(smb.SMB): def loop_write_andx(self,tid,fid,data, offset = 0, wait_answer=1): pkt = smb.NewSMBPacket() pkt['Flags1'] = 0x18 pkt['Flags2'] = 0 pkt['Tid'] = tid ...
# Copyright 2021, The TensorFlow Federated Authors. # # 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 o...
class Solution: def replaceDigits(self, s: str) -> str: output = '' for i in range(len(s)): if i % 2 != 0: output = output + (chr(ord(s[i-1]) + int(s[i]))) continue output += s[i] return output
# app.py """ Main server file that handles all client requests including socket calls and communication with postgres sql to store or fetch data like message and connected users in the public chat """ import os from os.path import join, dirname from datetime import datetime from dotenv import load_doten...
f_no = int(input("Enter the first number: ")) s_no = int(input("Enter the second number: ")) sum = f_no + s_no if sum in range(15, 20): print("sum = 20") else: print(sum)
import math import len_vec_c import time import numpy as np import len_vec_swig def lenv(vec): ''' input: a list, like [11, 1, 1, 0] ''' return math.sqrt(sum([i*i for i in range(vec)])) def lenv3(vec): return np.sqrt(np.array([i*i for i in range(vec)]).sum()) if __name__ == '__main__': # vec = 1000; # start1...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #import urllib.request import re plugin_version = '0.1' plugin_name = 'Adobe Flash' # #url = 'http://www.adobe.com/de/products/flashplayer/distribution3.html' #site = urllib.request.urlopen(url) def hello(): print('Loaded plugin: ' + plugin_name + ' ' + plugin_versio...
from django.urls import path from .views import PostsView app_name='quiz' urlpatterns = [ path('posts/', PostsView.as_view(), name='posts_view'), ]
""" Processando as informações da empresa. Utilize a linguagem de programação de sua preferência (e quaisquer bibliotecas que sejam necessárias) e escreva um programa que leia o nome de um arquivo JSON como parâmetro – que seguirá os mesmos moldes do arquivo funcionarios.json listado acima – e imprima as informações s...
from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator, InvalidPage, EmptyPage from django.contrib.auth.models import Group, User from django.http import HttpResponse, HttpResponseRe...
#! python #Thanks to https://docs.python.org/2/library/unittest.html import unittest """ I don't fully know how the __init__.py files work, so it looks like I'm just going to do this in a not-very-optimal way for now, but at least it's better than requiring an absolute path and making the code completely ...
# This programs cretes basic calculator using Python Class (OOP) import json class Calculator(): def __init__(self): self.num1 = 0 self.num2 = 0 self.resu = 0 def getonenum(self): self.num1 = int(input('Enter the Number: ')) def gettwonum(self): self.num1 = int(i...
class Solution(object): def findLadders(self, beginWord, endWord, wordList): """ :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: List[List[str]] """ word_dict = set(wordList) if endWord not in word_dict: return [] ...
from LCGenerator import random from Strategies.Interface import FieldStrategy from Strategies.Implementation import CurrencyPairStrategy, DateStrategy, VolumeStrategy class StatusStrategy(FieldStrategy): def __init__(self, population: list, date_strategy: DateStrategy, currency_strategy: Currency...
from mpl_toolkits.mplot3d import Axes3D from matplotlib.patches import FancyArrowPatch from mpl_toolkits.mplot3d import proj3d import matplotlib matplotlib.use ('TKAgg', warn=False, force=True) import matplotlib.pyplot as plt import numpy as np import sys class Arrow3D(FancyArrowPatch): def __init__(self, xs, ys, ...
from common.base_driver import BaseDriver import pytest #定义公共的fixture @pytest.fixture def common_driver(): driver = BaseDriver().base_driver() yield driver driver.close_app() driver.quit() #定义含有toast弹框的fixture @pytest.fixture def common_toast_driver(): driver = BaseDriver().base_driver(automati...
from ScenarioHelper import * def main(): CreateScenaFile( "c1050.bin", # FileName "c1050", # MapName "c1050", # Location 0x0001, # MapIndex "ed7150", 0x00002000, # Flags ...
import threading, time, datetime, json from concurrent.futures.thread import ThreadPoolExecutor import traceback import tornado.ioloop import tornado.web import tornado.websocket import tornado.template import tornado.httpserver from tornado import gen import ssl,os import OmniDB_app.include.Spartacus as Spartacus im...
""" App Configuration for the API Module """ from django.apps import AppConfig class ApiConfig(AppConfig): """ App Config for Api Module """ name = 'api'
import socket import sys import os import getpass import threading host = "127.0.0.1" port = 5012 username="" user_pass="" USER_FOLDER_PATH = "/Users/radhikamanivannan/Desktop/userfolders/" TIMER_TIME_SEC = 20.0 THREAD_RUN = True def checkupdates(): if THREAD_RUN == True: s = socket.socket() s.connect((host,por...
#!/usr/bin/python import numpy as np names = np.loadtxt("student_names.csv", delimiter=',', dtype=str) def create_grade_file(template_filename, name): lastname = name.split()[-1].lower() grade_filename = "grade_%s.txt" % lastname with open(template_filename, 'r') as template, open(grade_filename, 'w') as...
from flask import Blueprint, request, current_app, render_template, redirect, url_for, flash from flask_login import login_user, logout_user, login_required, current_user from werkzeug.utils import secure_filename from tblib.handler import json_response, ResponseCode from ..forms import OrderForm from ..services impo...
# coding: utf-8 __author__ = 'ZFTurbo: https://kaggle.com/zfturbo' from a1_common_functions import * import requests import zipfile def update_current_data(): store_file1 = INPUT_PATH + 'cases_country_latest.csv' store_file2 = INPUT_PATH + 'cases_all_latest.csv' store_file3 = INPUT_PATH + 'cases_state_l...
from django.contrib.auth import authenticate, login, logout from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect from django.contrib import messages # Create your views here. from .forms import LoginForm from django.contrib import messages def login_view(request): f...
from django.db import models from django.contrib.auth.models import User from django.utils.translation import gettext as _ from userena.models import UserenaBaseProfile class Author(UserenaBaseProfile): user = models.OneToOneField( User, unique=True, verbose_name=_('user'), related...
__author__ = 'Varun Tyagi' import androidlogutils import os import shutil log_file_location = '/mnt/sdcard/com.shoretel.RADialer/files/' class SMCLog: def __init__(self): self.andro = androidlogutils.adbHelper() # pass def start(self, dut, tcid, log_dir): self.andro.removeFiles(dut['...
from django.contrib import admin # Register your models here. from .models import GallerySection, SectionAlbum, AlbumPhoto class SectionAlbumModelAdmin(admin.ModelAdmin): list_display = ["album_title", "album_section", "updated", "timestamp"] # list_display_links = ["updated"] list_editable = ["album_ti...
# -*- coding: utf-8 -*- from datetime import datetime from flask import Flask, render_template, request, Response, json, jsonify, session from flask_migrate import MigrateCommand, Migrate from flask_script import Manager, Server from flask_sqlalchemy import SQLAlchemy from ext import init from mydb.db import...
lista = list() print('Digite 5 números inteiros.') lista.append(int(input('Digite um valor inteiro: '))) maior = lista[0] print('Valor adicionado na última posição do lista.') for count in range(1, 5): lista.append(int(input('Digite um valor inteiro: '))) for c in range(0, count): if lista...
## For å komma i gang med noko. import time minTekst = ("Hei verda") print(minTekst) time.sleep(2) print("Der sov eg 2 min") time.sleep(2) print("The End")
#!/usr/bin/env python3 """ Remove annotations from a document """ import sys import fitz def main(file_path: str) -> None: doc = fitz.open(file_path) for page in doc: annot = page.first_annot while annot: annot = page.delete_annot(annot) doc.save(file_path, encryption=fitz.P...
import os, sys binning = "Pt" #binning = "inclusive" if binning == "Pt": bins = ["0to70", "70to100", "100to200", "200to400", "400to600", "600toInf"] elif binning == "inclusive": bins = [""] for b in bins: if b == "": bstring = "" else: bstring = binning+"-"+b+"_" fDir = "DY1jToLL_...
# update_users # Implement the following function: # update_users : Takes in an old first name, an old last name, a new first name, and a new last name. Updates the users.csv file so that # any user whose first and last names match the old first and last names are updated to the new first and last names. The functio...
input = "Hezam Kafe Mohammed" def reverse(string): string = list(string) lenOfString = len(string) - 1 counter = 0 while counter < lenOfString: tempLetter = string[lenOfString] string[lenOfString] = string[counter] string[counter] = tempLetter counter +=1 lenOfSt...
# Database Assignment 02 # Author(s): John Shapiro import csv import pymysql # set up the credentials server = 'localhost' database = 'ippstest' user = 'ipps' password = '024680' # connect to the database conn = pymysql.connect(host = server, user = user, password = password, db = database) if (conn): print('Co...
import io import jwt # JWT claims # Modify the aud clain to much the DNS name of your gateway, or remove it payload = { 'aud': 'webthings.controlthings.gr' } # Read the generated private key with open('privkey.pem', mode='rb') as file: private_key = file.read() #J WT generation token = jwt.encode(payload, p...
""" SmartRegisterItemInfo操作用モジュール """ import os from aws.dynamodb.base import DynamoDB class SmartRegisterItemInfo(DynamoDB): """SmartRegisterItemInfo""" __slots__ = ['_table'] def __init__(self): """初期化メソッド""" table_name = os.environ.get("PAY_PAY_ITEM_INFO_DB") super().__init__...
# -*- coding: utf-8 -*- from dart_fss.api import filings, finance, info, shareholder, market __all__ = ['filings', 'finance', 'info', 'shareholder', 'market']
from django import forms class SearchForm(forms.Form): q = forms.CharField(label = 'Pretraga', max_length = 256, required = False, widget = forms.TextInput(attrs = {'size' : 100})) KATEGORIJE = ( (1, 'parkovi'), (2, 'spomenici'), (3, 'kafići/kafane'), (4, 'muzeji'), (5, 'pozorišta'), (6, 'bioskopi'), ...
import pygame import sys class Point(): def __init__(self,x,y): self.x=x self.y=y self.pos=(x,y) self.lie=False self.neighbours=0 def change_state(self): if self.lie == True: self.lie == False else: self.lie == True def get_neig...
from SimpleCV import Image import cv2 __author = "mimadrid" #img = Image('edi uveitis previa 11.png') windowTitle = "canny detector" cv2_img = cv2.imread('edi uveitis final6.png') scv_img = Image(cv2_img, cv2image=True) scv_img = scv_img.rotate90() def threshold(value): global scv_img # The t1 parameter is r...
import _init_paths import caffe import cv2 import numpy as np import numpy as np import os import skimage import sys import caffe import sklearn.metrics.pairwise as pw import math from fr_wuqianliang import * # sys.path.insert(0, '/Downloads/caffe-master/python'); # load Caffe model caffe.set_mode_gpu(); global net...
from os import path def open_file(): # function for requesting file name from user # and checking if the file exists in the specified directory or not while True: file = input('Enter file name: ') if path.exists(file): break else: print('Invalid file name or it does not exists!!') return open(file) ...
from django.shortcuts import render, redirect from django.core.urlresolvers import reverse from utils.decorators import login_required from df_user.models import Address from df_goods.models import Goods from django_redis import get_redis_connection from df_order.models import OrderGoods, OrderInfo from django.http imp...
import matplotlib matplotlib.use('TkAgg') matplotlib.rcParams['toolbar'] = 'None' import matplotlib.pyplot as plt import time import numpy as np from utils import Logger plt.ion() class ShowVariableLogger(Logger): def __init__(self, average_window=1, update_frequency=1): self.update_period = 1 / update_fr...
''' Works the same as our fast version ''' import numpy as np import matplotlib.pyplot as plt import numexpr as ne import time obj=plt.imread('jerichoObject.bmp') print obj.shape ref=plt.imread('jerichoRef.bmp') print ref.shape img=obj-ref #start=200e-6 #stop=13e-3 #stepSize=1e-6 #distance=np.arange(start,stop,stepSi...
from imutils.video import VideoStream import datetime import imutils import time import cv2 import collections from functools import reduce import gphoto2 as gp from camera_control import CameraControlManagerSubProcess, CameraControlMsg, release_camera, CAPTURE_IMAGE import concurrent.futures import numpy as np import...
from app.core.db import database from app.user.models import User from slugify import slugify from unicodedata import normalize class Transfer(database.Model): __tablename__ = 'transfer' id = database.Column(database.Integer, primary_key = True) value = database.Column(database.Integer) tujuan = datab...
import boto.ec2 import boto.ec2.autoscale from boto.ec2.autoscale import LaunchConfiguration from boto.ec2.autoscale import AutoScalingGroup from boto.ec2.cloudwatch import MetricAlarm from boto.ec2.autoscale import ScalingPolicy import boto.ec2.cloudwatch access_key_id = "" secret_access_key = "" REGION = "ap-south-...
import numpy as np from ..base import BaseLosses class CrossEntropy(BaseLosses): @staticmethod def forward(predictions:np.ndarray, ground_truths:np.ndarray): return np.mean(np.multiply(ground_truths, np.log(predictions)) + np.multiply((1-ground_truths), np.log(1-predictions)))...
#!/usr/bin/python # modelEditor.py is a python script to display fornt end of the model editor. It developed for FreeEDA software. It is written by Yogesh Dilip Save (yogessave@gmail.com) and Shalini Shrivastava. # Copyright (C) 2012 Yogesh Dilip Save and Shalini Shrivastava, FOSS Project, IIT Bombay. # This program ...
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class Question(db.Model): """Questions for users.""" __tablename__ = "questions" question_id = db.Column(db.Integer, primary_key=True) strand_id = db.Column(db.Integer) strand_name = db.Column(db.String(64)) standard_id = db.Column(db.Integer) standar...
import Augmentor as Augmentor image_path = 'images/' output_directory = 'output/' p = Augmentor.Pipeline( source_directory=image_path, output_directory=output_directory ) # p.flip_left_right(probability=0.5) # p.rotate(probability=1, max_left_rotation=25, max_right_rotation=25) # p.zo...
import requests import yaml import sys from WCLPayoutDistributor import WCLPayoutDistributor if len(sys.argv) < 3: print('Args: wclreport totalgold') sys.exit() id = sys.argv[1] total_currency = float(sys.argv[2]) with open('config.yaml', 'r', encoding="utf-8") as f: config = yaml.safe_load(f) resp = requests.ge...
import math import random import queue import ray from ray.rllib.train import torch from prey_dqn.prey_env import PreyEnv from prey_dqn.prey_policy import PreyPolicy from util.config_reader import ConfigReader class Preys(): def __init__(self): self.steps = 0 self.preys = [] self.hunter_...
from pypcsimplus import * import pypcsimplus as pcsim class LiquidModel400(pcsim.Model): def defaultParameters(self): p = self.params p.Frac_EXC = 0.8 # fraction of excitatory neurons p.OUScale = 0.4 p.Xdim = 15 p.Ydim = 6 ...
# output contact group in contact group score + volume + rsa import sys import itertools from cg import cg from naccess import naccess def main(): if len(sys.argv) < 3: print "Usage python proc_nvboard.py cg_file rsa_file" print "python proc_nvboard.py 1k2p.tip.hcg 1k2p.rsa" print "output: 1k2p.tip.hc...
# Michael Schorr # 2/28/19 # creating a list of anyone I want and inviting them to dinner on my new large dinner table. guests = ['george washington', 'bono', 'peter griffin'] message = ", Hey would you like to come to dinner on the 1st of March" print("Hey everyone I just bought a large new dinner table.") guests.ins...
#First, I will need to import the pandas module so that I can carry out dataframe operations. import pandas as pd #Now, I need to set my fields for column names for my dataframe fields = ["Scaffold", "Start", "Stop", "Element", "Score", "Strand", "Class", "Family", "Divergence"] #Now, I need to read the "aVan_rm.bed" f...
# try: # print("====") # print(x) # print("====") # print("====") # except KeyError as x: # print(x) # except NameError as e: # print(e) # print(111111) # s1="hello" # try: # int(s1) # except IndexError as e: # print(e) # except ValueError as e: # print(e) # except Exception as e: #...
import matplotlib.pyplot as plt import numpy as np import dxchange import os import sys if __name__ == "__main__": data_prefix = sys.argv[1] nscan = int(sys.argv[2]) ntheta = int(sys.argv[3]) nmodes = int(sys.argv[4]) ndet = 128 theta = np.zeros(ntheta, dtype='float32') scan = np....
# write down alphabet alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q', 'r','s','t','u','v','w','x','y','z'] message = input('Message to encrypt: ') message = message.lower() #to also encrypt CAPS shift = input('Number of shifts? ') shift = int(shift) d = ...