content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
# Copyright (C) 2021, RTE (http://www.rte-france.com)
# SPDX-License-Identifier: CC-BY-4.0
"""
Script to test Pacemaker module: remove VM
NOTE: If the VM is running it will wait until the machine is stopped.
"""
import time
from vm_manager.helpers.pacemaker import Pacemaker
SLEEP = 1
VM_NAME ... |
from unittest import TestCase
from webauthn.helpers.generate_challenge import generate_challenge
class TestWebAuthnGenerateChallenge(TestCase):
def test_generates_byte_sequence(self) -> None:
output = generate_challenge()
assert type(output) == bytes
assert len(output) == 64
def tes... |
"""Add bio and profile solumns to table users
Revision ID: 556e51cad32e
Revises: b8f9d89a437e
Create Date: 2019-12-01 17:26:12.132109
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '556e51cad32e'
down_revision = 'b8f9d89a437e'
branch_labels = None
depends_on =... |
with open('input.txt', 'r') as f, open('output.txt', 'w') as f2:
cases = int(f.readline())
for i in range(cases):
buf = list(map(int, f.readline().split()))
buf.sort()
for x in buf:
f2.write(str(x) + ' ')
f2.write('\n')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (c) The James Hutton Institute 2017-2019
# (c) University of Strathclyde 2019-2020
# Author: Leighton Pritchard
#
# Contact:
# leighton.pritchard@strath.ac.uk
#
# Leighton Pritchard,
# Strathclyde Institute for Pharmacy and Biomedical Sciences,
# 161 Cathedral Street,
# ... |
from torch import nn
from transformers import AutoModel, AutoTokenizer
import json
from typing import List
import os
import numpy as np
import logging
class Transformers(nn.Module):
"""BERT model to generate token embeddings.
Each token is mapped to an output vector from BERT.
"""
def __init__(self,... |
from MaudeMiner.core.database import db
from MaudeMiner import interactive
from MaudeMiner.querier.results import process_results
def run(args):
interactive.start("sqlite", 2, process_input=process_sql)
def process_sql(text):
# append ';' if the user forgot it
if not text.endswith(";"):
text += ";"
execute_sql... |
from __future__ import print_function, division, absolute_import
from bokeh.io import curdoc
from distributed.bokeh import messages
from distributed.bokeh.components import MemoryUsage
component = MemoryUsage(sizing_mode='stretch_both')
doc = curdoc()
doc.title = "Dask Memory Usage"
doc.add_periodic_callback(lambda... |
#Base libraries
import numpy as np
import logging
#Bokeh Libraries
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, Select
from bokeh.plotting import figure
class Dashboard:
def __init__(self,title,df) :
self._title=title
self._df=df
self._source=ColumnDataSourc... |
from enum import Enum
class Step(Enum):
# La string correspond avec l'enum frontend/src/types/step.ts
WAIT_FOR_ROBOT_READY_STATE = 'CycleNotStarted'
WAIT_FOR_FRONTEND_CYCLE_START = 'CycleReadyInWaitingMode'
MOVE_ROBOT_TO_RESISTANCE_STATION = 'ToResistanceStation'
READ_RESISTANCE = 'ReadResistance'... |
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# TH... |
score = 0
alien_color = 'green'
if alien_color == 'green':
score = score + 5
elif alien_color == 'yellow':
score = score + 10
elif alien_color == 'blue':
score = score + 15
else:
pass
|
# //////////////////////////////////////////////////////////////////////////////////// #
# ////////////////////////////// ## ## ### ## ### ### ///////////////////////////// #
# ////////////////////////////// # # # # # # # # # ///////////////////////////// #
# ////////////////////////////// ## ## # # # # ... |
import pytest
from src import add
def test_add_monkeypatch(monkeypatch):
def mockreturn(x, y):
return 10
# From module add, we wish to patch function "add" with the result from mockreturn
monkeypatch.setattr(add, "add", mockreturn)
result = add.add(1,3)
assert result == 10 |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# -*- coding: utf-8 -*-
import test_utils
DEMO_ID = test_utils.demo_id(__file__)
def test_write_summary():
test_utils.assert_summary_contents_by_demo(DEMO_ID)
def test_part_surfaces_count():
test_utils.assert_part_surfaces_count(DEMO_ID, 'Channel', 4)
def test_cell_count():
test_utils.assert_cell_co... |
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
# Copyright (C) 2012-2019 German Aerospace Center (DLR) and others.
# This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v2.0
# which accompanies this distribution, and is available at
... |
import sys
from typing import Union
# Use typing_extensions for Python < 3.8
if sys.version_info < (3, 8):
from typing_extensions import Literal # noqa
else:
from typing import Literal # noqa
NumberType = Union[float, int]
|
# Init
import os
import re
from route.tool.func import *
# from route import *
for i_data in os.listdir("route"):
f_src = re.search(r"(.+)\.py$", i_data)
f_src = f_src.group(1) if f_src else ""
if not f_src in ('', '__init__'):
try:
exec(
"from route." + f_src + " ... |
from game import game
from util_classes import PlayerStates
class AbstractAction:
pass
class ToDo(AbstractAction):
"""
A list of things to do when a button gets pressed
"""
def __init__(self, actions):
"""
Store the actions to execute later
:param actions: The actions
... |
import requests
import yaml
import sys
import uuid
from datetime import datetime
def printhelp():
print "Usage: flowbster-feeder.sh [file] [url]"
print " file: containing flowbster definition"
print " url : endpoint of a flowbster receiver component"
def parse_arguments():
if len(sys.argv) < 3:
... |
"""Equal opportunity - Protected and unprotected False negative ratio"""
import math
import sys
import numpy
from metrics.utils import calc_fp_fn
from metrics.Metric import Metric
class EqOppo_fn_ratio(Metric):
def __init__(self):
Metric.__init__(self)
self.name = "EqOppo_fn_ratio"
def calc(... |
def write_result_to_csv_file(model, model_name):
import csv
file_name = generate_result_file_name(model_name, 'csv')
with open(file_name, 'w') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['voltage', 'current', 'power'])
for i in range(len(model.voltages)):
w... |
# Generated by Django 2.2.16 on 2020-10-14 13:22
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('promoted', '0008_auto_20200924_1329'),
]
operations = [
migrations.CreateModel(
name='PromotedTheme',
fields=[
... |
"""preprocessing.py
Contains a single function for reading the .npz files from the original
AMASS dataset, preprocessing them and saving into TFRecords files.
This function is intended to process a single sub-dataset at a time,
making it suitable for multiprocessing.
See the "preprocess_amass.py" script for example ... |
"""rackio/dao/auth.py
This module implements Authentication Data Objects Access.
"""
from .core import RackioDAO
import logging
from ..dbmodels import UserRole, User, Authentication
from ..utils import hash_password, verify_password, generate_key
from ..utils import verify_password as check_password
class AuthDAO(R... |
"""Treadmill State REST api.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import flask_restplus as restplus
from flask_restplus import fields, inputs
from treadmill import exc
from treadmill import webutils
... |
from json import dumps
class MessageType(object):
CONNECT = 0
CONNECTACK = 1
SEND = 2
SENDACK = 3
class HeaderType(object):
endOfHeaders = 0
custom = 1
statusCode = 2
statusPhrase = 3
flag = 4
token = 5
class ValueFormat(object):
void =... |
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
def test_calldatacopy(get_contract_from_ir):
ir = ["calldatacopy", 32, 0, ["calldatasize"]]
get_contract_from_ir(ir)
|
from sys import stdin
hashes = dict()
reps = []
def main():
x = stdin.readline().strip()
while len(x) != 0:
a, b = [i for i in x.split()]
n = hashes.get(a, [])
n.append(b)
hashes[a] = n
x = stdin.readline().strip()
for a, b in hashes.items():
assert isinst... |
from __future__ import unicode_literals
import frappe
from frappe.utils import flt, cstr
from frappe.model.mapper import get_mapped_doc
from erpnext.stock.doctype.delivery_note import delivery_note as erpnext_delivery_note
from erpnext.selling.doctype.sales_order import sales_order as erpnext_sales_order
def update_... |
__author__ = 'Polychronis Patapis'
from PyQt4 import QtGui
from core.pco_gui import CameraWidget
import sys
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = QtGui.QMainWindow()
window.setWindowTitle('PCO.PixelFly -ETH Zurich- ')
try:
icon = QtG... |
Class Model(object):
def __init__(self):
pass
|
import torch
from torch import nn
import math
class GraphGather(nn.Module):
r"""The GGNN readout function
"""
def __init__(self, node_features, out_features,
att_depth=2, att_hidden_dim=100, att_dropout_p=0.0,
emb_depth=2, emb_hidden_dim=100, emb_dropout_p=0.0):
... |
def tuner(icm_lr, reward_weighting, normalise_rewards, args):
import argparse
import time
import datetime
import torch
import torch_ac
import tensorboardX
import sys
import numpy as np
import utils
from model import ACModel
from .a2c import A2CAlgo
from torch_ac import PP... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UI.ui'
#
# Created by: PyQt5 UI code generator 5.10
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
Mai... |
"""
E X P E R I M E N T A L
Performs a join between 3 datasets to build a list of higher education
institutions per county.
@author rambabu.posa
"""
import os
import logging
from pyspark.sql import (SparkSession, functions as F)
def get_absolute_file_path(path, filename):
current_dir = os.path.dirname(__fi... |
import logging, pickle
from gensim.models import word2vec
from keras.models import load_model
def train_word2vec(ver):
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG)
sentences = word2vec.LineSentence("Case/doc_clr/merge_/segment/"+ver+".txt")
model... |
from .evaluate_loss import evaluate_loss
from .predict import predict
from .visualize_loss import visualize_loss
__all__ = [evaluate_loss, predict, visualize_loss]
|
import os
from typing import List
from aux import Board, Instruction
PATH = os.path.join(os.path.dirname(__file__), 'input.txt')
with open(PATH) as file_in:
lines: "list[str]" = []
for line in file_in:
l = line.strip('\n')
lines.append(l)
instructions: List[Instruction] = []
for line in lin... |
import os
from collections import Counter
import seq2seq
from keras.optimizers import Adam
from keras.utils import to_categorical
from seq2seq.models import SimpleSeq2Seq, AttentionSeq2Seq
import numpy as np
from dataset.data_pipeline import DataPipeline
from utils import convert_chord_indices_to_embeddings
def ge... |
class Array():
def __init__(self, size=32, init=None):
self._size = size
self._items = [None]*size
def __getitem__(self, index):
return self._items[index]
def __setitem__(self, index, value):
self._items[index] = value
def __len__(self):
return self.... |
import subprocess
import time
import shutil
import os
import fnmatch
import logging
import argparse
default_logger = logging.getLogger(__name__)
"""
Utility class for monitoring the disk usage in a folder and automatically
cleaning up sub folders in case of need. Older sub folders would be cleaned up
first.
You can ... |
# Kokosnuss-Problem
# Beschreibung: 3 Piraten finden einen Haufen Kokosnüsse. In der Nacht steht einer nach dem anderen auf und
# nimmt ein Drittel der Nüsse weg und spendiert einem Affen eine Nuss. Wieviele Nüsse wurden mindestens gesammelt?
for nuts in range(1,10**6,3):
split_1=((nuts-1)/3*2)
split_2=((spl... |
def selectionSort(array):
n = len(array)
for i in range(len(array)):
min_idx = i
min_val = array[i]
for j in range(i,len(array)):
if array[j] < min_val:
min_idx = j
min_val = array[j]
array[i], array[min_idx] = array[min_idx],array[i]
return array
# Driver code
array = [... |
valor = int ( input ('QUANTO VAI SER EXTRAIDO R$'))
money = valor
cont = 0
cedula = 50
while True:
if money >= cedula:
money -= cedula
cont += 1
else:
if cont > 0:
print(f'Total de cedulas de R${cedula} foi de {cont}')
cont = 0
if cedula == 50:
... |
from enum import Enum
from tortoise import fields, models
class LiftStateEnum(str, Enum):
MODE_AGV = "avg"
MODE_EMERGENCY = "emergency"
MODE_FIRE = "fire"
MODE_HUMAN = "human"
MODE_OFFLINE = "offline"
MODE_UNKNOWN = "unknown"
# FIXME: add all lift states
class LiftMotionStateEnum(str, Enum)... |
import re
import random
import string
import logging
from datetime import datetime, timedelta
from dataclasses import dataclass
from api.quotes import QUOTES, TRIGGER_WORDS
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# timeout (in seconds) before re-using the same quote
QUOTE_REUSE_TIMEOUT = 1... |
import rados_deploy.internal.defaults.start as defaults
import rados_deploy.cli.util as _cli_util
from rados_deploy.internal.util.printer import *
'''CLI module to start RADOS-Ceph on a cluster.'''
def subparser(subparsers):
'''Register subparser modules'''
startparser = subparsers.add_parser('start', help='... |
import random
from typing import List
greeting_list: List[str] = [
'{member} We hope you brought some milk 🥛',
'{member} Hopped into the server!',
'{member} Glad to have you here today!',
'We hope you brought some sweets 🍩 {member}',
'Have a pizza slice 🍕 {member}',
'{member} Woooohooo! '
... |
"""Github Token
This is an utility to ease the process of accessing the GitHub API
by allowing a painless creation of application tokens.
Those tokens can be used as just passwords when interating with the API.
A much more secure way than storing an user password.
"""
import enum
import functools
import operator
impo... |
import math
import torch
import torch.nn as nn
from kornia.geometry.subpix import dsnt
from kornia.utils.grid import create_meshgrid
class FineMatching(nn.Module):
"""FineMatching with s2d paradigm."""
def __init__(self):
super().__init__()
def forward(self, feat_f0, feat_f1, data):
""... |
class Map:
def __init__(self, countries, continents):
self._countries = countries
self._continents = continents
def getCountries(self):
return self._countries
def getContinents(self):
return self._continents |
def calculate_hour_angle(ra, LST):
""" Calculate hour angle.
Input: ra as float
LST as float
Output: ha as float
"""
#Compute the hour angle in range [-12,12]
ha = LST - ra
#hour angles larger than 12 should be conv... |
import torch
import torch.nn as nn
def Conv1x1BNReLU(in_channels,out_channels):
return nn.Sequential(
nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1),
nn.BatchNorm2d(out_channels),
nn.ReLU6(inplace=True)
)
def Conv3x3BNReLU(in_chan... |
"""Add a description to api token
Revision ID: 3ffec872dfdf
Revises: 770149d96e24
Create Date: 2017-03-23 11:30:34.827399
"""
# revision identifiers, used by Alembic.
revision = '3ffec872dfdf'
down_revision = '770149d96e24'
from alembic import op
import sqlalchemy as sa
def upgrade():
''' Add the column descr... |
class Line:
def __init__(self, start, end, color=(1.0, 1.0, 1.0), discontinuous=False):
self.start = start
self.end = end
self.color = color
self.discontinuous = discontinuous |
import re
import os
from sklearn.metrics import f1_score, precision_score, recall_score, roc_auc_score, accuracy_score
import numpy as np
import pdb
def parse_text(line):
patternLabel = 'Label:\s+([+,-]?\d+)'
patternScore = 'Score:\s+([+,-]?\d+\.\d+)'
label = int(re.findall(patternLabel, line)[0])
sco... |
from lib_crawling.aws_client.aws_client import define_crawler, get_region, crawl
from lib_crawling.aws_client.aws_client import get_session_for_profile
from lib_crawling.conf_utils.conf_utils import get_profile_name, get_s3_folder_path, get_database_name, get_crawler_name
def main():
profile_name = get_profile_na... |
# External modules
import requests
class APIError(Exception):
"""Class for exceptions"""
def __init__(self, command, message):
self.command = command
self.message = message
class MythicAPI(object):
"""Class abstracting Mythic Beasts' Primary DNS API"""
def __init__(self, domain, pa... |
from typing import Optional, Type, Iterable, Union, BinaryIO, Tuple
from fpipe.exceptions import FileDataException
from fpipe.meta.abstract import FileData, MetaMap, T
from fpipe.meta.stream import Stream
class File:
"""container for all FileData related to a file
"""
def __init__(
self,
... |
from .cross_entropy import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
from .jsd import JsdCrossEntropy
from .asymmetric_loss import AsymmetricLossMultiLabel, AsymmetricLossSingleLabel
from .l2sp import L2SP |
from xlrd import open_workbook
from Essay import Essay
from sklearn import tree
import matplotlib.pyplot as plt
wb = open_workbook('training_set_rel3.xlsx')
essayMasterList = []
#Making essay objects
for sheet in wb.sheets():
numOfRows = sheet.nrows
for row in range(1700):
essayID = (sheet... |
from typing import Type
from tortoise import Model
from tortoise.backends.asyncpg.schema_generator import AsyncpgSchemaGenerator
from tortoise.fields import Field
from aerich.ddl import BaseDDL
class PostgresDDL(BaseDDL):
schema_generator_cls = AsyncpgSchemaGenerator
DIALECT = AsyncpgSchemaGenerator.DIALECT... |
s,t = input().strip().split(' ')
s,t = [int(s),int(t)]
a,b = input().strip().split(' ')
a,b = [int(a),int(b)]
m,n = input().strip().split(' ')
m,n = [int(m),int(n)]
apple = [int(apple_temp) for apple_temp in input().strip().split(' ')]
orange = [int(orange_temp) for orange_temp in input().strip().split(' ')]
print(sum(... |
import sys
sys.path.append("/Applications/VisIt.app/Contents/Resources/2.8.0/darwin-x86_64/lib/site-packages")
import os
import visit
import alpha
filesPath = "aztec.llnl.gov:/g/g14/damewood/scratchd/2014_Trilayer/vasp"
visit.Launch(vdir="/Applications/VisIt.app/Contents/Resources/bin/")
# Volume plot
visit.OpenDatab... |
#!/usr/bin/env python
from pathlib import Path
import re
from typing import List, Optional
import numpy as np
import pandas as pd
import defopt
REGEX = re.compile(r'([0-9]+)\+([0-9]+)\+([0-9]+) \(.*\) ([^\\]*)')
def predict(word, const=-0.021111467468646117, slope=0.00858736952056475):
return const + word * sl... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: model.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf ... |
#from .execute import execute as fit
from .version import version
from .execute import fit
# def fit(d):
# return {
# 'source_points': [[0,0],[0,0]],
# 'saccade_points': [[0,0], [1,1], [2,2], [3,3], [4,4], [5,5]],
# 'target_points': [[5,5],[5,5]],
# }
|
from cli import base
from core import data, container
import shutil
import os
import sys
import tarfile
from docker import Client
from urllib.request import urlretrieve
from cement.core.controller import CementBaseController, expose
class UpdateController(CementBaseController):
class Meta:
label = 'update'... |
# -*- coding: utf-8 -*-
# _ _
# | |__ ___ __| | __ _ ___
# | '_ \ / _ \ / _` |/ _` / __|
# | |_) | (_) | (_| | (_| \__ \
# |_.__/ \___/ \__,_|\__,_|___/
"""
Bodas library
~~~~~~~~~~~~~~~~~~~~~
Bodas is a library written in Python, sitting on top of SymPy, for asymptotic Bode plots.
Basic usage:
... |
"""
PrivacyFlash Pro is licensed under the MIT License
Copyright (c) 2019 Rafael Goldstein, David Baraka, Sarah Jin, Sebastian Zimmeck
"""
"""
privacy_practices.py
================================================================================
privacy_practices.py loads data from the app project to be analyzed.
"""
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import six
from tensorflow.contrib.seq2seq.python.ops import decoder
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework impo... |
""" Implementation of the most-frequent answer (MFA) model which predicts responses based on the
most-frequently selected choice from the available background (training) data.
"""
import collections
import ccobra
import numpy as np
class MFAModel(ccobra.CCobraModel):
def __init__(self, name='MFA'):
sup... |
### File created by preshma
import math
import os
import pickle
import h5py
import matplotlib.pyplot as plt
import numpy as np
from extract_from_aedat import extract_from_aedat
from normalizeImage3Sigma import normalizeImage3Sigma
from subsample import subsample
def ExtractEventsToTimeSurface(
fileID, # l... |
class grader():
def grade():
|
import json
import asyncio
import aiofiles
import imagehash
import os
import sys
from tqdm import tqdm
from concurrent.futures import ThreadPoolExecutor
from skimage import io
from PIL import Image
import pandas as pd
import multiprocessing
hashSize = 8
cpuCount = multiprocessing.cpu_count()
dbPath = sys.argv[1]
outF... |
import os
def get_replace_str():
with open(os.path.join("/home/python/","file-to-be-replaced")) as fp:
return fp.read() % "CONFIG_CONTROLLER_HOST = 10.20.30.40"
def main():
data = get_replace_str()
print 'data:' % data
|
import random
from app import app
from flask import request, Response
jokes = [
'A rabbi, a priest, and a Lutheran minister walk into a bar. The bartender looks up and says, "Is this some kind of joke?"',
'A screwdriver walks into a bar. The bartender says, "Hey, we have a drink named after you!" The Screwdriv... |
import time
class dude():
def __init__(self,brd):
self.x = int(brd.width/2)
self.y = brd.height-2
self.brd = brd
self.jump = 0
def move(self,d):
#self.brd.mat[self.y][self.x] = ' '
if 'r' in d:
if self.right():
d.remove('r')
i... |
#!/usr/bin/python3
class LedStateMessage:
def __init__(self, sense_hat, rotation=0):
self.sense = sense_hat
self.rotation = rotation
pass
def _show_pixel_message(self, pixels):
self.sense.set_pixels(pixels)
self.sense.set_rotation(self.rotation)
pass
def _g... |
OPEN_CHANNELS = "open_channels"
GROUP_CHANNELS = "group_channels"
|
class Solution:
def isMonotonic(self, A):
return all(A[i] <= A[i - 1] for i in range(1, len(A))) or all(A[i] >= A[i - 1] for i in range(1, len(A))) |
import re
UNSAFE_CHARS = re.compile('[\\[\\]\\<\\>+]')
def parse(query: str) -> str:
"""
Remove unsafe characters
https://github.com/redislabs-training/redis-sitesearch/blob/master/sitesearch/query_parser.py
"""
query = query.strip().replace("-*", "*")
query = UNSAFE_CHARS.sub(' ', query)
... |
import tensorflow as tf
import logging
def print_num_of_total_parameters(output_detail=False, output_to_logging=False):
total_parameters = 0
parameters_string = ""
for variable in tf.trainable_variables():
shape = variable.get_shape()
variable_parameters = 1
for dim in shape:
... |
# Script utility functions
#
# Copyright (C) 2014 Intel Corporation
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful... |
# -*- coding: utf-8 -*-
"""Cluster Robust Standard Errors with Two Clusters
Created on Sat Dec 17 08:39:16 2011
Author: Josef Perktold
"""
import numpy as np
from numpy.testing import assert_almost_equal
import statsmodels.api as sm
import statsmodels.stats.sandwich_covariance as sw
#requires Petersen's test_data
... |
import numpy as np
import SSVD
from SSVD.SSVD import SSVD
from ClusterPlot.ClusterPlot import ClusterPlot
lungcancer = pd.read_csv('LungCancerData.txt', sep=' ', header = None)
lungcancer = (np.array(lungcancer)).T
lungcancer.shape
lungcancer = pd.read_csv('LungCancerData.txt', sep=' ', header = None)
lungcancer = (n... |
"""
DualQuaternions operations, interpolation, conversions
Author: Achille Verheye
License: MIT
"""
import numpy as np
from pyquaternion import Quaternion # pyquaternion
import json
class DualQuaternion(object):
"""
dual number representation of quaternions to represent rigid transforms
A quaternion q ... |
# coding: utf-8
from django.shortcuts import render
from django.template import RequestContext
from esperancanordeste.context_processors import enterprise_proc
from esperancanordeste.newsletter.forms import SubscribeForm
def subscribe(request):
context = {}
if request.method == 'POST':
form = Subsc... |
print(102*0.6+225)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-03-28 06:46
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('adventure', '0010_auto_20160327_2227'),
]
operations = [
migrations.AddField... |
from django.shortcuts import render, redirect
from blog.models import Blog
# Create your views here.
def home(request):
blog = Blog.objects.filter(published=True).latest('dateline')
return render(request, 'pages/home.html', {
'menu_context': ('home',),
'blog': blog,
'is_homepage': True,
})
def about... |
"""
An implementation of Gaussian-Process Surrogate Optimisation - a tool for
optimizing large-scale biophysical networks.
Hadida, J., Sotiropoulos, S. N., Abeysuriya, R. G., Woolrich, M. W., & Jbabdi,
S. (2018). Bayesian Optimisation of Large-Scale Biophysical Networks.
NeuroImage, 174, 219-236.
"""
from .gp... |
#!/usr/bin/env python3
import unittest
from acme import Product
from acme_report import generate_products, ADJECTIVES, NOUNS
class AcmeProductTests(unittest.TestCase):
"""Making sure Acme products are the tops!
Tests product price, weight and stealability/explode methods
"""
def test_default_product... |
from datetime import datetime
register_log_file = None
try:
register_log_file = open("data/register_log.txt", "r+")
register = str(datetime.today()) + " || " + "Type the register >> 0"
print(register, file=register_log_file)
register_log_file.close()
except FileNotFoundError:
print("The file was n... |
#Test data module
from src import data
import pytest
import pandas as pd
import tempfile
import numpy as np
import os
ROOT = os.path.dirname(os.path.dirname(data.__file__))
os.environ['KMP_DUPLICATE_LIB_OK']='True'
@pytest.fixture(scope="session")
def config():
#Turn off CHM filtering for the moment
config = ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Userinfo.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import pymysql
from PyQt5.QtWidgets import QMessageBox
class Ui_User(object):
... |
# this is the bot token, gotten from BotFather
TELEGRAM_BOT_TOKEN = "1883132425:AAECYt_yoXGMsemxbzlE2QVraVhz-S9GnN0"
# this is your own telegram ID, which is used to send exception tracebacks
DEVELOPER_CHAT_ID = "1670573144"
# list of telegram IDs for them /stats command is enabled
MAINTAINERS_CHAT_IDS = [1670573144, ] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.