text
stringlengths
8
6.05M
class AbstractBackend: NAME = None SALT = None @classmethod def handle(cls): raise NotImplementedError()
from snakemake.utils import R import sys """ Author: D. Puthier Affiliation: AMU Aim: A simple Snakemake workflow to process paired-end stranded RNA-Seq. Date: Mon Nov 2 14:03:11 CET 2015 Run: snakemake -s Snakefile Latest modification: - todo """ ##-----------------------------------------------## ## A set of f...
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from .db import models from .db.database import engine from .routers import job, employee models.Base.metadata.create_all(bind=engine) app = FastAPI() origins = [ "http://localhost", "http://localhost:3000", ] app.add_middleware(...
#!/usr/bin/env python # -*- coding: utf-8 -*- from textblob.classifiers import NaiveBayesClassifier import pickle import os.path import hashlib from textblob import TextBlob import json DEBUG=True trained_classifier = 'nb.classifier' def loadSet(path, polarity): sentences = [] with open(path) as f: ...
import enum import sre_compile import sys from _typeshed import ReadableBuffer from collections.abc import Callable, Iterator from sre_constants import error as error from typing import Any, AnyStr, Match as Match, Pattern as Pattern, overload from typing_extensions import TypeAlias __all__ = [ "match", "fullm...
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from twit...
x,y=15,45 res=x if x<y esle y print(res)
# # This file is part of LUNA. # # Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com> # SPDX-License-Identifier: BSD-3-Clause """ Simple SoC abstraction for LUNA examples.""" import os import datetime import logging from amaranth import Elaboratable, Module from amaranth_soc ...
"""Postfix relay domains extension forms.""" from django.db.models.signals import pre_save, post_save from modoboa.lib.form_utils import WizardStep from modoboa.transport import forms as tr_forms, models as tr_models class DisableSignals(object): """Context manager to disable signals.""" def __init__(self)...
# parent class for battle options class BattleOptions: def __init__(self, name, fighter, targets): self.name = name self.fighter = fighter self.targets = targets def generate_round_actions(self): return
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django from django.db import models # Create your models here. from django.db.models.base import Model MANAGED = True class ScrapModel(models.Model): name = models.TextField() source = models.CharField(max_length=100, null=False, defaul...
from django import http def test_view(request): return http.HttpResponse()
import pandas as pd from selenium import webdriver driver = webdriver.Firefox(executable_path='C:\\Program Files\\Mozilla Firefox\\geckodriver-v0.29.0-win64\\geckodriver.exe') import json import time team_links = list() for year in range(2008,2021): driver.get(f'https://moneyball.insidesport.co/teams.php?section={...
import math A=int(input("A= ")) B=int(input("B= ")) C=int(input("C= ")) Number_squares=int(int(A/C)*int(B/C)) Unused_part=int(int(A*B)-int(Number_squares*pow(C,2))) print(Number_squares) print(Unused_part)
def result(num): if num < 100: return num cnt = 99 for n in range(100, num+1): digits = [int(digit) for digit in str(n)] if (digits[0] - digits[1]) == (digits[1] - digits[2]): cnt += 1 return cnt N = int(input()) print(result(N))
import util import network from librosa.util import find_files from librosa.core import load,stft import os.path import const as C import numpy as np from pesq import pesq from time import time start = time() PATH_MIR = C.PATH_EVAL audiolist = find_files(PATH_MIR, ext="wav") total_len = 0 gnsdr = gsi...
#! /usr/bin/env python #import pdb #pdb.set_trace() import json import urllib2 import argparse import sys username = '' CLIENT_ID='f9387851ff8001b7abacd24a73fe1044' def get_user_id(username, username_url): """ Get user id from username. """ try: user_obj = urllib2.urlopen(username_url) ...
# Plot Laser Runs from ROOT import * from plotDictionary import sipmDict, pindiodeDict, shuntSipms, shuntPindiodes from ADCConverter import ADCConverter import os import mapping from argparse import ArgumentParser from array import array def plotData(file1, file2, ch, type, runDir, plotDir, shunts): # Batch Mode ...
# References # https://web.archive.org/web/20140115053733/http://cs.bath.ac.uk:80/brown/papers/ijcv2007.pdf # https://github.com/linrl3/Image-Stitching-OpenCV/blob/master/Image_Stitching.py # https://living-sun.com/pt/python/708914-how-do-you-compute-a-homography-given-two-poses-python-opencv-homography.html # https://...
# # -*- coding: utf-8 -*- # Реализуйте программу, которая будет эмулировать работу с пространствами имен. Необходимо реализовать поддержку создания пространств имен и добавление в них переменных. # В данной задаче у каждого пространства имен есть уникальный текстовый идентификатор – его имя. # Вашей программе на вход...
import os from bs4 import BeautifulSoup import datetime from time import sleepimport datetime from selenium import webdriver email = input("Enter email: ") password = input('Enter password: ') month = input('Enter month: ') day = input("Enter day: ") interval = input('Enter time interval: ') clicks = int(month) - date...
from django.db import models # Create your models here. class face(models.Model): name = models.CharField(max_length=100) role = models.CharField(max_length=20) email = models.EmailField() number = models.IntegerField() emp_id = models.TextField(auto_created=True) class gender(models.Model): ...
# I pledge my honor that I have abided by the Stevens Honor System # Ashley Cannon def main(): print("This program generates usernames from a file of names. \n") infilename = input("What files are the names in: ") outfilename = input("Place names in this file: ") infile = open(infilename, "r") outf...
import rpy2 import rpy2.robjects.packages as rpackages utils = rpackages.importr('utils') utils.chooseCRANmirror(ind=1) packnames = ('tuneR', 'seewave', 'fftw', 'caTools', 'randomForest', 'warbleR', 'mice', 'e1071', 'rpart', 'rpart-plot', 'xgboost', 'e1071') from rpy2.robjects.vectors import StrVector names_to_insta...
# -*- coding: utf-8 -*- # Copyright (C) 2017 by # Randy Davila <davilar@uhd.edu> # BSD license. # # Authors: Randy Davila <davilar@uhd.edu> """Function for reading in the conjecture data. """ import pickle __all__ = ['get_conjectures'] def get_conjectures(target, family): """Returns current stored con...
import os import sys import argparse import math import shutil import time import logging from io import open import numpy as np import torch from torch import nn from torch.nn import init from torch.nn.parameter import Parameter import torch.nn.functional as F import torch.optim as optim from utils import get_xt,u...
import socket from threading import Thread s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_ip = "127.0.0.1" port = 4455 s.bind((server_ip,port)) print("Server Is Running On " + server_ip +" "+ str(port)) s.listen(1) conn, addr = s.accept() print("Connected") print(addr) class send(Thread)...
import pytest from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait from pageObjects.checkOutPage import checkOutPage from pageObjects.confirmPage import confirmPage from pageObjects.homePage import HomePage from...
# Generated by Django 3.0.3 on 2020-03-16 16:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main_app', '0013_membre_mail'), ] operations = [ migrations.AlterField( model_name='membre', name='imageProfil', ...
from gomill import sgf # leftoffat: implementing navigation forwards and backward through the game. class Goban: """Represents the go board. Handles stone placement, captures, etc""" # enum values for the board array EMPTY='.' WHITE='w' BLACK='b' SCORE_BLACK='B' SCORE_WHITE='W' SCORE_...
import re import math import collections class LanguageModel: def __init__(self, filenames): self.text = '' for filename in filenames: self.text += LanguageModel.read_file(filename) self.alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p...
"""add three time filed Revision ID: ed535bd21f09 Revises: 0a43e5b16392 Create Date: 2019-12-12 13:44:51.913300 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'ed535bd21f09' down_revision = '0a43e5b16392' branch_labels = None depends_on = None def upgrade():...
from django_filters import rest_framework as filters from mainapp.models import Event class EventFilter(filters.FilterSet): start_date = filters.DateTimeFromToRangeFilter(field_name='start_date') class Meta: model = Event fields = ['start_date']
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import logging from abc import ABCMeta from dataclasses import dataclass from enum import Enum from typing import ClassVar, Iterable, Mapping, Optional,...
import logging as log from pprint import pformat GOT_LOGGER = False def get_logger(): "Helper function to get the logger" global GOT_LOGGER if GOT_LOGGER: return log GOT_LOGGER = True logger = log.getLogger() logger.setLevel(log.DEBUG) ch = log.StreamHandler() ch.setFormatter(l...
import curses import random import time def hud(win, score): win.addstr(1, 1, "Score: " + str(score)) def update_player(win_col, k, player): if k == ord("a") and player[2] >= 1: player[2] -= 1 if k == ord("d") and player[2] <= win_col: player[2] += 1 if k == ord("s"): player[...
import torch from models.faster_rcnn import fasterrcnn_resnet_fpn from models.centernet.ctdet import CenterNetDetect def get_model_faster(name, num_classes, pretrained_path=None): with_mask = name.find('mask') != -1 resnet_backbone = name[name.find('resnet'):name.find('resnet') + 9].strip('_') # 'resnet18'...
import xlrd import sys import os data = xlrd.open_workbook("FormatDatalibsvm.xlsx") table = data.sheet_by_name('FormatDatalibsvm') nrows = table.nrows def init(): os.system('del learn.txt') os.system('del predict.txt') for j in xrange(0, nrows): init() learn = open('learn.txt' ,'w') pre = open...
import re import sys import requests import pandas as pd from bs4 import BeautifulSoup # Create all required lists ranks=[] movie_names=[] links=[] Rating_Values=[] Directors=[] Writers=[] Stars=[] casts=[] Genres=[] Certificate=[] Country=[] Language=[] Release_Date=[] Filming_Locations=[] Budget=[] Opening_Weekend_U...
def count_common_chars(s1, s2): """ Given two strings s1 and s2, counts the number of characters they have in common, i.e. these characters must be equal and appear at the same location in the strings. For example, 'abcd' and 'a123' have one character in common. 'ab' and 'ba' h...
#coding:gb2312 #使用多个文件 def words_num(filename): try: with open(filename) as f: contents = f.read() except FileNotFoundError: """ msg = "Sorry,the file "+filename+" does not exit." print(msg) """ pass #pass语句可以让python什么都不要做 else: words = contents.split() num_words = len(words) print(filen...
#!/usr/bin/env python from __future__ import print_function import tqdm import argparse import os import numpy as np import array import fastjet as fj from pyjetty.mputils import MPBase from pyjetty.mputils import DataIO from heppy.pythiautils import configuration as pyconf import pythia8 import pythiafjext import...
from translate import translate import getdata import requests import json class video(): sockip = ['112.192.179.75:4258', '175.154.44.87:4258', '124.161.43.184:4258', '119.5.176.249:4258', '175.155.50.78:4258', '112.194.178.181:4258', '124.161.212.88:4258', '119.5.179.10:4258', '112.194.178...
import tensorflow as tf input_data = [1, 2, 3, 4, 5] x = tf.placeholder(dtype=tf.float32) y = x * 2 sess = tf.Session() print(sess.run(y, feed_dict={x: input_data})) a = tf.placeholder(dtype=tf.float32) b = tf.placeholder(dtype=tf.float32) z = tf.multiply(a, b) print(sess.run(z, feed_dict={a: [[3, 2], [1, 2]], b: [...
from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('articles.views', url(r'^(?P<slug>[-\w]+)/$', 'detail', name='articles_detail'), )
import numpy as np from ..algo import score_bump def test_score_bump(): x = 0 vals = [0, 0.5, 0.75, 0.875] for i, item in enumerate(vals): assert x == vals[i] x = score_bump(x)
#W.A.P to troll you while(1>0): a=raw_input("Enter your gender(m/f) : ") if a!='m': print "YOU ARE A WASTE" if a=='m': a="males??" print "Did you know that almost half of the world's population are",a print"" print "This means that you are not as unique as y...
# %% # import NLP libraries import spacy from gensim.corpora.dictionary import Dictionary # %% # import utility and data libraries import os import re import pandas as pd import numpy as np # %% # load spacy model nlp = spacy.load("en_core_web_md") # %% # load state of the union texts def load_texts(dir_path): ...
import torch import torchaudio import librosa import csv import ast import warnings from multiprocessing import cpu_count from pathlib import Path from utils.logger import get_logger from utils.ipa_encoder import EOS_ID logger = get_logger('asr.train') warnings.filterwarnings('ignore') class SpeechDataset(torch.util...
import logging logger = logging.getLogger(__name__) import django.forms as forms from crispy_forms.helper import FormHelper from crispy_forms.layout import ( Layout, Fieldset, Submit, Div, HTML, Field, Button ) from models import Project, Category, Version, Entry class ProjectForm(...
try: read_or_write = input("Haluatko lukea vai kirjoittaa vieraskirjaan? (l/k)\n") if read_or_write == "l": # avataan tiedosto file_handle = open("guestbook.txt", "r", encoding='utf-8') # haetaan tiedoston sisältö content = file_handle.read() # tehdään lista, erotetaan ...
import numpy as np import matplotlib.pyplot as plt class BPNN: def __init__(self, nn_shape=[2, 4, 1]): self.W = [] # 权重 self.B = [] # 阈值 ...
from pandas import * from ggplot import * import pprint import datetime import itertools import operator import brewer2mpl import ggplot as gg import matplotlib.pyplot as plt import numpy as np import pandas as pd import pylab import scipy.stats import statsmodels.api as sm #%matplotlib inline #ggp...
class Solution: def rob(self, nums: List[int]) -> int: """ https://leetcode.com/problems/house-robber/ """ dp = [0 for i in range(len(nums))] dp[0] = nums[0] for i in range(1, len(nums)): dp[i] = max(dp[i-1], dp[i-2]+nums[i]) return dp[-1]
# Generated by Django 2.0.5 on 2018-06-04 08:14 import django.core.validators from django.db import migrations, models import django.db.models.deletion import re class Migration(migrations.Migration): dependencies = [ ('calculation', '0012_auto_20180604_0807'), ] operations = [ migratio...
from django.contrib import admin from TestModel.models import myDevice, Task # Register your models here. admin.site.site_header = 'WELLCOME' admin.site.site_title = 'WELLCOME' class devicesDisplay(admin.ModelAdmin): list_display = ('host_name', 'tag') # list class tasksDisplay(admin.ModelAdmin): list_displa...
__author__ = 'luca' from PyQt4.QtCore import * from PyQt4.QtGui import QPixmap class QAnalyzedFramesTimelineListModel(QAbstractListModel): def __init__(self, video, discared_frames): self.video = video self._discared_frames = discared_frames self.pixmaps = {} super(QAnalyzedFramesT...
num_set = {1, 2, 3, 4, 5} print(1 in num_set) print(8 in num_set)
import random def read_words(filename='20k.txt'): ''' Read file of most popular english words''' with open(filename) as words_file: words = words_file.read() words = [word for word in words.split('\n') if len(word) > 5] return words def choose_random_word(words): ...
def get_next(pattern): ''' KMP算法的next数组的求法 ''' next = [] m, k, j = len(pattern), -1, 0 next[0] = -1 while j < m-1: if k == -1 or pattern[j] == pattern[k]: k += 1 j += 1 next[j] = k else: k = next[k]
from django.db import models from django.urls import path class TableField(models.Model): model_id = models.IntegerField(primary_key=True, verbose_name='Порядковый номер') name = models.CharField(max_length=64, verbose_name='Имя') width = models.IntegerField(verbose_name='Ширина') class CsvPath(models.M...
from django.urls import path from .views import * urlpatterns = [ path('messages/', list_of_messages, name='list_of_messages'), path('messages/update/<int:pk>/', update_message, name='update_message'), path('messages/updated_messages/', updated_messages, name='updated_messages'), path('cancel_update_me...
from torch.utils.data import Dataset, DataLoader import numpy as np import json from transformers import BertTokenizer class myDataset(Dataset): # x: 输入的句子序列 y:情感分类结果 mask:mask矩阵 def __init__(self, x, y, mask): super(myDataset, self).__init__() self.sample_num = x.shape[0] self.x = x ...
def main(): print("This is the ops.py file.") list = [] list = [1,2,3,4,5,6,7,8,9,10] print("list = {}".format(list)) print("list[0] = {}".format(list[0])) print("list[1] = {}".format(list[1])) print("list[9] = {}".format(list[9])) print("list[0:5] = {}".format(list[0:5])) #list =...
''' Created on 1 abr. 2020 REVISTAS @author: goyo ''' from PyQt5 import QtCore, QtGui, QtWidgets from ventanas import ventana_list_revistas, ventana_listado_revistas, ventana_menu_revistas, ventana_principal, ventana_registro_revistas , ventana_editar_revistas from modulo.clases i...
from django.contrib import messages from django.contrib.auth import logout, authenticate, login from django.contrib.auth.forms import UserCreationForm from django.shortcuts import redirect, render from django.urls import reverse from django.views.generic import ListView, CreateView, UpdateView, DeleteView from notes.f...
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def findTarget(self, root, k): """ :type root: TreeNode :type k: int :rtype: bool """ ...
#!/home/boyuanli/tools/anaconda2/envs/python35/bin/python # -*- coding: utf-8 -*- """ Created on Fri Jan 25 16:34:27 2019 @author: lbybyl this file is used to find most max 50 bp window; so the stastic to find sig promoter and stastic the paused sig for the 50bp windows, you should used R, becaused R more convenie...
# -*- coding: utf-8 -*- from .plugin import SauceLabs import os, ssl if (not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None)): ssl._create_default_https_context = ssl._create_unverified_context __all__ = ["SauceLabs"]
#*_* coding=utf8 *_* #!/usr/bin/env python backend_list = [("9pk.118sh.com", "113.105.175.243")] BACKEND_DICT = dict() AccessList = map(lambda x:x[0], backend_list) def get_backend(host): return BACKEND_DICT.get(host) def init(): for (host, ip) in backend_list: BACKEND_DICT.setdefault(host, ip) in...
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- from pwn import * context.log_level = 'debug' elf = ELF('callme32') callme_one = elf.symbols['callme_one'] callme_two = elf.symbols['callme_two'] callme_three = elf.symbols['callme_three'] # ROPGadget --binary callme32 pop3ret = 0x080488a9 # pop esi ; pop edi ; pop e...
# import time # user_data = {} # for i in range(10000): # activity = input("Login or Sign up?\n>>").lower() # if activity == 'login': # email = input("Enter your email\n>>") # password = input("Enter your password\n>>") # time.sleep(2) # if email in user_data.keys(): # ...
# -*- coding: utf-8 -*- ############################################################################# # Copyright Vlad Popovici <popovici@bioxlab.org> # # 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 ...
#!/usr/bin/python3 # syntax.py by Bill Weinman [http://bw.org/] # This is an exercise file from Python 3 Essential Training on lynda.com # Copyright 2010 The BearHeart Group, LLC def main(): print("This is the syntax.py file.") #Gives the ability to call the fuction before their defined #Basicly it calls main at ...
import itertools from tqdm import tqdm def play(num_players, last_marble): players = itertools.cycle(range(num_players)) scores = [0 for _ in range(num_players)] current_player = next(players) marbles = [0] current_index = 0 for marble in tqdm(range(1, last_marble + 1)): current_play...
import numpy as np import pandas as pd from matplotlib.ticker import MultipleLocator from mpl_toolkits.mplot3d import Axes3D from sklearn.linear_model import Lasso from sklearn.preprocessing import PolynomialFeatures import matplotlib.pyplot as plt from sklearn.linear_model import Ridge df = pd.read_csv("week3.csv") p...
""" Сложность: 1. Худший случай: O(n^2) - когда нужно расставить элементы по возрастанию, а они расположены по убыванию. O(n^2) даёт итерация по 2 циклам: внешний цикл (сложность которого равна O(n)) мы умножаем на внутренний (он тоже равен O(n)). O(n * n) = O(n^2) 2. Лучший случай: O(n) - когда все элементы р...
""" Dox Markdown publishing for ACE. """ __help__ = """ Dox is a markdown oriented command line publishing tool for ACE. After installation, dox requires the following initialization: ace dox init --content-type=<content-type> --body-field=<body-field> --key-fie...
import sys import bluetooth uuid = "1e0ca4ea-299d-4335-93eb-27fcfe7fa848" service_matches = bluetooth.find_service(name="aaa", uuid=uuid) if len(service_matches) == 0: print "couldn't find the aaa Service" sys.exit(0) first_match = service_matches[0] port = first_match["port"] name = first_match["name"] host...
from django.db import models class Blacklist(models.Model): TYPE_CHOICES = ( (0, 'Bounce'), (1, 'Complaints'), ) email = models.EmailField(unique=True) type = models.PositiveSmallIntegerField(default=0, choices=TYPE_CHOICES) created_at = models.DateTimeField(auto_now_add=True) ...
from __future__ import absolute_import, unicode_literals from common_services.clients.base import CommonServicesBaseClient from common_services.models.email import RenderedEmail class EmailClient(CommonServicesBaseClient): VERSION = 'v1' def __init__(self): # type: () -> None super(EmailClie...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Date : 2016-11-24 14:22:59 # @Author : Arms (526923945@qq.com) # @Link : https://armszhou.github.io # @Version : $Id$ import sys Zero = [" *** ", " * * ", "* *", "* *", "* *", " * * ", " *** "]...
test_case = int(input()) while test_case: n, m = map(int, input().split()) print(min(2, n - 1) * m) test_case -= 1
class RandomizedCollection: def __init__(self): """ Initialize your data structure here. """ self.ms = [] def insert(self, val: int) -> bool: """ Inserts a value to the collection. Returns true if the collection did not already contain the specified elem...
# CD to DAPPER folder from IPython import get_ipython IP = get_ipython() if IP.magic("pwd").endswith('tutorials'): IP.magic("cd ..") else: assert IP.magic("pwd").endswith("DAPPER") # Load DAPPER from common import * # Load answers from tutorials.resources.answers import answers, show_answer # Load widgets fr...
#solve for x def solve_equation(equation): x, add, num1, equal, num2 = equation.split() num1, num2 = int(num1), int(num2) return "x =" + str(num2 - num1) print(solve_equation("x + 4 = 9"))
import pytest if __name__ == "__main__": pytest.run([__file__])
#coding:utf-8 def script(s, player=None): from NaoQuest.objective import Objective from NaoSensor.plant import Plant import NaoCreator.SGBDDialogue.creer as bd import NaoCreator.Tool.speech_move as sm if not player: print("Error in execution of p...
import time from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait class Ckeditor: def __init__(self, driver: webdriver, wait: WebDriverWait): self.browser = driver self.wait = wait def post(self, css_seletor: str, message: str = 'Enviado usando o Selenium'): ...
alphalist = [letter for letter in 'abcdefghijklmnopqrstuvwxyz'] tonum = dict(zip(alphalist, range(0, 26))) toalpha = dict(zip(range(0, 26), alphalist)) def encrypt(plaintext, key): ciphertext = '' cipherkey = '' plaintext = ''.join(plaintext.lower().split()) for i in range(len(plaintext)): cip...
# Auto generated configuration file # using: # Revision: 1.381.2.13 # Source: /local/reps/CMSSW/CMSSW/Configuration/PyReleaseValidation/python/ConfigBuilder.py,v # with command line options: data -s RAW2DIGI,L1Reco,RECO --eventcontent RECO --conditions auto:com10 -n 500 --no_exec --data --scenario pp --process RERECO i...
print(id("a")) x = "a" print(id(x)) #basically eveything is assigned to a # specific part of memory, which will always change from computer to computer # but doing print(id("")) will point to the memory identiifed on local computer
if __name__ == '__main__': print("Banknotes problem:\n") banknotes_romania = [1, 5, 10, 50, 100, 200, 500] print(banknotes_romania, '\n') from random import randint price = randint(5, 1000) print(f"The price is: {price}\n") from collections import OrderedDict solution...
import numpy as np import matplotlib.pyplot as plt class Bandit: def __init__(self, true_mean): self.true_mean = true_mean self.mean = 0 self.counter = 0 def pull_handle(self): return np.random.rand() + self.id
import array import numpy as np import matplotlib.pyplot as plt import rootpy.ROOT as ROOT from peaks import peaks p=peaks("total.root") speMean=[] speSigma=[] mpeSpeMean=[] spe_mpeRatio=[] mpeMean=[] mpeSigma=[] PE=[] mean_sig2=[] for sn in p.snDict['spe']: meanS=p.fitDict["spe","mean",sn] sigS=p.fitDict["spe...
#!/usr/bin/python3 #minimalist python pe library import sys import argparse import struct import PEHeader class Decoder: def __init__(self,_filename="",_fileperms="rb"): self._header = PEHeader.PEHeader() self.fields = self._header.header_fields self.fmt_dict = self._header.header_fmt_dict self.fmt = "".j...
# Copyright 2018 Cable Television Laboratories, Inc. # # 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...
# -*- coding: utf-8 -*- """ utils.py Utility functions using to analysis and evaluate solutions Function list: timepast memoize clear_cython_cache find_solution generate_catalogue_draft find_keyword_in_solutions @author: Jasper Wu """ import os import functools import shutil import time impo...
import io s = io.StringIO() s.write(u'Hello World\n') print('This is a test', file=s) print s.getvalue() s = io.StringIO(u'Hello World\n') print s.read(4) print s.read() s = io.BytesIO() s.write(b'binary data') print s.getvalue()
import tensorflow as tf tf.set_random_seed(777) w = tf.Variable(tf.random_normal([1]), name='weight') b = tf.Variable(tf.random_normal([1]), name='bias') x = tf.placeholder(tf.float32, shape=[None]) y = tf.placeholder(tf.float32, shape=[None]) hypothesis = x * w + b #cost loss function cost = tf.reduce_mean(tf.squa...