text
stringlengths
8
6.05M
#!/usr/bin/python """ This is environment module for Alfr3d """ # Copyright (c) 2010-2014 LiTtl3.1 Industries (LiTtl3.1). # All rights reserved. # This source code and any compilation or derivative thereof is the # proprietary information of LiTtl3.1 Industries and is # confidential in nature. # Use of this source co...
#!/usr/bin/env python import os import json import pprint as pp import math import torch from torch import nn, optim import torch.nn.functional as F import numpy as np from options import get_options from reinforce_baselines import NoBaseline from problems.tsp.problem_tsp import TSP as problem from train import trai...
import random import pygame _songs = ['./sound-files/lied.mp3', './sound-files/lied2.mp3'] def play_song(_song_file_name): pygame.mixer.music.load(_song_file_name) pygame.mixer.music.set_volume(0.2) print('Song playing:' + _song_file_name) pygame.mixer.music.play(0) # -1 plays song for ever def st...
#!/usr/bin/env python import dsx import soclib def _cluster(arch, no, ncpu, nram, icache_lines, icache_words, dcache_lines, dcache_words): crossbar = arch.create('caba:vci_local_crossbar', 'lc%d'%no) for i in range(ncpu): cn = arch.cpu_num arch.cpu_num ...
## This file is part of Invenio for the HGF collaboration. ## ## Create_PersistentID.py provides functions for registering ## Persistent-IDs, currently only Handles. ## ## ## CDS Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by t...
from models.hero.hero import Hero
import cv2 import numpy as np from config import Config from exception import ValueValidException class DataAugment(object): def __init__(self, augment=True, horizontal_flip=False, vertical_flip=False, rotate_angle=False): """ :param image_path: 图片地址 :param gt_boxes: 真实a...
from .deserializer import Deserializer from .serializer import Serializer from .serialization import serializable
#!/usr/bin/python3 #\file list_sub_modules.py #\brief certain python script #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Dec.08, 2022 import torch def ListChildModules(net): def routine(m,indent): for subn,subm in m.named_children(): print(' '*indent+subn) #if indent>0...
class Test: a = "attribut de classe" def __init__(self): self.b = "attribut d'objet" if __name__ == "__main__": attribut = Test ( ) print(attribut.b) print(Test.a) # Pour utiliser le(s) attribut(s) de classe, # il est inutile de créer un objet de cette classe puisque l’attribut est une pr...
import matplotlib.pyplot as plt # 可视化函数 # 将每个列车所经历的的时间可视化,方便用户选择更合理的方案 def ke_shi_hua(ks): x = list(ks.keys()) # 取出ks(列车的 code 和 其历时)的 键 并用list将其列表化 y = [] # 建立一个空列表,用来存放 y 值 y_j = list(ks.values()) # 取出 ks 的 值 并将去列表化 for i in range(len(y_j)): # for循环用来对 y 进行赋值 s = i...
def bubbleSort(arr): n = len(arr) for i in range(n-1): for j in range(0, n-i-1): if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] n=int(input('Enter the no. of elements in the list')) arr= [] for x in range(0,n): i=int(input('Enter the elem...
#!/usr/bin/env python import urllib import urllib.request import json from dateutil import parser from datetime import datetime, timezone import datetime import os from flask import Flask from flask import request from flask import make_response # Flask app should start in global layout app = Flask(__name__) @app.r...
import pygame from pygame.draw import * pygame.init() FPS = 30 screen = pygame.display.set_mode((700, 625)) #colors skyorange = (254, 213, 162) skypink = (254, 213, 196) yellow = (252, 238, 33) mountain_orange = (252, 152, 49) mountain_brown = (172, 67, 52) mountain_purple = (48, 16, 38) ground_purple = (179, 134, 14...
#import sys #input = sys.stdin.readline from collections import defaultdict def main(): N = int( input()) A = list( map( int, input().split())) d = defaultdict( int) for a in A: d[a] += 1 ans = 0 for key, value in d.items(): if key > value: ans += value elif k...
favorite_things = ['raindrops on roses', 'whiskers on kittens', 'bright copper kettles', 'warm woolen mittens', 'bright paper packages tied up with string', 'cream colored ponies', 'crisp apple strudels'] slice1 = favorite_things[1:4] slice2 = favorite_things[6:8] #slice list or st...
from random import randint class Move: def __init__(self, name, chance, getDamage, getSpeed, dmgRange): self.name = name self.chance = chance self.getDamage = getDamage self.getSpeed = getSpeed self.dmgRange = dmgRange def miss(self, target, player): print(f'{player.name}\'s {self.name} missed!') pass...
import socket import select import re import errno def main(): host = "127.0.0.1" port = 54581 address = host,port try: listenerSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) listenerSocket.bind((host,port)) listenerSocket.listen(2) except socket.error as err: if err.errno == errno.EADDRIN...
import unittest from conans.test.utils.tools import TestClient, TestServer, TestRequester from conans.test.utils.test_files import hello_source_files, temp_folder,\ hello_conan_files from conans.client.manager import CONANFILE import os from conans.paths import CONAN_MANIFEST, EXPORT_TGZ_NAME, CONANINFO import plat...
#_*_coding:utf-8_*_ # Author:Topaz import time from conf import settings import urllib import urllib.request import urllib.parse # import urllib2 import json import threading from django.http import HttpResponse from plugins import plugin_api class ClientHandle(object): def __init__(self): ...
import time from selenium.common.exceptions import TimeoutException, NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support.expected_conditions import visibility_of_element_located, \ presence_of_all_elements_located from selenium.webdriver.support.wait import WebDriverWa...
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-10-07 14:25 from __future__ import unicode_literals import datetime import django.contrib.postgres.fields.jsonb import django.core.validators from django.db import migrations, models import django.db.models.deletion from django.utils.timezone import utc impo...
import numpy as np import matplotlib.pyplot as plt import os, sys os.system("./mandelbrot" + " " + sys.argv[1] + " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4] + " " + sys.argv[5] + " " + sys.argv[6] + " " + sys.argv[7] + " " + sys.argv[8] + " mandelbrot.txt") mandel = [] with open("mandelbrot.txt", "r") ...
import pandas as pd import numpy as np import os def ecgframe(filename): # Created dataframe from .datfile with open(r'C:\Users\Sarah\Research_data\data\ecg_data\{}'.format(filename), 'r') as f: next(f) df = pd.DataFrame(line.rstrip().split() for line in f) # Assigned Column names ...
from ..models import Blockchain from ..invalidusage import InvalidUsage from flask import Flask, request, session, redirect, url_for, render_template, flash, send_from_directory from flask.json import jsonify from ..models import web3 def get_newest_20_blocks(): return jsonify(Blockchain.get_newest_20_blocks()) def ...
current_json = {} def main(): print_header() do_stuff() print_json() def print_header(): print('|-------------------------|') print('| JSON Commandline Editor |') print('|-------------------------|') def print_json(): for key in current_json: print(key) def do_stuff(): cu...
# coding:utf-8 import time import sched # 被调度触发函数 def event_func(msg): print("Current Time:", time.time(), 'msg:', msg) if __name__ == "__main__": # 初始化sched模块的scheduler类 s = sched.scheduler(time.time, time.sleep) # 调度 while True: s.enter(1, 2, event_func, ("Small event.", )) s.enter(2, 1, event_func, ("...
import csv import json myfile = open("classification_data.csv", 'wb') wr = csv.writer(myfile) csvrow = ["id", "bar", "bulge"] wr.writerow(csvrow) counts = {} with open('barbulge-classifications.csv', 'rb') as f: reader=csv.reader(f) next(reader) for row in reader: subject_id = row[13].split(';')...
from chess.engine import get_all_moves import pytest @pytest.mark.parametrize( "white, moves", [ (True, [(4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (4, 7), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (5, 7)]), (False, [(2, 0), (2, 1), (2, 2...
import requests from bs4 import BeautifulSoup import csv def makeSoup(city, state): city = city.lower().strip() state = state.lower().strip() location = city + '-' + state url = 'https://www.timeanddate.com/weather/usa/' + location + '/hourly' site = requests.get(url) soup = BeautifulSoup(site....
import urllib.request , urllib.error , urllib.parse url = 'enter url here' response = urllib.request.urlopen(url) webcontent = response.read() print(re.sub('<[^<]+?>','',str(webcontent)))
#!/usr/bin/env python3 # basic_functions.py def multiply (num1, num2): return num1 * num2 x = multiply(5,10) print ("The value of x is {}".format(x)) def hello_name(name): if not name : print("Hello, you!") else: print("Hello," + name + "!") hello_name("") hello_name("Akbar") numbers...
import imaplib, email import os class FetchMail(): con = None error = None def __init__(self, mail_server, username, password): self.con = imaplib.IMAP4_SSL(mail_server) self.con.login(username, password) self.con.select(readonly=False) def close_connection(self): """ ...
from math import floor def mergework(A, p, q, r): n1 = q - p n2 = r - q L = [None] * (n1 + 1) R = [None] * (n2 + 1) for i in range(n1): L[i] = A[p + i] for j in range(n2): R[j] = A[q + j] L[n1] = 999999999999999 R[n2] = 999999999999999 i = 0 j = 0 for k in ran...
# -*- coding: utf-8 -*- import scrapy import json class DoorhasSpider(scrapy.Spider): name = 'doorhas' allowed_domains = ['www.baidu.com'] # with open('C:\\Users\\Administrator\\Desktop\\city.txt', 'r', encoding='gbk')as f: # data = f.read() # citys = data.split(',') # # start_urls = [ ...
# Written in Python 3 import json import os # Get the current directory cwd = os.getcwd() # Get the sample csv file in 'samples' folder jsonFileDir = os.path.join(cwd, 'samples/sample-json.json') # Open the JSON file and pretty print it with open(jsonFileDir) as jsonFile: jsonDict = json.load(jsonFile) print...
import lxml.etree as ET def findRegion(lookupList, city, country): return lookupList.setdefault((city, country), "UNKNOWN") def buildRegionLooupDict(): lookupDict = {} for _, entry in ET.iterparse('xml/cityindex.xml', tag='entry'): city = entry.find('./city').text country = entry....
import os prosite_res = [x.strip('\n') for x in open('prosite_c2h2.results', 'r').readlines()] # Hits for PS50157 (ZINC_FINGER_C2H2_2) [PROSITE (release 20.128)] motif on all UniProtKB/Swiss-Prot # (release 2016_07 of 06-Jul-16: 551705 entries) database sequences : files = ['outputs/CoMET.search/' + f for f in os.li...
#!/usr/bin/env python # -*- coding: utf-8 -*- import theano from theano import tensor as T #tensor3 =T.Tensortype(broadcastable=(False, False, False),dtype='float32') #x =tensor3() dtype='float32' ndim=1 broadcast = (False,) * ndim name=None x = T.TensorType(dtype, broadcast)(name)
class BaseError(Exception): pass
import datetime import unittest from time import sleep import pytest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.select import Select import sys sys.path.append('..') #from Src.EnvSetup.EnvironmentSetUp import EnvironmentSetup from Src.EnvSetup.cnfgur...
"""Setup at app startup""" import os import sqlalchemy from flask import Flask from yaml import load, Loader import io from flask_mysqldb import MySQL def init_connection_engine(): """ initialize database setup Takes in os variables from environment if on GCP Reads in local variables that will be ignored ...
# Envisage - Ryan Bradshaw TITLE = "Envisage" WIDTH = 1920 HEIGHT = 1080 FPS = 60 FONT_NAME = "arial" HS_File = "highscore.txt" SPRITESHEET = "spritesheet_jumper.png" MY_SPRITESHEET = "my_spritesheet.png" # Colours BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = ...
import numpy as np from numbers import Number from typing import Union from pyrealm import warnings # DESIGN NOTES: DO 18/08/21 # # As originally implemented (still commented below), this module provided a # subclass of numpy.ma.core.MaskedArray. The intention was that a constrained # array becomes a thing that carrie...
from datetime import datetime import socket from django.db import models # Create your models here. def get_now(): return datetime.now().strftime("%Y-%m-%d %H:%M:%S") def get_ip(): return socket.gethostbyname(socket.gethostname()) class UserRegistration(models.Model): displayName = models.CharField(m...
""" ConditionalEBGAN ---------------- Implements conditional variant of the Energy based GAN[1]. Uses an auto-encoder as the adversary structure. Losses: - Generator: L2 (Mean Squared Error) - Autoencoder: L2 (Mean Squared Error) Default optimizer: - torch.optim.Adam Custom parameter: - m: Cut off for...
import sys import os sys.path.append(os.path.abspath("../eran/tf_verify")) sys.path.insert(0, os.path.abspath("../eran/ELINA/python_interface/")) sys.path.insert(0, os.path.abspath("../eran/deepg/code/")) from utils import * import numpy as np from eran import ERAN from read_net_file import * from read_zonotope_file i...
a=input() #input을 이용해 문자열을 입력 받는다. stack=[]# stack 선언 res='' #문자열 선언 for x in a: if x.isalpha(): #isalPha를 이용해 이것이 피연산자인지 알수있게 한다. res+=x #피연산자인 경우에 문자열에 추가해준다. else: if x=='(': #스택내 우선순위가 가장 낮은 것 부터 시작 stack.append(x)# append 해준다 elif x=='*'or x=='/': # 그 다음 우선순위를 ...
import argparse def replace_badchars(sequence): sequence = [x for x in sequence] for i in range(len(sequence)): if sequence[i] not in 'ACGTacgt-': sequence[i] = 'N' return "".join(sequence) parser = argparse.ArgumentParser(description = 'Replaces invalid bases with N \n Usage : remove_bad_chars.py -i input_ma...
def zerocrossings(a): return (a[1:].astype(int) * a[:-1]) <= 0 def next_zerocrossing(zcs, idx): # always late, ie. the *next* zero-crossing return idx + zcs[idx:].argmax()
import matplotlib.pyplot as plt #%% # plot average cross entropy # plt.style.use("ggplot") hidden_units = [5, 20, 50, 100, 200] train = [0.5368527675493823, 0.13284138665486048, 0.053223347968168806, 0.04753874124552824, 0.046427876315143946] test = [0.7015223942295157, 0.5294168576738014, 0.47391693320386075, 0.43430...
from .info import Info def setup(bot): bot.add_cog(Info(bot))
import re tiles = ["#","X","O"] board = [" "] * 9 availableSpaces = [str(num) for num in range(1,10)] def displayBoard(): print("Available Moves\t\tCurrent Board") print("|-----|-----|-----|\t|-----|-----|-----|") print("| {} | {} | {} |\t| {} | {} | {} |".format(availableSpaces[0],availableSp...
"""Main window of the app. Author: Randy Paredis Date: 03/12/2020 """ from PyQt5 import QtWidgets, QtCore, QtGui, uic import socketserver, datetime, re, os from rfc5424logging import Rfc5424SysLogHandler import logging from main.ServerDialog import ServerDialog from main.Threading import WorkerThread from main.Extr...
import types from yaml.constructor import * from loopdict import * class LoopConstructor(Constructor): def __init__(self): Constructor.__init__(self) def construct_loopdict(self, node): yd = SafeConstructor.construct_mapping(self, node, deep=True) looped = False try: looped = yd['=l...
#!/usr/bin/env python # -*- coding: utf-8 -*- """@package example Python minimum example """ class contohExample(): """Minimum class example """ ## a Global variable example konstanta = 10 def __init__(self): """Minimum init function example """ super(contohExample, self)...
import requests import requests_cache from pandas import read_html, DataFrame import wrcX.core import pandas.io.html as ih import re def _debug(msg): print(msg) NOCACHE=False DEBUG = True if wrcX.core.cachedb is not None: requests_cache.install_cache(wrcX.core.cachedb,old_data_on_error=True,expire_after=N...
from iInvest import db,app from flask import Flask, url_for, redirect, render_template, request from flask_sqlalchemy import SQLAlchemy from wtforms import form, fields, validators import flask_login as login import flask_admin as admin from flask_admin.contrib import sqla from flask_admin import helpers, expose from w...
#!/usr/bin/env python #coding: utf-8 from pyinotify import WatchManager class PicmanSync: def __init__(self): self.watch_manager = WatchManager()
from django.urls import path, include, re_path from .import views urlpatterns = [ path('', views.aboutHome, name='abouthome'), path('codeofconduct/', views.codeOfConduct, name='codeofconduct'), ]
from onegov.wtfs.forms.daily_list import DailyListSelectionForm from onegov.wtfs.forms.invoice import CreateInvoicesForm from onegov.wtfs.forms.municipality import DeleteMunicipalityDatesForm from onegov.wtfs.forms.municipality import ImportMunicipalityDataForm from onegov.wtfs.forms.municipality import MunicipalityFor...
#!/usr/bin/env python # -- encoding: utf-8 -- # # Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U # # This file is part of FI-Core project. # # 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 ...
/Users/rasmuslevinsson/anaconda3/lib/python3.6/operator.py
from enum import Enum class Attributes(Enum): """ Name 0) ID 1) True weapon only False armour only None both 2) Base value """ critical_strike_chance = 0, True, 2 critical_strike_multiplier = 1, True, 3 global_damage_multiplier = 2, False, 1 life_steal = 3, True, 1 ...
from django.shortcuts import render, redirect, get_object_or_404 from .models import Post from django.utils import timezone # Create your views here. def showmain(request): posts = Post.objects.all() return render(request, 'main/mainpage.html', {'posts':posts}) def first(request): return render(request, ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('pmtool', '0009_flowchart_ftype'), ] operations = [ migrations.RemoveField( model_name='activity', na...
#!/usr/bin/env python import os import sys from math import * __current_path = os.path.dirname(__file__) or '.' sys.path.insert(0, os.path.abspath(os.path.join(__current_path, os.path.pardir))) class Kinematics(object): def __init__(self): self.__kineps = 1e-6 def matrix2Euler(self, matrix, euler):...
# -*- coding: utf-8 -*- """Tests for the utils module. MIT License Copyright (c) 2021-2022, Daniel Nagel All rights reserved. """ import os.path import numpy as np import pytest import mosaic # Current directory HERE = os.path.dirname(__file__) TEST_FILE_DIR = os.path.join(HERE, 'test_files') def Xrand(N): "...
import os import numpy as np import matplotlib.pyplot as plt from keras.models import Sequential, Model from keras.layers import Input, Dense, Dropout, Activation, Flatten, merge from keras.layers import Convolution2D, MaxPooling2D, AveragePooling2D from keras.utils import np_utils from keras.constraints import ...
from django.db import models from ckeditor.fields import RichTextField class ModeloBase(models.Model): id = models.AutoField(primary_key = True) estado = models.BooleanField('Estado',default = True) fecha_creacion = models.DateField('Fecha de Creación',auto_now = False, auto_now_add = True) fecha_modi...
# File_name: stop_kinesisanalytics.py # Purpose: Stop emr cluster that are running # Problem: botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: "https://kinesisanalytics.eu-north-1.amazonaws.com/" # Author: Søren Wandrup-Bendixen # Email: soren.wandrup-Bendixen@cybercom.com # Created: ...
import unittest import numpy as np import numpy.testing as npt import sigpy.mri.rf as rf if __name__ == "__main__": unittest.main() class TestSim(unittest.TestCase): def test_abrm(self): # also provides testing of SLR excitation. Check ex profile sim. tb = 8 N = 128 d1 = 0....
''' Python mapping for the CoreServices framework. This module does not contain docstrings for the wrapped code, check Apple's documentation for details on how to use these functions and classes. Note that PyObjC only wrappers the non-deprecated parts of the CoreServices framework. ''' import sys import objc import F...
# comprehension and conditional # a = {x | x E N and x is even number and 1<=x<=10 # expresion,range/enumerate,conditon a = [x ** 2 + x for x in range(1, 11) if x % 2 == 0] print(a)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.views.generic import CreateView from django.core.urlresolvers import reverse_lazy from ..userapp.forms imp...
#!/usr/bin/env python # coding:utf-8 # vi:tabstop=4:shiftwidth=4:expandtab:sts=4 from ..stacked import curr_layer def query_batchsize_fn(curr_layer): return curr_layer.be.bsz curr_batchsize = (query_batchsize_fn, curr_layer, {})
n = 1 sum = 0 while n<=100: if n % 2 == 1: # 奇数 sum += n else: sum += -n n += 1 print(sum) name = ['alex', 'eric', 'rain'] name_str ='_'.join(name) # name_str = '%s_%s_%s'%(name[0], name[1], name[2]) print(name_str) # name_str = '' # for index,val in enumerate(name): # name_str = ...
import numpy as np import ot import matplotlib.pyplot as plt # 2 subjects, each subject has one zone, # uniform noise: (b - a) * random_sample(size) + a # noise is uniformly distributed in the interval [a,b) # gaussian noise: np.random.normal(mu, sigma, size) x_min = [10, 70] x_max = [20, 80] y_min = [5, 40] y_max =...
# Created by Qin_young on 2020/9/20 20:10 # coding = utf-8 import collections # 排序法:总体时间复杂度为 O(n log n) class Solution: def is_anagram(self, s: str, t: str) -> bool: return sorted(s) == sorted(t) # Hash Table 利用python内置模块 class Solution: def is_anagram(self, s: str, t: str) -> bool: return ...
# -*- coding: utf-8 -*- from django import forms from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.forms.formsets import BaseFormSet, DELETION_FIELD_NAME from django.forms.models import inlineformset_factory from django.template.defaultfilters import slugify fro...
#!/usr/bin/python #-*-coding:utf-8-*- from wx import WxAPI import requests import os import time def get_oneday_text(): url = 'http://open.iciba.com/dsapi' resp = requests.get(url) return {'en': resp.json()['content'], 'ch': resp.json()['note'], 'img': resp.json()['picture']} def post_iciba_template_msg()...
#!/usr/bin/env python # Funtion: # Filename: class Person(object): def __init__(self, name, age): self.name = name self.age = age def talk(self): print("person is talking...") # def talk(self, time): # print('--- person is talking at the time', time) class BlackPers...
def findOrder(numCourses, prerequisites): """ :type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int] """ dic = [set() for _ in range(numCourses)] neigh = [set() for _ in range(numCourses)] for x,y in prerequisites: dic[x].add(y) neigh[y].add(x) ...
# Copyright(c) 2014, MessageBird # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the follo...
import pytest import morse @pytest.mark.parametrize('mrs, exp', [ ('.-', 'A'), ('... --- ...', 'SOS'), ('-.- .. -. -.. .-', 'KINDA'), ('... ..- ...', 'SUS') ]) def test_decode(mrs, exp): assert morse.decode(mrs) == exp
def guess_fruit( fruit, basket_type): # def guess_fuit(): is defining a function print(fruit + basket_type) print(fruit + " aint nobodys business and lives in the " + basket_type + " basket") guess_fruit("MANGO", "Weave") # is calling a function
from distutils.core import setup setup(name='tuppence_kernel', version='0.1', py_modules=['tuppence_kernel.kernel', 'tuppence_kernel.install'], )
import model class Customer: customer = model.Customer session = model.loadSession() res = session.query(customer).all() def __init__(self): pass @staticmethod def get_cust_ids(): ids = [] for item in Customer.res: ids.append(item.customer_id) ret...
from .scale_up import make_linear_curve, scale_up_function from .tanh import tanh_based_scaleup
# Facebook is quite keen on pushing their new programming language Hack to all # their offices. They ran a survey to quantify the popularity of the language # and send it to their employees. To promote Hack they have decided to pair # developers which love Hack with the ones who hate it so the fans can convert # th...
import re from base64 import b64encode, b64decode from onegov.core.custom import json from onegov.form import Form from onegov.gis.models import Coordinates from onegov.gis.forms import CoordinatesField def test_coordinates_field(): value = re.compile(r'value="([a-zA-Z0-9=]+)"') # initially the field contai...
""" Provides a trivial likelihood factory function for testing purposes. The likelihood created requires a string parameter named "sacc_file". """ from firecrown.likelihood.likelihood import NamedParameters from . import lkmodule def build_likelihood(params: NamedParameters): """Return a ParameterizedLikelihood o...
from django.shortcuts import render, get_object_or_404, redirect from .models import * from .funcoes import get_itens_context def index(request): context = {} context.update({ 'itens': [1,2,3,4,5] }) return render(request, 'index.html', context) def itens(request, tipo_item): context =...
import sys class TrianglePath(): @staticmethod def solve(triangle): n = len(triangle) for i in xrange(n-1,-1,-1): for j in xrange(n-1,-1,-1): if i < j: triangle[j-1][i] += max(triangle[j][i], triangle[j][i+1]) return triangle[0][0] if __name__ == "__main__": rl = lambda: sys.stdin.readline().rst...
#!/usr/bin/env python import sys import numpy import os import warnings from matplotlib import pyplot as plt import matplotlib.patches as mpatches from matplotlib.collections import PatchCollection import fortranfile from optparse import OptionParser def label(xy, text): y = xy[1] + 15 # shift y-value for label so...
#parse a matix file (up, down, or NC) to get clusters for each condition and negative cluster #write each positive cluster and negative cluster to its own file import sys inp_matrix= open(sys.argv[1], 'r') header = inp_matrix.readline() def all_same(items): return all(x == items[0] for x in items) def get_matrix_d...
dota_heros = ["lifestealer", "juggernaut", "luna"] print len(dota_heros) print dota_heros[0] print dota_heros[1] print dota_heros[2] #you can easily replace items in the list dota_heros[0] = "kunka" print dota_heros dota_heros[-1]= "io" print dota_heros #you can add to the end of an array with .append dota_heros.appe...
import numpy as np from scipy import stats import streamlit as st # # st.title('P value from T test') # # Calculate the t-statistics t_test =st.number_input(" Enter T value : ") # #0.408 # #Degrees of freedom df =st.number_input(" Enter Degrees of Freedom : ") pval=(stats.t.sf((t_test), df)) # print((1...
#!/bin/python import sys import copy import re infile = open(sys.argv[1], "r") class Deck: def __init__(self, player, cards): self.name = player self.cards = cards def drawCard(self): return self.cards.pop(0) def winRound(self, cards): self.cards += cards def cardCo...
#!/bin/python3 s, t = [int(x) for x in input().strip().split(' ')] a, b = [int(x) for x in input().strip().split(' ')] m, n = [int(x) for x in input().strip().split(' ')] def check_on_house(tree, dist, house_start, house_end): drop_location = tree + dist return house_start <= drop_location <= house_end def ...