text
stringlengths
38
1.54M
import aocread import numpy as np box_strings = aocread.read_file('input03') class Box: def __init__(self, id, left, top, width, height): self.id = int(id) - 1 self.left = int(left) self.top = int(top) self.width = int(width) self.height = int(height) self.right = ...
# -*- coding: utf-8 -*- """ Created on Mon Mar 9 2015 @author: Oliver Lemke """ import numpy as np import numpy.matlib as M from numpy.matlib import rand,zeros,ones,empty,eye import time import sys import argparse import pickle import os # Define ismember function def ismember(a, b): bi = {} for i, el in en...
from django.contrib import admin from django.core.urlresolvers import reverse from django import forms from django.utils.safestring import mark_safe from utils import utils import models class MyThumbnailWidget(forms.TextInput): def render(self, name, value, attrs=None): return mark_safe(u'<h1>blah</h1>')...
# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod class Heater(object): __metaclass__ = ABCMeta @abstractmethod def on(self): pass @abstractmethod def off(self): pass @abstractmethod def is_hot(self): pass
import json import redis import requests from pymongo import MongoClient import pymongo class Data: def __init__(self, account_name): self.url = "https://proxy.eosnode.tools/v1/{}" # self.url = "https://api-kylin.eosasia.one/v1/{}" self.s = requests.Session() self.s.headers = { ...
from django.shortcuts import get_object_or_404,render from django.http import HttpResponse, HttpResponseNotFound, HttpResponseRedirect from django.urls import reverse from django.db.models import Q, ProtectedError from .models import Ingredient, MeasurementUnit from .forms import IngredientForm def index(request): ...
# Homework Lesson 3 # 1 - 1 favorieten = ["Alison Wonderland"] print(favorieten) # Output = ['Alison Wonderland'] # 1 - 2 favorieten.append("Lido") print(favorieten) # Output = ['Alison Wonderland', 'Lido'] # 1 - 3 favorieten[1] = "Boris Brejcha" print(favorieten) # Output = ['Alison Wonderland', 'Boris Brejcha']...
from PyQt5.QtCore import QSize, QSizeF, Qt from PyQt5.QtGui import QImage, QPainter, QTransform from PyQt5.QtWidgets import QWidget from QPanda3D.QPanda3D_Keys_Translation import QPanda3D_Key_translation from QPanda3D.QPanda3D_Modifiers_Translation import QPanda3D_Modifier_translation, QTimer from direct.showbase.Messe...
from flask import Flask app = Flask(__name__) @app.route('/aaa/<bbs_id>') @app.route('/aaa', defaults={ 'bbs_id': 100 }) def aaa(bbs_id): return "aaa의 {}번 글 입니다.".format(bbs_id) if __name__ == '__main__': app.run()
import xlrd from datetime import datetime from .models import * def get_or_none(classmodel, **kwargs): """ the function will get the from the Model if exist other wise will return none @author : Arun Gopi @date : 3/4/2016 """ try: return classmodel.objects.get(**kwargs) except classmodel.DoesNotExist...
# coding: utf-8 """ Загрузчик шаблонов (темплейтов) для генерации пользовательского интерфейса для m3_ext_demo.ui. Необходимость данного шаблона обусловлена спецификой реализации template-loaders в django. Для корректной работы загрузчика в settings.py прикладного приложения необходимо добавить строку 'm3_ext_demo.ui...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # pylint: disable=missing-docstring """Bot for Webex Teams - Define decorator for bot - Show/Create/Delete webhook for Webex Teams Links: - user account: https://developer.webex.com/ - webhook api: https://developer.webex.com/docs/api/v1/webhooks - buttons and card...
import turtle import random for i in range(3): col = random.randint(0, 2) sel = random.randint(0, 1) if(col == 0): turtle.pencolor('yellow') elif (col == 1): turtle.pencolor('blue') elif(col == 2): turtle.pencolor('red') if(sel == 0): turtle.forward(100) elif ...
def get_csv_and_pred(i=42): elements = ['Pr', 'Ni', 'Ru', 'Ne', 'Rb', 'Pt', 'La', 'Na', 'Nb', 'Nd', 'Mg', 'Li', 'Pb', 'Re', 'Tl', 'Lu', 'Pd', 'Ti', 'Te', 'Rh', 'Tc', 'Sr', 'Ta', 'Be', 'Ba', 'Tb', 'Yb', 'Si', 'Bi', 'W', 'Gd', 'Fe', 'Br', 'Dy', 'Hf', 'Hg', 'Y', 'He', 'C', 'B', 'P'...
import time class PID: def __init__(self, Kp=0, Ki=0, Kd=0, sat=1023): #Initialise gains self.Kp = Kp self.Ki = Ki self.Kd = Kd self.sat = sat #Initialise delta variables self.cur_time = time.time() self.prev_time = self.cur_time ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 第一行注释为了告诉Linux/OS X系统,这是一个Python可执行程序,Windows系统会忽略这个注释 # 第二行注释是为了告诉Python解释器,按照UTF-8编码读取源代码,否则,你在源代码中写的中文输出可能会有乱码。 n = 32 f = 4325.564 s1 = 'hello, world' s2 = 'hello, \'Jin\'' s3 = r'hello, "Jin"' s4 = r'''hello, Jin! das''' print(n) print(f) print(s1) print(s2) prin...
#1 print('Task 1') for x in range(0, 13): print(x, 'Results') for y in range(0, 13): z = y * x print(x, '*', y, '=', z)
from PIL.ExifTags import TAGS from PIL import Image def testForExif(imgFileName): try: exifData = {} imgFile = Image.open(imgFileName) info = imgFile._getexif() # Extrae metadatos de una imagen if info: for (tag,value) in info.items(): decoded = TAGS.ge...
# https://leetcode.com/problems/n-th-tribonacci-number/ """ The Tribonacci sequence Tn is defined as follows: T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. Given n, return the value of Tn. Example 1: Input: n = 4 Output: 4 Explanation: T_3 = 0 + 1 + 1 = 2 T_4 = 1 + 1 + 2 = 4 Example 2: Input: n...
#!/usr/bin/env python # encoding: utf-8 from pyroute2 import IPDB import time class RtTable(): def __init__(self): """ rip_entry = [ {'dst': '172.16.1.0/24', 'metric': 1, #1-16 'gateway': '172.16.1.2', 'interface': 4, 'timer': 0, } ] ...
from World import Narrative from World.Types.Log import Message from Grammar.tree import Node from Grammar.actions import Terminals as T from Grammar.plot import export_grammar_plot from copy import copy class Progress: quest: Node = None semantics_indices = {} semantics_parsed_for_branches = [] cu...
import datetime as dt import matplotlib.pyplot as plt from matplotlib import style import pandas_datareader.data as web import pandas as pd df = web.DataReader('TSLA', 'yahoo', '2018-01-01', '2018-01-05') exit(df)
# -*- coding: utf-8 -*- from django.test.client import Client from networkapi.test.test_case import NetworkApiTestCase from networkapi.util.geral import mount_url class RouteMapPostSuccessTestCase(NetworkApiTestCase): route_map_uri = '/api/v4/route-map/' fixtures = [ 'networkapi/config/fixtures/ini...
import os import subprocess as sp print("Hello, what is your name: ",end='') name=input() print("{}, which software service you need: ".format(name),end='') sw=input() if sw=='firefox': cmd= "ssh -X -l root 172.17.0.2 firefox" sp.getoutput(cmd) elif sw=='atom': cmd= "ssh -X -l root 172.17.0.2 atom" sp.getoutput(...
import ex3 import point_cloud import numpy as np from matplotlib import pyplot from matplotlib import patches # # an attempt at constructing the # boundary operators of the graph # from the given threshold in ex3.py. # # SCRATCH THAT # First, just try to manually visualize # all 2-simplices # (complete graphs on 3 ve...
from core.base.parser import StaticParser from core.utils import parse_hexstring from core.base.parser import STR_TEMPLATE class SetProgressStatusParser(StaticParser): name = 'MSG_Set_Progress_Status' event_code = '1003' def _make_str(self, container): data = parse_hexstring(container.src_data.dat...
from core.models.Employee import Employee from django.db.utils import IntegrityError import pytest @pytest.mark.django_db class TestEmployee: """Test for employee models.""" def test_register_employee(self): """test registering employee.""" employee = Employee.objects.create( ...
import numpy as np import pytest import tensorflow as tf from sklearn.metrics import mean_squared_error from ml_intuition.evaluation.performance_metrics import overall_rms_abundance_angle_distance, \ cnn_rmse, per_class_rmse, dcae_rmse, average_angle_spectral_mapper sess = tf.Session() def softmax(x: np.ndarray...
from socket import * serverSocket = socket(AF_INET,SOCK_STREAM) serverSocket.bind(("",8899)) serverSocket.listen(5) clientSocket,clientInfo = serverSocket.accept() recvData = clientSocket.recv(1024) print ("%s:%s"%(str(clientInfo),recvData)) clientSocket.close() serverSocket.close()
"""Data manipulation tools for cognate detection.""" import numpy as np import itertools as it import collections import csv import lingpy from . import distances from . import ipa2asjp def clean_word(w): """Clean a string to reduce non-IPA noise.""" w = w.replace("-", "") w = w.replace(" ", "") w...
# Generated by Django 2.0 on 2018-07-30 19:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0003_remove_post_image'), ] operations = [ migrations.AddField( model_name='post', name='image',...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'enter_ques.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui from st_entry import Ui_MainWindowStent import urllib2 import urllib try: ...
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set() import statsmodels.api as sm import warnings warnings.filterwarnings('ignore') df = pd.read_csv('../csv_files/1.03. Dummies.csv') # print(df.drop(['Attendance'], axis=1)) f = lambda x: 1 if x == 'Yes' else 0 # df['Attendan...
import p44_random_tools as RT reload(RT) Nx = 100 k = np.arange(Nx,dtype='complex') x = np.arange(0,1,1./Nx) Ak = np.zeros(Nx,dtype='complex') odds = k.real%2 == 1 # -Nx keeps the normalization right, so F(x) = 1,0 # 1/np.pi is for the actual series. # 1j makes it a sign series. # Ak[0]=50 keeps the zero-point right...
from time import sleep def analisar(* val): mai = 'nenhum' print('~'*40) print('Analisando os valores passados...') for i, v in enumerate(val): print(v, end=' ') if i == 0 or v > mai: mai = v sleep(0.3) print(f'- Foram informados {len(val)} valores ao todo') ...
#!/usr/bin/env python from setuptools import setup # Lets makes ure we have the correct modules installed before continuing. # OpenSSL is required. def readme(): with open('README.rst') as f: return f.read() setup( name="pykeytool", version="0.2", description="pykeytool - IoT SC PKI Tool fo...
import datetime import logging import time from urllib.parse import quote import uuid import requests from django.core.cache import cache from django.shortcuts import render, redirect from django.conf import settings from django.http import HttpResponse, HttpResponseRedirect from django.utils.encoding import force_tex...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('profiles', '0012_auto_20141030_2158'), ] operations = [ migrations.CreateModel( name='message', fiel...
import tarfile import os for filename in os.listdir(): if filename.endswith(".tar.gz"): tar=tarfile.open(filename) name = tar.getnames() if os.path.isdir(file_name): pass else: os.mkdir(file_name) tar.extract(name, file_name + "_files/") # for root,dir,files in os.walk('/path/to/dir...
#!/usr/bin/env python3 import sys import random VOCABFILE = 'hogwarts-houses-vocab.tsv' houses = {} with open(VOCABFILE) as vf: for line in vf: uri, name = line.strip().split('\t') houses[uri] = name namedata = [] for uri, house_name in houses.items(): housefn = house_name.lower() + ".txt" ...
import selenium.webdriver as webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By class taobao_infos: # 对象初始化 def __init__(self): self.url = "https://login.taobao.com/member/login.j...
#!/usr/bin/python import copy import sys sys.setrecursionlimit(1000000) def check(word, arrs, count): warr = list(word) karrs = copy.copy(arrs) for c in warr: if c not in arrs: arrs[c] = 0 karrs[c] = 0 if karrs[c] == 0: return count karrs[c] = ka...
# Generated by Django 2.2 on 2019-04-10 12:41 from django.db import migrations, models import django.db.models.deletion import phonenumber_field.modelfields class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Use...
from abc import ABC, abstractmethod class SpikeElement(ABC): # Abstract methods @staticmethod @abstractmethod def get_installed_spif_cls_list(): pass @staticmethod @abstractmethod def get_display_name_from_spif_class(spif_class): pass @abstractmethod def run(sel...
#!/usr/bin/python # coding:utf-8 import os import cv2 import random import numpy as np from ctools.basic_func import get_all_files for j, left_right in enumerate(["left", "right"]): for area in range(5): # area = 0 # image_dir = "/media/cobot/5C8B2D882D247B561/project_data/screw_miss/1217" ...
#!/usr/bin/env python # coding: utf-8 # In[17]: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns get_ipython().run_line_magic('matplotlib', 'inline') # In[25]: df = pd.read_csv('student-mat.csv') df.head() # In[20]: sns.set(style = 'white') g = sns.lmplot(y='Walc',...
""" Features 1. if title contain special 2. if title contain number (usually phone number) 3. """ from digoie.domain.docs.parser import doc_url from digoie.domain.docs.parser import doc_title from digoie.domain.docs.parser import doc_body class Doc(object): # URL = None; # TITLE = None; # BODY = ...
import uuid from rest_framework import status from rest_framework.decorators import api_view, parser_classes from rest_framework.response import Response from rest_framework.parsers import FormParser, MultiPartParser from .models import products, attributes from .serializers import productsSerializers, attributesSeria...
import chess import encode import copy import util import numpy as np import scoring # wrapper for chess board class Game: def __init__(self, board=None): if board is None: self.board = chess.Board() else: self.board = board self.key = None s...
#!/usr/bin/env python3 """ Advent of Code 2017: Day # """ import os from shared.readdayinput import readdayinput def first_half(d): """ first half solver: """ d = d.split(',') away = 0 vert = 0 horzl = 0 horzr = 0 for step in d: if step == 'n': vert += 1 ...
from django.contrib import admin from .models import User, Profile, Review, UserRecommendation # Register your models here. class UserAdmin(admin.ModelAdmin): readonly_fields = ('slug',) class ProfileAdmin(admin.ModelAdmin): readonly_fields = ('user',) class ReviewAdmin(admin.ModelAdmin): # fields = ('au...
import os import omise def create_token(): omise.api_public = os.getenv("OMISE_PKEY") token = omise.Token.create( name="Somchai Prasert", number="4242424242424242", expiration_month=10, expiration_year=2022, # city="Bangkok", # postal_code="10320", # se...
# Version 8.1.1 # ############################################################################ # OVERVIEW ############################################################################ # This file contains descriptions of the settings that you can use to # configure te alert action for PagerDuty. The TA writes to the ...
from configs import * import speech_recognition as sr from random import choice import pyttsx3 import datetime import sys from time import sleep as wait import webbrowser as wb def intro(): print('=============================================================================================') print('...
n = int(input()) if n in [1,3,5,7,8,10,12]: print(31) elif n in [4,6,9,11]: print(30) else: print(28)
from __future__ import print_function import os import sys import time import boto from boto.s3.key import Key from pymongo import MongoClient from pymongo.cursor import Cursor from pymongo.errors import AutoReconnect # Monkey-patch PyMongo to avoid throwing AutoReconnect # errors. We try to reconnect a couple times...
from ledger import messaging import coloredlogs, logging from errors.errors import ApiBadRequest, ApiInternalError coloredlogs.install() from addressing import addresser from protocompiled import payload_pb2 from transactions.common import make_header_and_batch async def send_float_account(**in_data): """ ...
''' Created on 24/03/2013 @author: artavares This scripts writes a .csv file with the average values of user-selected fields from a sequence of SUMO output files. Example: duaIterate.py generated 100 tripinfo files: tripinfo_000.xml to tripinfo_099.xml, and the user wants to know the average travel time of each it...
import requests # Para tipos de peliculas respuesta = requests.get(url='http://127.0.0.1:5000/type/all') if respuesta.ok: print(respuesta.json()) else: print('No hay respuesta') # Para tener lista de actores respuesta = requests.get(url='http://127.0.0.1:5000/actors/all') if respuesta.ok: print(respuesta....
# Some utility methods for sets and dictionaries. In a better world these # could all be replaced by fold(). import copy import itertools def iterlen(iterator): return sum(1 for i in iterator) def intersection(sets): if len(sets) == 0: return set() base = copy.copy(sets[0]) for s in itertools.islice(se...
from scisoftpy.dictutils import DataHolder from scisoftpy.nexus.nxclasses import NXroot import scisoftpy as dnp import logging logger = logging.getLogger(__name__) def determineScannableContainingField(targetFieldname, scannables): for scn in scannables: fieldnames = list(scn.getInputNames()) + list(scn.getExtraNa...
# Standard library from argparse import ArgumentParser # Third party import climate_learn as cl import pytorch_lightning as pl from pytorch_lightning.callbacks import ( EarlyStopping, ModelCheckpoint, RichModelSummary, RichProgressBar, ) from pytorch_lightning.loggers.tensorboard import TensorBoardLogg...
# -*- coding: utf-8 -*- ''' # Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. # # This file was generated and any changes will be overwritten. ''' from __future__ import unicode_literals from ..model.education_cont...
import time from selenium import webdriver from selenium.webdriver.common.keys import Keys #variables gmail gmail = "nahoj1992@gmail.com" contrasena = "dragonball2010" gmailAulavirtual = "jcalderonva@unsa.edu.pe" #"creamos una instancia de chrome hacia el aulavirtual" driver = webdriver.Chrome("C:\Python\Li...
from django.contrib import admin from pelicula.models import Cliente, Genero, Pelicula, Prestamo admin.site.register(Cliente) admin.site.register(Genero) admin.site.register(Pelicula) admin.site.register(Prestamo)
# Generated by Django 2.2.9 on 2020-01-25 15:36 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('humans', '0001_initial'), ] operations = [ migrations.AlterField( model_name='group', ...
#coding: utf-8 from django import forms from UserManagement.models import Person from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() class MyRegistrationForm(form...
import numpy as np from operator import itemgetter from sklearn.svm import LinearSVC from sklearn.model_selection import cross_val_score import csv # training and cross validation with open('data/processed_tfidf/ALLYEARS/SPARSE2016.dat') as f: content = f.readlines() data = [] for line in content: y = int(line...
# 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 th...
from datetime import datetime from ward import test from repository import BookRepository @test('test find by author should return list of books') def _(): books = [ { 'name': 'The Gatuk book', 'author': 'Gatuk' }, { 'name': 'The Human book', ...
import re def read_passports(): passports = [] combo = "" # For sexy oneliner later with open('day04/input') as f: for line in f: if line == '\n': # break between passports passports.append({x.split(':')[0]: x.split(':')[1] for x in c...
"""youtubeの操作を行う""" import json import traceback from datetime import datetime from datetime import timedelta import requests from bs4 import BeautifulSoup def get_video_info(conn, api_key, video_id): """動画情報の取得""" conn_str = '/youtube/v3/videos?id={0}&key={1}&fields=items(id,snippet(channelId,title,categoryI...
import numpy as np from itertools import chain class Lattice: def __init__(self, N, conc): self.matrix_size = N self.spin = np.random.choice([1, -1], p = [conc, 1-conc], size = (N, N)) self.decision_times = [] self.last_changed = np.zeros((N, N)) self.time = 0 self....
import sys import os abs_file_path = os.path.abspath(os.path.dirname(__file__)) sys.path.append(os.path.join(abs_file_path, "..", "..")) # add path import torch import torch.nn as nn import collections from torch.utils.serialization import load_lua from model import SCNN model1 = load_lua('experiments/vgg_SCNN_DULR_w...
from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from blog.models import Post, Comment, BlogUser # Register your models here. class BlogUserInline(admin.StackedInline): model = BlogUser can_delete = False verbose...
from multiprocessing import Process import time def f(name): time.sleep(2) print("hello, {0}".format(name)) if __name__ == '__main__': p = Process(target=f, args=["zys",]) p1 = Process(target=f, args=["zys",]) p.start() p1.start()
""" This script is used for trimming SGS data """ #!/usr/bin/python # -*- coding: <encoding name> -*- import argparse from processores.file_processor import FilePorcessor from processores.cmd_processor import CmdProcessor def fozu(): print(" _ooOoo_ ") print(" ...
from Crypto.Cipher import AES from collections import OrderedDict def pad(data): pad_length = 16 - len(data) % 16 return data + bytearray(pad_length * [pad_length]) def unpad(data): pad_length = data[-1] if pad_length < 16: data = data[:-pad_length] return data def parse(qs): result ...
# -*- coding: utf-8 -*- import scrapy from scrapy import Request from recruitment.items import TongchengItem class TongchengSpider(scrapy.Spider): handle_httpstatus_list = [301, 302] name = 'tongcheng' allowed_domains = ['58.com'] #一期数据爬取 didian_list={'bj','cd','cq','cs','cc','dl','dg','fz'} #...
import matplotlib.pyplot as plt import numpy as np from scipy.interpolate import make_interp_spline as spline U = np.array([0, 0.15, 0.24, 0.3, 0.41, 0.51, 0.6, 0.7, 0.75, 0.76, 0.78]) I = np.array([0, 0, 0, 0, 0, 0.02, 1.9, 13.9, 46.7, 59.1, 98.1]) # U_smooth = np.linspace(U.min(), I.max(), 300) # I_smooth = spline(...
repo = { r"profiles/[\w-]+" : Profile, r"[^/]+" : Category, r"[^/]+/[^/]+" : CatPkg, r"[^/]+/[^/]+/[^_]+" : PkgAtom, } disk = { r"[^/]+" : Category, r"[^/]+/[^/]+" : CatPkg, r"[^/]+/[^/]+/[^_]+" : PkgAtom, class Root(object): def __init__(self,path): self.path = path def __hash__(self): return h...
# coding: utf-8 from django.views.generic import FormView from .classes import Keeper from .forms import PaymentForm from .mixins import AjaxFormMixin from .models import AppUser class HomepageView(AjaxFormMixin, FormView): template_name = 'homepage.html' form_class = PaymentForm @staticmethod def g...
#!/usr/bin/python env # coding: utf-8 from helper.model import DBConnection from config import finance_dict import time """" mysql数据库迁移 """ if __name__ == "__main__": # model = Model() # model.select(select_param=["id", "name", "gender"], where_param={"name = ": "jack", "gender = ": "M"}) # model.order_b...
import os from flask import Flask, render_template app = Flask(__name__) # disable caching app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 @app.route("/") @app.route("/index") def show_image(): image_path = os.sep.join(["static", "co2.png"]) return render_template("index.html", co2_graph_path=image_path)
#!/usr/bin/env python # # test_state.py - # # Author: Paul McCarthy <pauldmccarthy@gmail.com> # import os.path as op from fsl.data.image import Image from fsl.data.vtk import VTKMesh import fsleyes.state as state from fsleyes.views.orthopanel import OrthoPanel from fsleyes.views.histogrampanel import HistogramPan...
import unittest #from django.http import HttpResponse #from django.test.client import RequestFactory from django.test import Client from django.contrib.auth.models import User from pip._vendor.requests import session class MyTestCase(unittest.TestCase): def test_FactoryUserStatus(self): # Running from vi...
# filename : jutil.py # author : Jinho D. Choi # last update: 4/19/2010 import math # Converts 'i' into 'n' binary bits # i: integer # n: number of bits: integer def bits(i, n): return tuple((0,1)[i>>j & 1] for j in range(n-1,-1,-1)) # Returns sublist of 'L' indicated by 't'. # L: list # t: binary tuple def ...
file = open('PersonalData.txt','w') file.write("Sebastian Bętkowski\n") file.write("Uniwersytet Ekonomiczny\n") file.write("Informatyka Stosowana") file.close()
#!/usr/bin/env python # encoding: utf-8 """ Created by Nick DeVeaux on 2014-08-07. to run: python counting_nucleotides.py < dna.txt Sample Dataset AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC Sample Output 20 12 17 21 """ import sys import os import utils import fileinput def nucleiot...
from sys import argv, exit script, sstfile, imgName = argv import matplotlib matplotlib.use('Agg') #import pandas as pd import numpy as np from netCDF4 import Dataset, num2date import datetime #from itertools import compress import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature ...
from django_cron import cronScheduler, Job from ioestu.endofday import * class CheckMail(Job): """ Cron Job that checks the lgr users mailbox and adds any approved senders' attachments to the db """ # run every 300 seconds (5 minutes) run_every = 300 def job(self): backupDatabase() cronScheduler.regist...
s=input() if str(s).isdigit() and str(s).isupper() or str(s).islower(): print("yes") else: print("no")
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2019-07-04 09:52 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main_app', '0008_auto_20190628_1447'), ] operations = [ migrations.AlterFie...
# Bioinformatics # Normalize raw dataset using MEAN or MEDIAN value # Spike-in control normalization # 4/7/2018, Bongsoo Park, Johns Hopkins import operator import numpy as np f = open("raw_data_before_normalization.txt","r") line_cnt = 0 id_list = [] norm_factor_mean = [] norm_factor_median = [] mirna_dataset = {} ...
""" .. module:: verzamelend.tests :platform: Unix :synopsis: .. moduleauthor:: Pedro Salgado <steenzout@ymail.com> """ import os import verzamelend.config import verzamelend.logging import logging import unittest LOGGING_CONFIG_FILE = '%s/tests/logging.conf' % os.curdir PACKAGE_CONFIG_FILE = '%s/tests/ve...
#!/usr/bin/env python """ A simple echo server """ import socket host = '' port = 12345 backlog = 5 size = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(backlog) while 1: client, address = s.accept() amountsent = 0 while True: try: data = client.rec...
from django.urls import path from . import views app_name = 'my_admin' urlpatterns = [ path('/index', views.index, name='index'), path('/manage', views.ManageUser, name='manage'), path('<int:id>/info', views.Info, name='info'), path('<int:id>/change', views.Change, name='change'), path('/saveinfo...
import numpy as np import struct import sys import pdb np.set_printoptions(threshold=np.inf) import scipy.misc caffe_root = '/home/mjhuria/caffe/' # this file is expected to be in {caffe_root}/examples sys.path.insert(0, caffe_root + 'python') import caffe import matplotlib.pyplot as plt # %matplotlib inline caffe.set...
import os import platform import hashlib def clear(): return os.system('cls') if(platform.system() == "Windows") else os.system('clear') def hashmd5(password): return hashlib.md5(password.encode('utf-8')).hexdigest()
import math import os from random import randint from collections import deque import pygame from pygame.locals import * # Constants fps = 60 # frequency rate Animation_speed = 0.2 # horizontal flying speed window_width = 284*2 # the width of the window window_height = 512 # the height of the...