content stringlengths 1 1.04M | input_ids listlengths 1 774k | ratio_char_token float64 0.38 22.9 | token_count int64 1 774k |
|---|---|---|---|
from setuptools import setup, find_packages
setup(
name='fchat',
version='0.0',
packages=find_packages(exclude=['test']),
license='MIT',
description='A python based f-chat client',
long_description=open('README.txt').read(),
install_requires=['requests'],
url='https://github.com',
author='Tucker',
author_email='tucker@example.com'
)
| [
6738,
900,
37623,
10141,
1330,
9058,
11,
1064,
62,
43789,
198,
198,
40406,
7,
198,
220,
220,
220,
1438,
11639,
69,
17006,
3256,
198,
220,
220,
220,
2196,
11639,
15,
13,
15,
3256,
198,
220,
220,
220,
10392,
28,
19796,
62,
43789,
7,
... | 2.666667 | 141 |
# "TOP" means the last-known value of each property of each device.
# One use for this is so that we can set the type of each property explicitly after bulk-uploading to DevicePilot
# NOTE: Any property can occasionally have a value of None (null), from which the type can't be inferred. So we need to explicitly exclude any Nones from our "top"
| [
2,
366,
35222,
1,
1724,
262,
938,
12,
4002,
1988,
286,
1123,
3119,
286,
1123,
3335,
13,
198,
2,
1881,
779,
329,
428,
318,
523,
326,
356,
460,
900,
262,
2099,
286,
1123,
3119,
11777,
706,
11963,
12,
25850,
278,
284,
16232,
47,
2343... | 4.130952 | 84 |
# https://theailearner.com/2018/10/15/creating-video-from-images-using-opencv-python/
# Steps:
# Fetch all the image file names using glob
# Read all the images using cv2.imread()
# Store all the images into a list
# Create a VideoWriter object using cv2.VideoWriter()
# Save the images to video file using cv2.VideoWriter().write()
# Release the VideoWriter and destroy all windows.
# Generate Video from images
import cv2
import numpy as np
import glob
import re
numbers = re.compile(r'(\d+)')
img_array = []
filenames = [filename for filename in glob.glob('./*.png')]
filenames.sort(key=numericalSort)
# sorted(filenames)
for filename in filenames:
print(filename)
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width,height)
img_array.append(img)
out = cv2.VideoWriter('self_supervised_DDAD_384x640.avi',cv2.VideoWriter_fourcc(*'DIVX'), 15, size)
for i in range(len(img_array)):
out.write(img_array[i])
out.release() | [
2,
3740,
1378,
1169,
64,
576,
283,
1008,
13,
785,
14,
7908,
14,
940,
14,
1314,
14,
20123,
278,
12,
15588,
12,
6738,
12,
17566,
12,
3500,
12,
9654,
33967,
12,
29412,
14,
198,
2,
32144,
25,
198,
2,
220,
376,
7569,
477,
262,
2939,
... | 2.743017 | 358 |
import logging
from typing import Iterable
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker as sqlalchemy_sessionmaker
from sqlalchemy.orm.session import Session
logger = logging.getLogger(f"py_reportit.{__name__}")
| [
11748,
18931,
198,
198,
6738,
19720,
1330,
40806,
540,
198,
6738,
44161,
282,
26599,
1330,
2251,
62,
18392,
198,
6738,
44161,
282,
26599,
13,
579,
1330,
6246,
10297,
355,
44161,
282,
26599,
62,
29891,
10297,
198,
6738,
44161,
282,
26599,
... | 3.464789 | 71 |
import torch
import torch.nn.functional as F
from collections import namedtuple
from rlpyt.ul.algos.ul_for_rl.base import BaseUlAlgorithm
from rlpyt.ul.models.ul.vae_models import VaeHeadModel, VaeDecoderModel
from rlpyt.utils.quick_args import save__init__args
from rlpyt.utils.logging import logger
from rlpyt.ul.replays.offline_ul_replay import OfflineUlReplayBuffer
from rlpyt.utils.buffer import buffer_to
from rlpyt.utils.tensor import valid_mean
from rlpyt.ul.models.ul.encoders import DmlabEncoderModelNorm
from rlpyt.ul.models.ul.forward_models import SkipConnectForwardAggModel
from rlpyt.ul.replays.offline_dataset import OfflineDatasets
IGNORE_INDEX = -100 # Mask action samples across episode boundary.
OptInfo = namedtuple("OptInfo", ["reconLoss", "klLoss", "gradNorm"])
ValInfo = namedtuple("ValInfo", ["reconLoss", "klLoss"])
class VAE(BaseUlAlgorithm):
"""VAE to predict o_t+k from o_t."""
opt_info_fields = tuple(f for f in OptInfo._fields) # copy
def named_parameters(self):
"""To allow filtering by name in weight decay."""
yield from self.encoder.named_parameters()
yield from self.forward_agg_rnn.named_parameters()
yield from self.forward_pred_rnn.named_parameters()
yield from self.vae_head.named_parameters()
yield from self.decoder.named_parameters()
| [
11748,
28034,
198,
11748,
28034,
13,
20471,
13,
45124,
355,
376,
198,
6738,
17268,
1330,
3706,
83,
29291,
198,
6738,
374,
75,
9078,
83,
13,
377,
13,
14016,
418,
13,
377,
62,
1640,
62,
45895,
13,
8692,
1330,
7308,
47920,
2348,
42289,
... | 2.754098 | 488 |
from traitlets.config.configurable import LoggingConfigurable
from traitlets import Unicode
__author__ = 'Manfred Minimair <manfred@minimair.org>'
| [
6738,
1291,
2578,
912,
13,
11250,
13,
11250,
11970,
1330,
5972,
2667,
16934,
11970,
198,
6738,
1291,
2578,
912,
1330,
34371,
628,
198,
834,
9800,
834,
796,
705,
5124,
39193,
1855,
320,
958,
1279,
805,
39193,
31,
1084,
320,
958,
13,
23... | 3.282609 | 46 |
print("importing: pytest and platform")
import pytest
import platform
print("importing: sys and os")
import sys, os
sys.path.append(os.path.realpath(os.path.dirname(__file__)+"/.."))
print("importing: numpy")
import numpy as np
print("importing: matplotlib")
import matplotlib
@pytest.mark.mpl_image_compare(baseline_dir='figs_baseline', remove_text=True)
@pytest.mark.mpl_image_compare(baseline_dir='figs_baseline', remove_text=True)
@pytest.mark.mpl_image_compare(baseline_dir='figs_baseline', remove_text=True)
@pytest.mark.mpl_image_compare(baseline_dir='figs_baseline', remove_text=True)
@pytest.mark.mpl_image_compare(baseline_dir='figs_baseline', remove_text=True)
@pytest.mark.mpl_image_compare(baseline_dir='figs_baseline', remove_text=True)
| [
4798,
7203,
11748,
278,
25,
12972,
9288,
290,
3859,
4943,
198,
11748,
12972,
9288,
198,
11748,
3859,
198,
198,
4798,
7203,
11748,
278,
25,
25064,
290,
28686,
4943,
198,
11748,
25064,
11,
28686,
198,
17597,
13,
6978,
13,
33295,
7,
418,
... | 2.608844 | 294 |
# -*- coding: utf-8 -*-
"""
Author: David Wong <davidwong.xc@gmail.com>
License: 3 clause BSD license
"""
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^/?$', 'graphi_main.views.home'),
url(r'^graphing/?$', 'graphi_main.views.graphing'),
url(r'^parsepython/?$', 'graphi_main.views.parsepython'),
url(r'^parsepython-example/?$', 'graphi_main.views.parsepython_example'),
url(r'^about/?$', 'graphi_main.views.about'),
url(r'^contact/?$', 'graphi_main.views.contact'),
url(r'^thanks/?$', 'graphi_main.views.thanks'),
url(r'^hireme/?$', 'graphi_main.views.hire_me'),
url(r'^faq/?$', 'graphi_main.views.faq'),
url(r'^features/?$', 'graphi_main.views.features'),
url(r'^termsofservice/?$', 'graphi_main.views.terms'),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
urlpatterns += staticfiles_urlpatterns()
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
37811,
198,
13838,
25,
3271,
27247,
1279,
67,
8490,
86,
506,
13,
25306,
31,
14816,
13,
785,
29,
198,
34156,
25,
513,
13444,
347,
10305,
5964,
198,
198,
37811,
198,
198... | 2.53 | 500 |
import numpy as np
import matplotlib.pyplot as plt
# RELU函数当input>0: output: x, input < 0, output = 0
x = np.arange(-5.0, 5.0, 0.1)
y1 = sigmoid_function(x)
y2 = step_function(x)
y3 = relu(x)
plt.plot(x, y1, label = "sigmoid")
plt.plot(x, y2, label = "step", linestyle = "--")
plt.plot(x, y3, label = "relu", linestyle = "-")
plt.ylim(-0.1, 5.1)
plt.legend()
plt.show()
| [
11748,
299,
32152,
355,
45941,
198,
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
198,
198,
2,
29749,
52,
49035,
121,
46763,
108,
37605,
241,
15414,
29,
15,
25,
5072,
25,
2124,
11,
5128,
1279,
657,
11,
5072,
796,
657,
198... | 2.010811 | 185 |
import tensorflow as tf
import numpy as np
from dias.model.FPN_Model import Dias_FPN
from dias.model.Unet_Model import Dias_Unet
from dias.dataIO.data import IonoDataManager
import segmentation_models as sm
import matplotlib.pyplot as plt
import os
def train(cfgs):
"""
Function for training DIAS.
"""
print('Setting Model...')
if cfgs['Model']['Type'] == 'Unet' or cfgs['Model']['Type'] == 'naiveUnet':
model = Dias_Unet(cfgs)
elif cfgs['Model']['Type'] == 'FPN':
model = Dias_FPN(cfgs)
dataManager = IonoDataManager(cfgs)
# check data IO
total_step = int(cfgs['Train']['TotalStep'])
# print interval
print_interval = int(cfgs['Train']['PrintInterval'])
# plot interval
plot_inverval = int(cfgs['Train']['PlotInterval'])
# save interval
save_inverval = int(cfgs['Train']['SaveInterval'])
# plot image save directory
img_save_dir = cfgs['Train']['ImgSaveDir']
if os.path.exists(img_save_dir):
pass
else:
os.makedirs(img_save_dir)
# history log directory
hist_log_dir = cfgs['Train']['HistLogDir']
if os.path.exists(hist_log_dir):
pass
else:
os.makedirs(hist_log_dir)
# model save directory
model_save_dir = cfgs['Train']['ModelSaveDir']
if os.path.exists(model_save_dir):
pass
else:
os.makedirs(model_save_dir)
hist_list = list()
print('Start Training')
# start training
for idx in range(total_step):
x_train, y_train = dataManager.get_train_batch()
hist = model.train_on_batch(x=x_train,y=y_train)
hist_list.append(hist)
# Print history information
if idx % print_interval == 0:
print('On Step {}'.format(idx))
print(hist)
# Save image result
if idx % plot_inverval == 0:
x_train, y_train = dataManager.get_train_batch()
y_test = model.predict(x_train)
plt.figure(figsize=(24,8))
plt.subplot(1,3,1)
plt.imshow(x_train[0,:,:,:])
plt.subplot(1,3,2)
plt.imshow(y_train[0,:,:,:])
plt.subplot(1,3,3)
plt.imshow(y_test[0,:,:,:])
plt.savefig(img_save_dir+'STEP_{}.png'.format(idx),dpi=300)
plt.close()
# Save model
if idx % save_inverval == 0:
model.save(model_save_dir+'STEP_{}.model'.format(idx))
np.save(model_save_dir+'hist.npy',hist_list)
return
| [
11748,
11192,
273,
11125,
355,
48700,
198,
11748,
299,
32152,
355,
45941,
198,
6738,
2566,
292,
13,
19849,
13,
5837,
45,
62,
17633,
1330,
360,
4448,
62,
5837,
45,
198,
6738,
2566,
292,
13,
19849,
13,
3118,
316,
62,
17633,
1330,
360,
... | 2.049715 | 1,227 |
from abc import abstractmethod, ABCMeta
from pymarkdownlint.options import IntOption
from bs4 import BeautifulSoup
import markdown
import re
RE_HEADERS = re.compile('^h[1-6]$')
class Rule(object, metaclass=ABCMeta):
""" Class representing markdown rules. """
options_spec = []
id = []
name = ""
error_str = ""
@abstractmethod
class FileRule(Rule):
""" Class representing rules that act on an entire file """
@staticmethod
def md_to_tree(md):
"""
Converts a string of pure markdown into a bs4 object. Makes parsing much
easier, but not necessarily faster.
"""
return BeautifulSoup(markdown.markdown(md), "html.parser")
class LineRule(Rule):
""" Class representing rules that act on a line by line basis """
pass
class HeaderIncrement(FileRule):
"""Rule: Header levels should only increment 1 level at a time."""
name = "header-increment"
id = "MD001"
error_str = "Headers don't increment"
class TopLevelHeader(FileRule):
"""Rule: First header of the file must be h1."""
name = "first-header-h1"
id = "MD002"
options_spec = [IntOption("first-header-level", 1, "Top level header")]
error_str = "First header of the file must be top level header"
class TrailingWhiteSpace(LineRule):
"""Rule: No line may have trailing whitespace."""
name = "trailing-whitespace"
id = "MD009"
error_str = "Line has trailing whitespace"
class HardTab(LineRule):
"""Rule: No line may contain tab (\\t) characters."""
name = "hard-tab"
id = "MD010"
error_str = "Line contains hard tab characters (\\t)"
class MaxLineLengthRule(LineRule):
"""Rule: No line may exceed 80 (default) characters in length."""
name = "max-line-length"
id = "MD013"
options_spec = [IntOption('line-length', 80, "Max line length")]
error_str = "Line exceeds max length ({0}>{1})"
| [
6738,
450,
66,
1330,
12531,
24396,
11,
9738,
48526,
198,
6738,
12972,
4102,
2902,
75,
600,
13,
25811,
1330,
2558,
19722,
198,
6738,
275,
82,
19,
1330,
23762,
50,
10486,
198,
11748,
1317,
2902,
198,
198,
11748,
302,
198,
198,
2200,
62,... | 2.823789 | 681 |
"""GDAX Trading simulator
Usage:
train_lr.py [-zepd <file> -s --stop <stop> -a <after> -b <before> -c <cnt>]
[--err-avg]
train_lr.py (-h | --help)
Options:
-d=FILE Data path [default: /data/gdax/BTC-EUR_27_6_2017_200_days_min.json]
-h --help Show this screen.
-v --version Version
-z --zmq Use ZMQ async send
-e --elastic Use Elasticsearch
-p --debug Debug mode
-s --stop=<stop> Stop time (e.x. 1481416080)
-a --after=<after> After time
-b --before=<before> Before time
-c --cnt=<cnt> Sample count [default: 10000]
--err-avg Compute error of averages
"""
import time
from typing import Dict, List
import numpy as np
import ujson as json
from ct.open_trade import OpenTrade
from ct.product import Product
from ct.time_frame_trade_stats import TimeFrameTradeStats
from docopt import docopt
from simulate_tools import _init_zmq, update_trade_stats, _init_es, \
send_to_es, performance_stats, get_prediction_err, TradeSimulator, \
check_ready, error_average, time_frame_trade_stats_sim, trade
from time_perf import TimePerf
VERSION = "1.0.0"
def trade_volume():
"""
Returns:
int: How much money you want to invest in the trade (EUR)
"""
return 100
if __name__ == "__main__":
main()
| [
37811,
38,
5631,
55,
25469,
35375,
198,
198,
28350,
25,
198,
220,
4512,
62,
14050,
13,
9078,
25915,
89,
538,
67,
1279,
7753,
29,
532,
82,
1377,
11338,
1279,
11338,
29,
532,
64,
1279,
8499,
29,
532,
65,
1279,
19052,
29,
532,
66,
12... | 2.537402 | 508 |
for x in arrayYield():
print(x) | [
198,
1640,
2124,
287,
7177,
56,
1164,
33529,
198,
220,
220,
220,
3601,
7,
87,
8
] | 2.25 | 16 |
import rpxdock as rp, concurrent
if __name__ == '__main__':
main() | [
11748,
374,
8416,
67,
735,
355,
374,
79,
11,
24580,
198,
198,
361,
11593,
3672,
834,
6624,
705,
834,
12417,
834,
10354,
198,
220,
220,
1388,
3419
] | 2.592593 | 27 |
from django import forms
from django.contrib.auth.models import User
from django.db import IntegrityError
from categories.exceptions import ShareContractUserIsOwner, ShareContractAlreadyExists, ShareContractUserDoesNotExist
from categories.models import ShareContract
| [
6738,
42625,
14208,
1330,
5107,
198,
6738,
42625,
14208,
13,
3642,
822,
13,
18439,
13,
27530,
1330,
11787,
198,
6738,
42625,
14208,
13,
9945,
1330,
39348,
12331,
198,
198,
6738,
9376,
13,
1069,
11755,
1330,
8734,
45845,
12982,
3792,
42419... | 4.285714 | 63 |
# Generated by Django 3.2.5 on 2021-08-06 17:22
from django.db import migrations, models
| [
2,
2980,
515,
416,
37770,
513,
13,
17,
13,
20,
319,
33448,
12,
2919,
12,
3312,
1596,
25,
1828,
198,
198,
6738,
42625,
14208,
13,
9945,
1330,
15720,
602,
11,
4981,
628
] | 2.84375 | 32 |
import os
import time
import random
import tkinter
import threading
import subprocess
import glob
from ascii_art import *
from widgets import *
import platform
platform = platform.system()
# thanks to everyone on https://www.asciiart.eu/
class FILE_HANDLER(object):
""" File opening and closing yes"""
# def load_scratch(self, arg=None):
# self.parent.buffer_unplace()
# self.parent.buffer_render_list.insert(self.parent.buffer_render_index, self.buffer_list[0][0])
# self.parent.buffer = self.parent.buffer_render_list[self.parent.buffer_render_index]
# self.parent.buffer.focus_set()
# self.parent.reposition_widgets()
# self.parent.title(f"Nix: <{self.parent.buffer.name}>")
# self.parent.buffer.font_size_set()
# self.parent.theme_load()
# if (arg): return "break"
def save_file(self, arg = None):
""" saves current text into opened file """
if (self.parent.buffer.type != "normal"): self.parent.error(f"{self.parent.buffer.type} buffer") ;return "break"
if (self.parent.buffer.full_name):
size0 = os.path.getsize(self.parent.buffer.full_name)
current_file = open(self.parent.buffer.full_name, "w")
current_file.write(self.parent.buffer.get("1.0", "end-1c"))
current_file.close()
self.parent.buffer.file_start_time = os.stat(self.parent.buffer.full_name).st_mtime
self.parent.buffer.set_highlighter()
size1 = os.path.getsize(self.parent.buffer.full_name)
self.current_dir = os.path.dirname(self.parent.buffer.full_name)
self.parent.title(f"Nix: <{os.path.basename(self.parent.buffer.name)}>")
self.parent.buffer.state_set(pop=["*", "!"])
# self.buffer_tab.change_name(extra_char=" ")
self.parent.notify(rf"saved [{size1-size0}B|{size1}B|{self.parent.buffer.get_line_count()}L] to {self.current_file_name}")
elif (not self.current_file_name):
self.new_file()
self.save_file()
if (arg): return "break"
def save_file_as(self, arg=None, filename=None, new_filename=None):
""" saves current text into a new file """
if (filename): filename = os.path.abspath(f"{self.current_dir}/{filename}")
else: filename = self.parent.buffer.full_name
new_filename = os.path.abspath(f"{self.current_dir}/{new_filename}")
print("saveas: ", new_filename)
os.rename(filename, new_filename)
self.rename_buffer(filename, new_filename)
self.save_file()
self.parent.highlight_chunk()
if (arg): return "break"
def load_file(self, arg=None, filename=None):
""" opens a file and loads it's content into the text widget """
buffer_type = "normal"
# if (filename):
# if (not os.path.isfile(filename)): filename = os.path.abspath(f"{self.current_dir}/{filename}")
# if (self.buffer_exists(filename)): self.load_buffer(buffer_name=filename)
if (not os.path.isfile(filename)):
self.new_file(filename=filename)
return
try:
current_file = open(filename, "r+") #opens the file
except PermissionError:
current_file = open(filename, "r")
buffer_type = "readonly"
t0 = time.time() # timer| gets current time in miliseconds
self.current_dir = os.path.dirname(filename)
try:
file_content = current_file.read()
except Exception:
current_file.close()
self.new_buffer(filename, buffer_type="GRAPHICAL"); return
self.new_buffer(filename, buffer_type=buffer_type)
if (self.parent.conf["backup_files"]):
file = open("."+os.path.basename(filename)+".error_swp", "w+")
file.write(file_content)
file.close()
self.parent.buffer.delete("1.0", "end") #deletes the buffer so there's not any extra text
self.parent.buffer.insert("1.0", file_content) #puts all of the file's text in the text widget
self.parent.buffer.total_chars = len(file_content)+1
self.parent.buffer.total_lines = self.parent.buffer.get_line_count()
# if (platform == "Windows"): self.parent.convert_to_crlf()
# else: self.parent.convert_to_lf()
self.parent.buffer.mark_set("insert", "1.0") #puts the cursor at the start of the file
self.parent.buffer.see("insert")
current_file.close()
self.parent.highlight_chunk() #highlights the text in the text widget
t1 = time.time() # timer| gets current time in miliseconds
elapsed_time = round(t1-t0, 3) #elapsed time
# puts the time it took to load and highlight the text in the command output widget
self.parent.notify(f"total lines: {self.parent.buffer.get_line_count()}; loaded in: {elapsed_time} seconds", tags=[
["1.12", f"1.{13+len(str(self.parent.buffer.get_line_count()))}"],
[f"1.{15+len(str(self.parent.buffer.get_line_count()))+11}", f"1.{15+len(str(self.parent.buffer.get_line_count()))+11+len(str(elapsed_time))}"]
]) # wild...
self.parent.title(f"Nix: <{self.parent.buffer.name}>")
del file_content
if (arg): return "break"
| [
11748,
28686,
198,
11748,
640,
198,
11748,
4738,
198,
11748,
256,
74,
3849,
198,
11748,
4704,
278,
198,
11748,
850,
14681,
198,
11748,
15095,
198,
198,
6738,
355,
979,
72,
62,
433,
1330,
1635,
198,
6738,
40803,
1330,
1635,
198,
198,
1... | 2.594005 | 1,835 |
# The MIT License (MIT)
#
# Copyright © 2021 Fridtjof Gjengset, Adele Zaini, Gaute Holen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the “Software”), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of
# the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from sklearn.model_selection import train_test_split
from random import randint
import numpy as np
from .regression import OLS_solver, scale_Xz, MSE, ridge_reg, lasso_reg
def group_indeces(n, random_groupsize = False, sections = 10):
"""Creates index pairs, sectioning off a range of indexes into smaller groups
Args:
n (int): Length of list to be grouped
random_groupsize (bool): Whether groupsizes are equal or random
Returns:
list: List of pairs (start_index, end_index) for each group
"""
if sections*3 > n:
raise ValueError("n must be at least 3 times greater than the number of sections")
inddex_cutoffs = [0]
if random_groupsize: #Randomly sized groups
while len(inddex_cutoffs) < sections:
new_randint = randint(2,n-2)
if all(x not in inddex_cutoffs for x in [new_randint-1,new_randint,new_randint+1]):
inddex_cutoffs.append(new_randint)
inddex_cutoffs.append(n)
else: #Evenly sized groups
const_group_size = n//sections
for i in range(1,sections-1):
inddex_cutoffs.append(i*const_group_size)
inddex_cutoffs.append(n)
inddex_cutoffs.sort()
#Make index pairs
index_pairs = []
for i in range(len(inddex_cutoffs)-1):
index_pairs.append((inddex_cutoffs[i], inddex_cutoffs[i+1]-1))
return index_pairs
def combine_groups(index_pairs, data):
"""Combines the index pairs into one np.array
Args:
index_pairs (list): List of pairs (start_index, end_index) for each group
data (np.array): data to be indexed and recombined
Returns:
np.array(): combined np.array from the given indexes
"""
#print("Index pairs: ",index_pairs)
#Only one pair "automatically" removes top list layer... >:(
if index_pairs.__class__ is tuple:
index_pairs = [index_pairs]
#print("Input tuple converted to list(tuple): ",index_pairs)
#Get length of combined groups ndarray
len_comb_groups = 0
for pairs in index_pairs:
len_comb_groups+=pairs[1]-pairs[0]+1
#print("Lenght of combined groups: ",len_comb_groups)
if len(data.shape) == 1:
combined_groups = np.ndarray(shape=(len_comb_groups,))
#print("Shape of combined groups: ", combined_groups.shape)
"""if index_pairs[0][0] == 0:
combined_groups[0:index_step+index_interval+1] = data[pairs[0]:pairs[1]+1]
index_step = index_pairs[0][1]-index_pairs[0][0]
"""
index_step = 0
for i in range(len(index_pairs)):
pairs = index_pairs[i]
#print("Pairs: ",pairs)
index_interval = pairs[1]-pairs[0]
combined_groups[index_step:index_step+index_interval+1] = data[pairs[0]:pairs[1]+1]
#print(combined_groups)
index_step+=index_interval+1
elif len(data.shape) == 2:
combined_groups = np.ndarray(shape=(len_comb_groups,data.shape[1]))
index_step = 0
for i in range(len(index_pairs)):
pairs = index_pairs[i]
#print("Pairs: ",pairs)
index_interval = pairs[1]-pairs[0]
for j in range(index_interval+1):
combined_groups[index_step+j,:] = data[pairs[0]+j,:]
#combined_groups[index_step:index_step+index_interval+1,:] = data[pairs[0]:pairs[1]+1,:]
#print(combined_groups)
index_step+=index_interval+1
return combined_groups
def cross_validation(k, designmatrix, datapoints, solver="OLS",random_groupsize = False, lmd=10**(-12)):
"""Divides the dataset into k folds of n groups and peforms cross validation
Args:
k (int): number of folds
n_groups (int): number of groups
designmatrix (np.array(n,m)): The design matrix
datapoints (np.array(n)): datapoints
random_groupsize (bool, optional): Whether group size is even or random. Defaults to False.
Returns:
[type]: [description]
"""
if solver not in ["OLS", "RIDGE", "LASSO"]:
raise ValueError("solver must be OLS, RIDGE OR LASSO")
#Defaults to using 2/10 groups for testing
#Currently only tested for 5 folds, 10 groups
n = len(datapoints)
n_groups = 2*k
index_pairs = group_indeces(n,True, n_groups)
#print("Index pairs: ",index_pairs)
ols_beta_set = []
MSE_train_set = []
MSE_test_set = []
for i in range(0,n_groups-1,2):
test_index_pairs = []
test_index_pairs.append(index_pairs[i])
test_index_pairs.append(index_pairs[i+1])
#print("TEST index pairs: ",test_index_pairs)
train_index_pairs = list(index_pairs)
del train_index_pairs[i]
del train_index_pairs[i]
#print("TRAIN index pairs: ",train_index_pairs)
X_train = combine_groups(train_index_pairs, designmatrix)
X_test = combine_groups(test_index_pairs, designmatrix)
z_train = combine_groups(train_index_pairs, datapoints)
z_test = combine_groups(test_index_pairs, datapoints)
X_train, X_test, z_train, z_test = scale_Xz(X_train, X_test, z_train, z_test)
if solver == "OLS":
ols_beta, z_tilde,z_predict = OLS_solver(X_train, X_test, z_train, z_test)
elif solver == "RIDGE":
ridge_beta_opt, z_tilde, z_predict = ridge_reg(X_train, X_test, z_train, z_test,lmd=lmd)
elif solver == "LASSO":
z_tilde, z_predict = lasso_reg(X_train, X_test, z_train, z_test, lmd=lmd)
MSE_train = MSE(z_train,z_tilde)
MSE_test = MSE(z_test,z_predict)
MSE_train_set.append(MSE_train)
MSE_test_set.append(MSE_test)
#print(ols_beta,MSE_train,MSE_test)
return np.mean(MSE_train_set), np.mean(MSE_test_set)
| [
2,
383,
17168,
13789,
357,
36393,
8,
198,
2,
198,
2,
15069,
10673,
33448,
1305,
312,
83,
73,
1659,
402,
73,
1516,
2617,
11,
1215,
11129,
1168,
391,
72,
11,
12822,
1133,
6479,
268,
198,
2,
198,
2,
2448,
3411,
318,
29376,
7520,
11,
... | 2.344422 | 2,976 |
import sqlite3 | [
11748,
44161,
578,
18
] | 3.5 | 4 |
import urllib2
import json
from celery.decorators import task
from celery.utils.log import get_task_logger
from .models import GroupMember
logger = get_task_logger(__name__)
@task(name='fetch_members_from_group')
@task(name='fetch_facebook_page_fans')
| [
11748,
2956,
297,
571,
17,
198,
11748,
33918,
198,
6738,
18725,
1924,
13,
12501,
273,
2024,
1330,
4876,
198,
6738,
18725,
1924,
13,
26791,
13,
6404,
1330,
651,
62,
35943,
62,
6404,
1362,
198,
6738,
764,
27530,
1330,
4912,
27608,
198,
... | 2.855556 | 90 |
import argparse
import logging
import sys
import uuid
from psycopg2 import connect
QUERY = """
SELECT DISTINCT t.table_schema as schema_name
FROM information_schema.tables t
WHERE t.table_schema NOT IN
('pg_catalog', 'information_schema',
'pg_toast', 'gp_toolkit', 'pg_internal')
ORDER BY t.table_schema;
"""
if __name__ == "__main__":
args = parse_args()
# Enable logging
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
cleanup_metadata({
'database': args.postgresql_database,
'host': args.postgresql_host,
'user': args.postgresql_user,
'pass': args.postgresql_pass
})
| [
11748,
1822,
29572,
198,
11748,
18931,
198,
11748,
25064,
198,
11748,
334,
27112,
198,
198,
6738,
17331,
22163,
70,
17,
1330,
2018,
198,
198,
10917,
19664,
796,
37227,
198,
46506,
220,
360,
8808,
1268,
4177,
256,
13,
11487,
62,
15952,
2... | 2.431655 | 278 |
from nets import neural_net as nn
import matplotlib.pyplot as plt
from operator import itemgetter
from sklearn.metrics import roc_curve, auc, roc_auc_score
from sklearn.model_selection import train_test_split
import numpy as np
"""
# AUTOENCODER
# Instantiate neural network and training classes
NN = nn.Neural_Network(inS=1, outS=1, hS=3, depth = 1, actFunction="sigmoid")
T = nn.trainer(NN, epochs = 400, batch_size = 8, metric = "roc_auc",learningRate="default")
# Ensure that the 8x3x8 encoder problem can be solved by this NN
test_vec = [[0],[0],[0],[0],[0],[0],[1],[0]]
print("Input: ", test_vec)
X = np.array(test_vec, dtype=float)
y = np.array(test_vec, dtype=float)
T.train(X,y)
results = T.prediction
print("Prediction: ", results)
"""
# Function to get kmers of 17 from the negative example file
# Step size = 8 because any shorter and the sequences will share >50% identity...
# not as interesting as new sequences
# Function to convert a DNA sequence into a list in which each element is an
# encoded nucleotide (A,C,T,G->1000,0100,0010,0001)
print(encode('ACTGCT'))
# Read in and encode the positive and negative sequences to train on Rap1 binding
nfile = "seqs/filt-negative.txt"
pfile = "seqs/filt-positive.txt"
# Read in and encode the DNA sequences
with open(pfile, 'r') as pf:
pos_seqs = pf.read().splitlines()
pos_list = []
for seq in pos_seqs:
pos_list.append(encode(seq))
with open(nfile, 'r') as nf:
neg_seqs = nf.read().splitlines()
kmers = []
for long_seq in neg_seqs[0:10]:
neg_kmers = get_kmers(long_seq)
kmers = kmers + neg_kmers
neg_list = []
for seq in kmers:
neg_list.append(encode(seq))
# Combine into X and y, adding a column of ones to X to represent the bias node
x = np.concatenate( (np.asarray(pos_list), np.asarray(neg_list)), axis=0 )
y = [[1] for i in range(0,len(pos_list))] + [[0] for i in range(0,len(neg_list))]
test = np.ones((x.shape[0],1,4))
X = np.hstack((test, x)) #bias node: one for each sample(?)
"""
# Parameter grid search
act_opts = ["sigmoid","ReLU","tanh"]
epoch_opts = np.arange(300,500,50)
batch_opts = np.arange(50,250,25)
metric_opts = ["roc_auc", "mse"]
LR_opts = {"sigmoid": np.arange(.20,.80,.05),\
"ReLU": np.arange(.0002,.0008,.00005),\
"tanh": np.arange(.002,.008,.0005)}
# Test each possible parameter combination
for seed in [1,42,7]:
print("Random seed: ", seed)
# Split the test/train data by random seed
print("Length of first axis: ", len(X[0]))
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=seed, stratify=y)
act_list = list()
epoch_list = list()
batch_list = list()
metric_list = list()
learning_list = list()
score_list = list()
param_comparison = []
for actFunction in act_opts:
print("Activation fucntion: ", actFunction)
for epochs in epoch_opts:
print("Epoch ",epochs)
for batch_size in batch_opts:
for metric in metric_opts:
for learningRate in LR_opts[actFunction]:
# Append parameters to lists
act_list.append(actFunction)
epoch_list.append(epochs)
batch_list.append(batch_size)
metric_list.append(metric)
learning_list.append(learningRate)
# Initialize and train the network
NN = nn.Neural_Network(inS=18, outS=1, hS=3, depth=4, actFunction=actFunction)
T = nn.trainer(NN, epochs, batch_size, metric,learningRate)
T.train(X_train,y_train)
# Now try it on the testing data
T.forward(X_test)
Z = T.yHat
score = roc_auc_score(y_test, Z)
# Save parameter dict and accuracy result in a list of tuples
param_comparison.append(tuple([T.params, score]))
score_list.append(score)
# Print out best parameters and their scores
best = max(param_comparison,key=itemgetter(1))
worst = min(param_comparison, key=itemgetter(1))
print("Best parameters: ", best[0])
print("AUROC score: ", best[1])
print("\nWorst parameters: ", worst[0])
print("AUROC score: ", worst[1])
# Save parameter results to a text file
with open('output/ParameterSearchResults_{}.tsv'.format(seed), 'w') as f:
for i in range(len(act_list)):
value_list = [act_list[i],epoch_list[i],batch_list[i],metric_list[i],learning_list[i],score_list[i]]
f.write("\t".join(str(v) for v in value_list))
f.write("\n")
"""
"""
#SCREW THIS, I'M USING R
# Plot, coloring by parameter of interest
print("Lengths of lists:\n",len(epoch_list))
print("\n",len(act_list))
print("\n",len(score_list))
fig, axs = plt.subplots(1, 3, figsize=(9, 3), sharey=True)
axs[0].scatter(epoch_list, score_list, c=act_list,label=act_list)
axs[1].scatter(epoch_list, score_list, c=metric_list,label=metric_list)
axs[2].scatter(batch_list, score_list, c=act_list, label=act_list)
fig.suptitle('Parameter Grid Search Results')
axs.legend()
axs.grid(True)
fig.savefig("output/ParameterGrid_{}".format(seed))
"""
"""
# RUN FOR IDEAL PARAMETERS
def ideal_run(NN, suff):
T = nn.trainer(NN, epochs=300, batch_size=50, metric='roc_auc',learningRate=0.5)
T.train(X,y)
# Now try it on the testing data
T.forward(X)
Z = T.yHat
lossHistory = T.errorHistory
# Print out the performance given by AUROC
score = roc_auc_score(y, Z)
print("Score of final training: ", score)
# Plot a figure looking at the error over time
plt.plot(lossHistory)
plt.title('Error history')
plt.xlabel('Epoch Number')
plt.ylabel('Error')
plt.savefig("output/LossHistory_{}".format(suff))
return score
# Initialize and train the network for the ideal case
NN = nn.Neural_Network(inS=18, outS=1, hS=3, depth=4, actFunction='sigmoid')
ideal_run(NN, "3Layer")
# Test on different values of hidden layer size
score_list = []
for i in range(1,20):
NN = nn.Neural_Network(inS=18, outS=1, hS=i, depth=4, actFunction='sigmoid')
score_list.append(ideal_run(NN, suff=i))
print(len(score_list))
# create a simple scatterplot to look at this
plt.scatter(range(1,20), score_list)
plt.title('Model score dynamics with respect to changing hiddenLayerSize')
plt.xlabel('Hidden Layer Size')
plt.ylabel('AUROC score')
plt.show()
"""
# OUT-OF-SAMPLE DATA
"""
# Run on the test data, saving out in file with format seq\tscore\n
tfile = "seqs/rap1-lieb-test.txt"
seq_list = []
# Read in and encode the DNA sequences
with open(tfile, 'r') as tf:
seqs = tf.read().splitlines()
pos_list = []
for seq in seqs:
seq_list.append(encode(seq))
# Train the neural net
NN = nn.Neural_Network(inS=18, outS=1, hS=3, depth=4, actFunction='sigmoid')
T = nn.trainer(NN, epochs=300, batch_size=50, metric='roc_auc',learningRate=0.5)
T.train(X,y)
# make a prediction for the data, adding a bias vector
encseqs = np.asarray(seq_list)
bias = np.ones((encseqs.shape[0],1,4))
OOS = np.hstack((bias, encseqs))
T.forward(OOS)
Z = T.yHat
"""
"""
# Print out to file
outfile = 'output/predictions.txt'
with open(outfile,'w') as fh:
for i in range(len(seq_list)):
string = "{}\t{}\n".format(seqs[i],Z[i])
fh.write(string)
"""
| [
6738,
31720,
1330,
17019,
62,
3262,
355,
299,
77,
198,
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
198,
6738,
10088,
1330,
2378,
1136,
353,
198,
6738,
1341,
35720,
13,
4164,
10466,
1330,
686,
66,
62,
22019,
303,
11,
257,
... | 2.30058 | 3,277 |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--file', required=True)
args = parser.parse_args()
file1 = open(f'{args.file}', 'r')
lines = file1.readlines()
Data_Memory={}
#While not end of line
i = 0
j= []
#print(len(lines))
while (i<len(lines)) :
arr = lines[i].split(" ")
aro = arr[0]
# print(arr)
if (aro=="AFC"):
Data_Memory[str(arr[1])]=int(arr[2])
elif(aro=="COP") :
Data_Memory[str(arr[1])]=Data_Memory[str(arr[2])]
elif(aro=="ADD") :
Data_Memory[str(arr[1])]=int(Data_Memory[str(arr[2])])+int(Data_Memory[str(arr[3])])
elif(aro=="MUL"):
Data_Memory[str(arr[1])]=int(Data_Memory[str(arr[2])])*int(Data_Memory[str(arr[3])])
elif(aro=="SOU"):
Data_Memory[str(arr[1])]=int(Data_Memory[str(arr[2])])-int(Data_Memory[str(arr[3])])
elif(aro=="JMP"):
i = int(arr[1])-2
# -1 ++ à la fin
# -1 car les lignes d'instructions sont lue à partir de l'instruction numéro une
elif(aro=="BJ"):
j.append(i)
i = int(arr[1])-2
elif(aro=="JMF"):
if(not(Data_Memory[str(arr[1])])):
i = int(arr[2])-2
# print(i)
#-1 ++
#-1 Première instruction on part de 0
elif(aro=="DIV"):
if (Data_Memory[str(arr[3])]==0):
print("Forbidden Division")
break
else :
Data_Memory[str(arr[1])]=int(int(Data_Memory[str(arr[2])])/int(Data_Memory[str(arr[3])]))
elif(aro=="EQU"):
Data_Memory[str(arr[1])] = (int(Data_Memory[str(arr[2])])==int(Data_Memory[str(arr[3])]))
elif(aro=="INF"):
Data_Memory[str(arr[1])] = (int(Data_Memory[str(arr[2])])<int(Data_Memory[str(arr[3])]))
elif(aro=="SUP"):
Data_Memory[str(arr[1])] = (int(Data_Memory[str(arr[2])])>int(Data_Memory[str(arr[3])]))
elif(aro=="SUPE"):
Data_Memory[str(arr[1])] = (int(Data_Memory[str(arr[2])])>=int(Data_Memory[str(arr[3])]))
elif(aro=="INFE"):
Data_Memory[str(arr[1])] = (int(Data_Memory[str(arr[2])])<=int(Data_Memory[str(arr[3])]))
elif(aro=="PRI"):
print(Data_Memory[str(arr[1])])
elif(aro=="LR"):
i=j.pop()
i+=1
#print(Data_Memory)
file1.close() | [
198,
11748,
1822,
29572,
198,
198,
48610,
796,
1822,
29572,
13,
28100,
1713,
46677,
3419,
198,
198,
48610,
13,
2860,
62,
49140,
10786,
438,
7753,
3256,
2672,
28,
17821,
8,
198,
198,
22046,
796,
30751,
13,
29572,
62,
22046,
3419,
198,
... | 1.731034 | 1,450 |
import networkx as nx
columns = ['discharge_id',
'avg_clust',
'cumulative_experience',
'avg_cumulative_experience',
'team_edge_size',
'team_size']
notes_with_disposition_file = '../data/notes_w_disposition.csv'
discharges_with_disposition_file = '../data/discharges_w_disposition.csv' | [
11748,
3127,
87,
355,
299,
87,
198,
198,
28665,
82,
796,
37250,
6381,
10136,
62,
312,
3256,
198,
220,
220,
220,
220,
220,
220,
220,
705,
615,
70,
62,
565,
436,
3256,
198,
220,
220,
220,
220,
220,
220,
220,
705,
36340,
13628,
62,
... | 2.295775 | 142 |
import json
import yaml
import configparser
from pathlib import Path
| [
11748,
33918,
198,
11748,
331,
43695,
198,
11748,
4566,
48610,
198,
6738,
3108,
8019,
1330,
10644,
198
] | 4.058824 | 17 |
from flask import Flask, render_template
from models.service import Service
import mlab
app = Flask(__name__)
mlab.connect()
@app.route('/')
@app.route('/search/<int:gender>')
if __name__ == '__main__':
app.run(debug=True)
| [
6738,
42903,
1330,
46947,
11,
8543,
62,
28243,
198,
6738,
4981,
13,
15271,
1330,
4809,
198,
11748,
285,
23912,
198,
198,
1324,
796,
46947,
7,
834,
3672,
834,
8,
198,
4029,
397,
13,
8443,
3419,
628,
198,
31,
1324,
13,
38629,
10786,
1... | 2.771084 | 83 |
# Copyright 2020 Google LLC
#
# 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 the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Helper functions for getting mTLS cert and key."""
import json
import logging
from os import path
import re
import subprocess
import six
from google.auth import exceptions
CONTEXT_AWARE_METADATA_PATH = "~/.secureConnect/context_aware_metadata.json"
_CERT_PROVIDER_COMMAND = "cert_provider_command"
_CERT_REGEX = re.compile(
b"-----BEGIN CERTIFICATE-----.+-----END CERTIFICATE-----\r?\n?", re.DOTALL
)
# support various format of key files, e.g.
# "-----BEGIN PRIVATE KEY-----...",
# "-----BEGIN EC PRIVATE KEY-----...",
# "-----BEGIN RSA PRIVATE KEY-----..."
# "-----BEGIN ENCRYPTED PRIVATE KEY-----"
_KEY_REGEX = re.compile(
b"-----BEGIN [A-Z ]*PRIVATE KEY-----.+-----END [A-Z ]*PRIVATE KEY-----\r?\n?",
re.DOTALL,
)
_LOGGER = logging.getLogger(__name__)
_PASSPHRASE_REGEX = re.compile(
b"-----BEGIN PASSPHRASE-----(.+)-----END PASSPHRASE-----", re.DOTALL
)
def _check_dca_metadata_path(metadata_path):
"""Checks for context aware metadata. If it exists, returns the absolute path;
otherwise returns None.
Args:
metadata_path (str): context aware metadata path.
Returns:
str: absolute path if exists and None otherwise.
"""
metadata_path = path.expanduser(metadata_path)
if not path.exists(metadata_path):
_LOGGER.debug("%s is not found, skip client SSL authentication.", metadata_path)
return None
return metadata_path
def _read_dca_metadata_file(metadata_path):
"""Loads context aware metadata from the given path.
Args:
metadata_path (str): context aware metadata path.
Returns:
Dict[str, str]: The metadata.
Raises:
google.auth.exceptions.ClientCertError: If failed to parse metadata as JSON.
"""
try:
with open(metadata_path) as f:
metadata = json.load(f)
except ValueError as caught_exc:
new_exc = exceptions.ClientCertError(caught_exc)
six.raise_from(new_exc, caught_exc)
return metadata
def _run_cert_provider_command(command, expect_encrypted_key=False):
"""Run the provided command, and return client side mTLS cert, key and
passphrase.
Args:
command (List[str]): cert provider command.
expect_encrypted_key (bool): If encrypted private key is expected.
Returns:
Tuple[bytes, bytes, bytes]: client certificate bytes in PEM format, key
bytes in PEM format and passphrase bytes.
Raises:
google.auth.exceptions.ClientCertError: if problems occurs when running
the cert provider command or generating cert, key and passphrase.
"""
try:
process = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
stdout, stderr = process.communicate()
except OSError as caught_exc:
new_exc = exceptions.ClientCertError(caught_exc)
six.raise_from(new_exc, caught_exc)
# Check cert provider command execution error.
if process.returncode != 0:
raise exceptions.ClientCertError(
"Cert provider command returns non-zero status code %s" % process.returncode
)
# Extract certificate (chain), key and passphrase.
cert_match = re.findall(_CERT_REGEX, stdout)
if len(cert_match) != 1:
raise exceptions.ClientCertError("Client SSL certificate is missing or invalid")
key_match = re.findall(_KEY_REGEX, stdout)
if len(key_match) != 1:
raise exceptions.ClientCertError("Client SSL key is missing or invalid")
passphrase_match = re.findall(_PASSPHRASE_REGEX, stdout)
if expect_encrypted_key:
if len(passphrase_match) != 1:
raise exceptions.ClientCertError("Passphrase is missing or invalid")
if b"ENCRYPTED" not in key_match[0]:
raise exceptions.ClientCertError("Encrypted private key is expected")
return cert_match[0], key_match[0], passphrase_match[0].strip()
if b"ENCRYPTED" in key_match[0]:
raise exceptions.ClientCertError("Encrypted private key is not expected")
if len(passphrase_match) > 0:
raise exceptions.ClientCertError("Passphrase is not expected")
return cert_match[0], key_match[0], None
def get_client_ssl_credentials(
generate_encrypted_key=False,
context_aware_metadata_path=CONTEXT_AWARE_METADATA_PATH,
):
"""Returns the client side certificate, private key and passphrase.
Args:
generate_encrypted_key (bool): If set to True, encrypted private key
and passphrase will be generated; otherwise, unencrypted private key
will be generated and passphrase will be None.
context_aware_metadata_path (str): The context_aware_metadata.json file path.
Returns:
Tuple[bool, bytes, bytes, bytes]:
A boolean indicating if cert, key and passphrase are obtained, the
cert bytes and key bytes both in PEM format, and passphrase bytes.
Raises:
google.auth.exceptions.ClientCertError: if problems occurs when getting
the cert, key and passphrase.
"""
metadata_path = _check_dca_metadata_path(context_aware_metadata_path)
if metadata_path:
metadata_json = _read_dca_metadata_file(metadata_path)
if _CERT_PROVIDER_COMMAND not in metadata_json:
raise exceptions.ClientCertError("Cert provider command is not found")
command = metadata_json[_CERT_PROVIDER_COMMAND]
if generate_encrypted_key and "--with_passphrase" not in command:
command.append("--with_passphrase")
# Execute the command.
cert, key, passphrase = _run_cert_provider_command(
command, expect_encrypted_key=generate_encrypted_key
)
return True, cert, key, passphrase
return False, None, None, None
def get_client_cert_and_key(client_cert_callback=None):
"""Returns the client side certificate and private key. The function first
tries to get certificate and key from client_cert_callback; if the callback
is None or doesn't provide certificate and key, the function tries application
default SSL credentials.
Args:
client_cert_callback (Optional[Callable[[], (bytes, bytes)]]): An
optional callback which returns client certificate bytes and private
key bytes both in PEM format.
Returns:
Tuple[bool, bytes, bytes]:
A boolean indicating if cert and key are obtained, the cert bytes
and key bytes both in PEM format.
Raises:
google.auth.exceptions.ClientCertError: if problems occurs when getting
the cert and key.
"""
if client_cert_callback:
cert, key = client_cert_callback()
return True, cert, key
has_cert, cert, key, _ = get_client_ssl_credentials(generate_encrypted_key=False)
return has_cert, cert, key
def decrypt_private_key(key, passphrase):
"""A helper function to decrypt the private key with the given passphrase.
google-auth library doesn't support passphrase protected private key for
mutual TLS channel. This helper function can be used to decrypt the
passphrase protected private key in order to estalish mutual TLS channel.
For example, if you have a function which produces client cert, passphrase
protected private key and passphrase, you can convert it to a client cert
callback function accepted by google-auth::
from google.auth.transport import _mtls_helper
def your_client_cert_function():
return cert, encrypted_key, passphrase
# callback accepted by google-auth for mutual TLS channel.
def client_cert_callback():
cert, encrypted_key, passphrase = your_client_cert_function()
decrypted_key = _mtls_helper.decrypt_private_key(encrypted_key,
passphrase)
return cert, decrypted_key
Args:
key (bytes): The private key bytes in PEM format.
passphrase (bytes): The passphrase bytes.
Returns:
bytes: The decrypted private key in PEM format.
Raises:
ImportError: If pyOpenSSL is not installed.
OpenSSL.crypto.Error: If there is any problem decrypting the private key.
"""
from OpenSSL import crypto
# First convert encrypted_key_bytes to PKey object
pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key, passphrase=passphrase)
# Then dump the decrypted key bytes
return crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)
| [
2,
15069,
12131,
3012,
11419,
198,
2,
198,
2,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
198,
2,
345,
743,
407,
779,
428,
2393,
2845,
287,
11846,
351,
262,
13789,
13,
198,
2,
921,
743,
733... | 2.791398 | 3,255 |
from JumpScale import j
from GitFactory import GitFactory
j.base.loader.makeAvailable(j, 'clients')
j.clients.git = GitFactory()
| [
6738,
15903,
29990,
1330,
474,
198,
6738,
15151,
22810,
1330,
15151,
22810,
198,
198,
73,
13,
8692,
13,
29356,
13,
15883,
10493,
7,
73,
11,
705,
565,
2334,
11537,
198,
73,
13,
565,
2334,
13,
18300,
796,
15151,
22810,
3419,
628
] | 3.195122 | 41 |
from django.conf.urls.defaults import *
urlpatterns = patterns('djangobench_webui.webui.views',
(r'^$', 'results'),
(r'^data/(?P<benchmark>\w+)/$', 'benchmark_data'),
)
| [
6738,
42625,
14208,
13,
10414,
13,
6371,
82,
13,
12286,
82,
1330,
1635,
628,
198,
6371,
33279,
82,
796,
7572,
10786,
28241,
648,
672,
24421,
62,
12384,
9019,
13,
12384,
9019,
13,
33571,
3256,
198,
220,
220,
220,
357,
81,
6,
61,
3,
... | 2.294872 | 78 |
#
# Valuation of European Call Options in BSM Model
# Comparison of Analytical, int_valueegral and FFT Approach
# 11_cal/BSM_option_valuation_FOU.py
#
# (c) Dr. Yves J. Hilpisch
# Derivatives Analytics with Python
#
import numpy as np
from numpy.fft import fft
from scipy.integrate import quad
from scipy import stats
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['font.family'] = 'serif'
#
# Model Parameters
#
S0 = 100.00 # initial index level
K = 100.00 # strike level
T = 1. # call option maturity
r = 0.05 # constant short rate
sigma = 0.2 # constant volatility of diffusion
#
# Valuation by int_valueegration
#
# Analytical Formula
def BSM_call_value(S0, K, T, r, sigma):
''' Valuation of European call option in BSM Model.
--> Analytical Formula.
Parameters
==========
S0: float
initial stock/index level
K: float
strike price
T: float
time-to-maturity (for t=0)
r: float
constant risk-free short rate
sigma: float
volatility factor in diffusion term
Returns
=======
call_value: float
European call option present value
'''
d1 = (np.log(S0 / K) + (r + 0.5 * sigma ** 2) * T) \
/ (sigma * np.sqrt(T))
d2 = (np.log(S0 / K) + (r - 0.5 * sigma ** 2) * T) \
/ (sigma * np.sqrt(T))
BS_C = (S0 * stats.norm.cdf(d1, 0.0, 1.0) -
K * np.exp(-r * T) * stats.norm.cdf(d2, 0.0, 1.0))
return BS_C
#
# Fourier Transform with Numerical int_valueegration
#
def BSM_call_value_INT(S0, K, T, r, sigma):
''' Valuation of European call option in BSM model via Lewis (2001)
--> Fourier-based approach (integral).
Parameters
==========
S0: float
initial stock/index level
K: float
strike price
T: float
time-to-maturity (for t=0)
r: float
constant risk-free short rate
sigma: float
volatility factor in diffusion term
Returns
=======
call_value: float
European call option present value
'''
int_value = quad(lambda u:
BSM_integral_function(u, S0, K, T, r, sigma), 0, 100)[0]
call_value = max(0, S0 - np.exp(-r * T) * np.sqrt(S0 * K) /
np.pi * int_value)
return call_value
def BSM_integral_function(u, S0, K, T, r, sigma):
''' Valuation of European call option in BSM model via Lewis (2001)
--> Fourier-based approach: integral function. '''
cf_value = BSM_characteristic_function(u - 1j * 0.5, 0.0, T, r, sigma)
int_value = 1 / (u ** 2 + 0.25) \
* (np.exp(1j * u * np.log(S0 / K)) * cf_value).real
return int_value
def BSM_characteristic_function(v, x0, T, r, sigma):
''' Valuation of European call option in BSM model via
Lewis (2001) and Carr-Madan (1999)
--> Fourier-based approach: charcteristic function. '''
cf_value = np.exp(((x0 / T + r - 0.5 * sigma ** 2) * 1j * v -
0.5 * sigma ** 2 * v ** 2) * T)
return cf_value
#
# Fourier Transform with FFT
#
def BSM_call_value_FFT(S0, K, T, r, sigma):
''' Valuation of European call option in BSM model via Lewis (2001)
--> Fourier-based approach (integral).
Parameters
==========
S0: float
initial stock/index level
K: float
strike price
T: float
time-to-maturity (for t=0)
r: float
constant risk-free short rate
sigma: float
volatility factor in diffusion term
Returns
=======
call_value: float
European call option present value
'''
k = np.log(K / S0)
x0 = np.log(S0 / S0)
g = 1 # factor to increase accuracy
N = g * 4096
eps = (g * 150.) ** -1
eta = 2 * np.pi / (N * eps)
b = 0.5 * N * eps - k
u = np.arange(1, N + 1, 1)
vo = eta * (u - 1)
# Modificatons to Ensure int_valueegrability
if S0 >= 0.95 * K: # ITM case
alpha = 1.5
v = vo - (alpha + 1) * 1j
modcharFunc = np.exp(-r * T) * (BSM_characteristic_function(
v, x0, T, r, sigma) /
(alpha ** 2 + alpha - vo ** 2 + 1j * (2 * alpha + 1) * vo))
else: # OTM case
alpha = 1.1
v = (vo - 1j * alpha) - 1j
modcharFunc1 = np.exp(-r * T) * (1 / (1 + 1j * (vo - 1j * alpha)) -
np.exp(r * T) / (1j * (vo - 1j * alpha)) -
BSM_characteristic_function(v, x0, T, r, sigma) /
((vo - 1j * alpha) ** 2 -
1j * (vo - 1j * alpha)))
v = (vo + 1j * alpha) - 1j
modcharFunc2 = np.exp(-r * T) * (1 / (1 + 1j * (vo + 1j * alpha))
- np.exp(r * T) /
(1j * (vo + 1j * alpha))
- BSM_characteristic_function(
v, x0, T, r, sigma) /
((vo + 1j * alpha) ** 2 - 1j * (vo + 1j * alpha)))
# Numerical FFT Routine
delt = np.zeros(N, dtype=np.float)
delt[0] = 1
j = np.arange(1, N + 1, 1)
SimpsonW = (3 + (-1) ** j - delt) / 3
if S0 >= 0.95 * K:
FFTFunc = np.exp(1j * b * vo) * modcharFunc * eta * SimpsonW
payoff = (fft(FFTFunc)).real
CallValueM = np.exp(-alpha * k) / np.pi * payoff
else:
FFTFunc = (np.exp(1j * b * vo) *
(modcharFunc1 - modcharFunc2) *
0.5 * eta * SimpsonW)
payoff = (fft(FFTFunc)).real
CallValueM = payoff / (np.sinh(alpha * k) * np.pi)
pos = int((k + b) / eps)
CallValue = CallValueM[pos] * S0
# klist = np.exp((np.arange(0, N, 1) - 1) * eps - b) * S0
return CallValue # , klist[pos - 50:pos + 50]
| [
2,
198,
2,
3254,
2288,
286,
3427,
4889,
18634,
287,
347,
12310,
9104,
198,
2,
34420,
286,
16213,
22869,
11,
493,
62,
8367,
1533,
1373,
290,
376,
9792,
38066,
198,
2,
1367,
62,
9948,
14,
4462,
44,
62,
18076,
62,
2100,
2288,
62,
37,... | 2.064879 | 2,759 |
from ._seam_carving import _seam_carve_v
from .. import util
from .._shared import utils
import numpy as np
def seam_carve(image, energy_map, mode, num, border=1, force_copy=True):
""" Carve vertical or horizontal seams off an image.
Carves out vertical/horizontal seams from an image while using the given
energy map to decide the importance of each pixel.
Parameters
----------
image : (M, N) or (M, N, 3) ndarray
Input image whose seams are to be removed.
energy_map : (M, N) ndarray
The array to decide the importance of each pixel. The higher
the value corresponding to a pixel, the more the algorithm will try
to keep it in the image.
mode : str {'horizontal', 'vertical'}
Indicates whether seams are to be removed vertically or horizontally.
Removing seams horizontally will decrease the height whereas removing
vertically will decrease the width.
num : int
Number of seams are to be removed.
border : int, optional
The number of pixels in the right, left and bottom end of the image
to be excluded from being considered for a seam. This is important as
certain filters just ignore image boundaries and set them to `0`.
By default border is set to `1`.
force_copy : bool, optional
If set, the `image` and `energy_map` are copied before being used by
the method which modifies it in place. Set this to `False` if the
original image and the energy map are no longer needed after
this opetration.
Returns
-------
out : ndarray
The cropped image with the seams removed.
References
----------
.. [1] Shai Avidan and Ariel Shamir
"Seam Carving for Content-Aware Image Resizing"
http://www.cs.jhu.edu/~misha/ReadingSeminar/Papers/Avidan07.pdf
"""
utils.assert_nD(image, (2, 3))
image = util.img_as_float(image, force_copy)
energy_map = util.img_as_float(energy_map, force_copy)
if image.ndim == 2:
image = image[..., np.newaxis]
if mode == 'horizontal':
image = np.transpose(image, (1, 0, 2))
image = np.ascontiguousarray(image)
out = _seam_carve_v(image, energy_map, num, border)
if mode == 'horizontal':
out = np.transpose(out, (1, 0, 2))
return np.squeeze(out)
| [
6738,
47540,
325,
321,
62,
7718,
1075,
1330,
4808,
325,
321,
62,
7718,
303,
62,
85,
198,
6738,
11485,
1330,
7736,
198,
6738,
11485,
62,
28710,
1330,
3384,
4487,
198,
11748,
299,
32152,
355,
45941,
628,
198,
4299,
15787,
62,
7718,
303,... | 2.751163 | 860 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" QiBuild """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import zipfile
from qisys.qixml import etree
def name_from_archive(archive_path):
""" Name From Archive """
archive = zipfile.ZipFile(archive_path, allowZip64=True)
xml_data = archive.read("manifest.xml")
elem = etree.fromstring(xml_data)
return elem.get("uuid")
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
15069,
357,
66,
8,
2321,
12,
1238,
2481,
8297,
28650,
47061,
13,
1439,
2489,
10395,
13,
198,
2,
5765,
286,
428,
... | 2.980676 | 207 |
######################
# Author: Nick Gavalas
# 2/3/2019 fixed by Kimon Moschandreou
######################
import time
import sys
import os
import selenium
from selenium import webdriver
# TODO: Substitute timers with webdriverwaits.
url = sys.argv[1]
projectname = 'deleteme'
tjobname = 'deletethisproject'
tjobimage = 'elastest/ebs-spark'
commands = """
git clone https://github.com/elastest/demo-projects.git
cd demo-projects/ebs-test
mvn -q package
rm -f big.txt
wget -q https://norvig.com/big.txt
hadoop fs -rmr /out.txt
hadoop fs -rm /big.txt
hadoop fs -copyFromLocal big.txt /big.txt
spark-submit --class org.sparkexample.WordCountTask --master spark://sparkmaster:7077 /demo-projects/ebs-test/target/hadoopWordCount-1.0-SNAPSHOT.jar /big.txt
hadoop fs -getmerge /out.txt ./out.txt
head -20 out.txt
"""
#setup Chrome WebDriver
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('--no-sandbox')
capabilities = options.to_capabilities()
eusUrl=os.environ['ET_EUS_API']
print("EUS URL is: "+str(eusUrl))
driver = webdriver.Remote(command_executor=eusUrl, desired_capabilities=capabilities)
driver.get(url)
# create new project
time.sleep(5)
element=driver.find_element_by_xpath("//button[contains(string(), 'New Project')]")
element.click()
time.sleep(5)
driver.find_element_by_name("project.name").send_keys(projectname)
driver.find_element_by_xpath("//button[contains(string(), 'SAVE')]").click()
time.sleep(5)
# create new tjob
driver.find_element_by_xpath("//button[contains(string(), 'New TJob')]").click()
time.sleep(5)
driver.find_element_by_name("tJobName").send_keys(tjobname)
# driver.find_element_by_xpath('//*[@id="mat-select-0"]/div/div[1]/span').click()
driver.find_element_by_class_name("mat-select-trigger").click()
driver.find_element_by_xpath("//mat-option/span[contains(string(), 'None')]").click()
driver.find_element_by_name("tJobImageName").send_keys(tjobimage)
driver.find_element_by_name("commands").send_keys(commands)
driver.find_element_by_xpath("//mat-checkbox[@id='serviceEBS']/label").click()
driver.find_element_by_xpath("//button[contains(string(), 'SAVE')]").click()
time.sleep(1)
# run tjob
driver.find_element_by_xpath("//button[@title='Run TJob']").click()
time.sleep(10)
# default max wait 5 minutes
TSS_MAX_WAIT = 300
# check for success.
while TSS_MAX_WAIT > 0:
try:
element = driver.find_element_by_id('resultMsgText')
if (element.text=="Executing Test" or element.text=="Starting Test Support Service: EBS" or element.text=="Starting Dockbeat to get metrics..."):
print("\t Waiting for tjob execution to complete")
time.sleep(20)
TSS_MAX_WAIT = TSS_MAX_WAIT - 20
element = driver.find_element_by_id('resultMsgText')
continue
else:
print("\t TJob Execution Result: "+element.text)
break
except:
print("\t Something is wrong")
break
driver.close()
| [
14468,
4242,
2235,
198,
2,
6434,
25,
8047,
402,
9226,
292,
198,
2,
362,
14,
18,
14,
23344,
5969,
416,
6502,
261,
5826,
354,
49078,
280,
198,
14468,
4242,
2235,
198,
198,
11748,
640,
198,
11748,
25064,
198,
11748,
28686,
198,
11748,
... | 2.714825 | 1,059 |
import os
import argparse
import numpy as np
import gym
from gym.envs.atari.atari_env import ACTION_MEANING
import pygame
from atari_demo.wrappers import AtariDemo
from atari_demo.utils import *
import time
parser = argparse.ArgumentParser()
parser.add_argument('-g', '--game', type=str, default='MontezumaRevenge')
parser.add_argument('-f', '--frame_rate', type=int, default=60)
parser.add_argument('-y', '--screen_height', type=int, default=840)
parser.add_argument('-d', '--save_dir', type=str, default=None)
parser.add_argument('-s', '--frame_skip', type=int, default=4)
args = parser.parse_args()
if args.save_dir is None:
save_dir = os.path.join(os.getcwd(), 'demos')
else:
save_dir = args.save_dir
if not os.path.exists(save_dir):
os.makedirs(save_dir)
demo_file_name = os.path.join(save_dir, args.game + '.demo')
# //////// set up gym + atari part /////////
ACTION_KEYS = {
"NOOP" : set(),
"FIRE" : {'space'},
"UP" : {'up'},
"RIGHT": {'right'},
"LEFT" : {'left'},
"DOWN" : {'down'},
"UPRIGHT" : {'up', 'right'},
"UPLEFT" : {'up', 'left'},
"DOWNRIGHT" : {'down', 'right'},
"DOWNLEFT" : {'down', 'left'},
"UPFIRE" : {'up', 'space'},
"RIGHTFIRE" : {'right', 'space'},
"LEFTFIRE" : {'left', 'space'},
"DOWNFIRE" : {'down', 'space'},
"UPRIGHTFIRE" : {'up', 'right', 'space'},
"UPLEFTFIRE" : {'up', 'left', 'space'},
"DOWNRIGHTFIRE" : {'down', 'right', 'space'},
"DOWNLEFTFIRE" : {'down', 'left', 'space'},
"TIMETRAVEL": {'b'}
}
env = AtariDemo(gym.make(args.game + 'NoFrameskip-v4'))
available_actions = [ACTION_MEANING[i] for i in env.unwrapped._action_set] + ["TIMETRAVEL"]
env.reset()
loaded_previous = False
if os.path.exists(demo_file_name):
env.load_from_file(demo_file_name)
loaded_previous = True
# ///////// set up pygame part //////////
pygame.init()
screen_size = (int((args.screen_height/210)*160),args.screen_height)
screen = pygame.display.set_mode(screen_size)
small_screen = pygame.transform.scale(screen.copy(), (160,210))
clock = pygame.time.Clock()
pygame.display.set_caption("Recording demonstration for " + args.game)
key_is_pressed = set()
# //////// run the game and record the demo! /////////
quit = False
done = False
show_start_screen()
demonstrations = []
while not quit:
# process key presses & save when requested
key_presses, quit, save = process_key_presses()
if save:
if done and os.path.exists(demo_file_name):
os.remove(demo_file_name)
elif not done:
env.save_to_file(demo_file_name)
save_as_pickled_object(demonstrations, args.game + time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())+".bin")
quit = True
# advance gym env
action = get_gym_action(key_presses)
print("Action:", action)
for step in range(args.frame_skip):
observation, reward, done, info = env.step(action)
#collect demonstrations
#print("Size of observation:", np.asarray(observation).shape)
demonstration = {'observation': observation, 'reward': reward, 'done': done, 'info': info, 'action': action}
if ACTION_KEYS['TIMETRAVEL'].issubset(key_presses):
demonstrations.pop()
elif done:
pass
else:
demonstrations.append(demonstration)
print("Size of demonstrations:", np.asarray(demonstrations).shape)
# show screen
if done:
show_end_screen()
else:
show_game_screen(observation)
clock.tick(float(args.frame_rate)/args.frame_skip)
| [
11748,
28686,
198,
11748,
1822,
29572,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
11550,
198,
6738,
11550,
13,
268,
14259,
13,
35554,
13,
35554,
62,
24330,
1330,
40282,
62,
11682,
1565,
2751,
198,
11748,
12972,
6057,
198,
6738,
379,
... | 2.365142 | 1,509 |
"""Methods for dealing with configuration files."""
import os
try:
import ujson as json
except ImportError:
import json
import sutter
config_ = None
class Config(object):
"""
An internal representation of a configuration file.
Handles multiple possible config sources (path or env var) and nested-key lookups.
"""
def __init__(self, config):
"""Instantiate a Config object with config file contents."""
self.config_ = config
@classmethod
def from_path(cls, path):
"""Load configuration from a given path."""
with open(path) as file:
return cls(json.loads(file.read()))
@classmethod
def from_enviroment(cls):
"""Load configuration based on information provided by enviromental variables."""
path = os.environ.get('CONFIGPATH')
if path is None:
raise ValueError('CONFIGPATH not set!')
return cls.from_path(path)
def get(self, key, default=None):
"""
Fetch a configuration variable, returning `default` if the key does not exist.
:param key: Variable key.
:param default: Default value to return if `key` is not found.
:returns: The value, or `default` if the key does not exist.
"""
try:
value = self[key]
except KeyError:
value = default
return value
def __getitem__(self, key):
"""
Fetch a configuration variable, returning `default` if the key does not exist.
:param key: Variable key.
:returns: The value.
:raises: TypeError if key is not found.
"""
# Handle nested parameters
return_object = self.config_
for key in key.split('.'):
return_object = return_object[key]
return return_object
def get(key, default=None):
"""
Fetch a configuration variable, returning `default` if the key does not exist.
:param key: Variable key, possibly nested via `.`s.
:param default: Default value to return.
:returns: The value, or `default` if the key does not exist.
"""
global config_
if config_ is None:
reload()
return config_.get(key, default)
def reload(path=None):
"""
Reload configuration.
This method looks in three places, in order, to find the config file:
1. an explicit path, if one is passed as an argument
2. the CONFIGPATH env variable, if set
3. the default path at ../config.json
"""
module_base = os.path.dirname(os.path.abspath(sutter.__file__))
fixed_path = os.path.join(module_base, '..', 'config.json')
global config_
if path is not None:
config_ = Config.from_path(path)
elif os.environ.get('CONFIGPATH'):
config_ = Config.from_enviroment()
elif os.path.exists(fixed_path):
config_ = Config.from_path(fixed_path)
else:
print("no configuration path or file given (see README)")
| [
37811,
46202,
329,
7219,
351,
8398,
3696,
526,
15931,
198,
198,
11748,
28686,
198,
198,
28311,
25,
198,
220,
220,
220,
1330,
334,
17752,
355,
33918,
198,
16341,
17267,
12331,
25,
198,
220,
220,
220,
1330,
33918,
198,
11748,
264,
10381,
... | 2.58045 | 1,156 |
# -*- coding: utf-8 -*-
"""
ARM lexer
~~~~~~~~~
Pygments lexer for ARM Assembly.
:copyright: Copyright 2017 Jacques Supcik
:license: Apache 2, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, include
from pygments.token import Text, Name, Number, String, Comment, Punctuation
__all__ = ['ArmLexer']
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
37811,
198,
220,
220,
220,
20359,
31191,
263,
198,
220,
220,
220,
220,
15116,
93,
628,
220,
220,
220,
9485,
11726,
31191,
263,
329,
20359,
10006,
13,
628,
220,
220,
22... | 2.85 | 120 |
import datetime
import os
import sys
import tempfile
import unittest
import rr
if __name__ == "__main__":
unittest.main()
| [
11748,
4818,
8079,
198,
11748,
28686,
198,
11748,
25064,
198,
11748,
20218,
7753,
198,
11748,
555,
715,
395,
198,
198,
11748,
374,
81,
628,
198,
198,
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
198,
220,
220,
220,
555,
71... | 2.765957 | 47 |
import asyncio
import base64
from .base import TelnetShell
TAR_DATA = "tar -czOC /data mha_master miio storage zigbee devices.txt gatewayInfoJson.info 2>/dev/null | base64"
| [
11748,
30351,
952,
198,
11748,
2779,
2414,
198,
198,
6738,
764,
8692,
1330,
12088,
3262,
23248,
198,
198,
51,
1503,
62,
26947,
796,
366,
18870,
532,
26691,
4503,
1220,
7890,
285,
3099,
62,
9866,
21504,
952,
6143,
1976,
328,
20963,
4410,... | 2.933333 | 60 |
from typing import *
class IdentifyPolicy:
"""
Provides entity identification functionalities used during appending entities to a graph.
Identification mechanism is based on the equality of identification keys extracted by entities.
:param identifier: A function to extract the identification key from an entity.
"""
def get_identifier(self, value: Any) -> Any:
"""
Returns identification key from an entity.
:param value: An entity.
:returns: Identification key.
"""
return self.identifier(value) if self.identifier else None
def identify(
self,
prop: 'GraphTemplate.Property',
candidates: List['Node'],
ancestors: Dict[str, List['Node']],
) -> Tuple[List[Optional['Node']], List['Node']]:
"""
Select parent nodes and identical nodes of a new entity.
This method is called during appending an entity to a graph.
:param prop: Template property for new entity.
:param candidates: Nodes having the same identification key as the key of new entity.
:param ancestors: Parent nodes mapped by property names.
:returns: The first item is a list of Parent nodes which the node of new entity should be appended newly.
``None`` means to append a new node without parent. The second item is a list of identical nodes,
which will be merged into ancestors and used in subsequent identifications of child entities.
"""
raise NotImplementedError()
class HierarchicalPolicy(IdentifyPolicy):
"""
Default identification policy used in a container where identification function is defined.
This policy identifies nodes whose entity has the same identification key as the key of appending entity
and whose parent is also identical to the parent of the entity.
"""
class NeverPolicy(IdentifyPolicy):
"""
Identification policy which never identifies nodes.
This policy is used in a container where identification function is not defined.
"""
| [
6738,
19720,
1330,
1635,
201,
198,
201,
198,
201,
198,
4871,
11440,
1958,
36727,
25,
201,
198,
220,
220,
220,
37227,
201,
198,
220,
220,
220,
47081,
9312,
11795,
10345,
871,
973,
1141,
598,
1571,
12066,
284,
257,
4823,
13,
201,
198,
... | 3.051355 | 701 |
import scrapy
| [
11748,
15881,
88,
628,
198
] | 3.2 | 5 |
import os | [
11748,
28686
] | 4.5 | 2 |
import behave
@behave.when(u'I delete the created bot by email')
@behave.when(u'I try to delete a bot by the name of "{bot_name}"')
@behave.then(u'There are no bot by the name of "{bot_name}"')
@behave.given(u'There are no bots in project')
| [
11748,
17438,
628,
198,
31,
1350,
14150,
13,
12518,
7,
84,
6,
40,
12233,
262,
2727,
10214,
416,
3053,
11537,
628,
198,
31,
1350,
14150,
13,
12518,
7,
84,
6,
40,
1949,
284,
12233,
257,
10214,
416,
262,
1438,
286,
45144,
13645,
62,
... | 2.829545 | 88 |
from .models import Entry
| [
6738,
764,
27530,
1330,
21617,
628,
198
] | 4 | 7 |
"""
Module with code related to creating data.
"""
import PIL.Image
import PIL.ImageDraw
import PIL.ImageFont
import numpy as np
import cv2
import net.printing
class TemplatesMaker:
"""
Class for creating plain images of characters.
Plain image is defined as a simple black character on white background. No noise, rotation, etc included.
"""
def __init__(self, font, size):
"""
:param font: PIL.ImageFont's truefont object to be used to create character image
:param size: a (width, height) tuple representing size of images to be produced
"""
self.font = font
self.size = size
def create_template(self, character):
"""
:param character: character to be shown in the image
:return: numpy matrix representing the character
"""
image = self._get_character_image(character)
# Cut out portion that contains characters
upper_left, lower_right = self._get_character_bounding_box(image)
# Image cropped to contain only character
character_image = image[upper_left[0]:lower_right[0], upper_left[1]:lower_right[1]]
larger_dimension = max(character_image.shape)
padding = 20
full_image_size = larger_dimension + 2 * padding, larger_dimension + 2 * padding
full_image = 255 * np.ones(full_image_size)
image_center = int(full_image_size[0] / 2), int(full_image_size[1] / 2)
y_start = int(image_center[0] - (character_image.shape[0] / 2))
x_start = int(image_center[1] - (character_image.shape[1] / 2))
# Paste character image onto full image
full_image[
y_start:y_start + character_image.shape[0],
x_start:x_start + character_image.shape[1]] = character_image
scaled_image = cv2.resize(full_image, self.size)
black_bordered_image = net.printing.get_image_with_border(scaled_image, 2, 0)
white_bordered_image = net.printing.get_image_with_border(black_bordered_image, 4, 255)
return cv2.resize(white_bordered_image, self.size)
| [
37811,
198,
26796,
351,
2438,
3519,
284,
4441,
1366,
13,
198,
37811,
198,
198,
11748,
350,
4146,
13,
5159,
198,
11748,
350,
4146,
13,
5159,
25302,
198,
11748,
350,
4146,
13,
5159,
23252,
198,
198,
11748,
299,
32152,
355,
45941,
198,
1... | 2.602723 | 808 |
import re
import pymysql
| [
11748,
302,
198,
11748,
279,
4948,
893,
13976,
628
] | 2.888889 | 9 |
import datetime
from typing import Any, Callable, Dict, List, Optional, TypedDict, TypeVar
import attr
from . import base_core, base_db, base_proto
def Attrib(
# proto section
is_proto_field: bool = True,
proto_path: Optional[str] = None,
proto_converter: Optional[base_proto.ProtoConverter] = None,
# db section
is_db_field: bool = True,
db_path: Optional[str] = None,
db_converter: Optional[base_db.DbConverter] = None,
# general section
type: type = None,
repeated: bool = False,
deprecated: bool = False,
metadata: Optional[Dict[str, Any]] = None,
**kwargs) -> attr.Attribute:
'''
Args:
# Proto section
is_proto_field: True if this attribute is a field in proto message.
Arguments in proto section take effect only if this is True.
proto_path: field name of the attribute in its proto message.
proto_converter: converter to converte this attribute between proto message and internal Model.
# Db section
is_db_field: True if this attribute is a field in database schema.
Arguments in db section take effect only if this is True.
db_path: field name of this attribute in database schema.
db_converter: converter to converte this attribute between internal Model and database field.
is_serial_id: True if this attribute is used in database as a serial increasing id.
A model class can have at most 1 attribute as serial_id.
is_pkey: True if this db field is the primary key for the row.
The data model of a table should be: (pkey1, pkey2, ..., data_in_json)
# General section
deprecated: The field will be excluded from proto and db layer.
'''
if type is None:
raise ValueError(f'`type` must be specified')
metadata = metadata or {}
passthrough_types = [int, str, bool]
if type in passthrough_types:
if is_proto_field and proto_converter is None:
proto_converter = base_proto.PassThroughConverter()
if is_db_field and db_converter is None:
db_converter = base_db.PassThroughConverter()
elif type is datetime.datetime:
if is_proto_field and proto_converter is None:
proto_converter = base_proto.DatetimeProtoConverter()
if is_db_field and db_converter is None:
db_converter = base_db.DatetimeDbConverter()
metadata[base_core.IS_PROTO_FIELD] = is_proto_field
if is_proto_field:
metadata[base_core.PROTO_PATH] = proto_path
metadata[base_core.PROTO_CONVERTER] = proto_converter
metadata[base_core.IS_DB_FIELD] = is_db_field
if is_db_field:
metadata[base_core.DB_PATH] = db_path
metadata[base_core.DB_CONVERTER] = db_converter
metadata[base_core.REPEATED] = repeated
if repeated:
type = List[type]
if deprecated:
kwargs['default'] = None
return attr.ib(metadata=metadata, type=type, **kwargs)
MODELS = {}
COLLECTION_TO_MODEL = {}
| [
11748,
4818,
8079,
198,
6738,
19720,
1330,
4377,
11,
4889,
540,
11,
360,
713,
11,
7343,
11,
32233,
11,
17134,
276,
35,
713,
11,
5994,
19852,
198,
198,
11748,
708,
81,
198,
198,
6738,
764,
1330,
2779,
62,
7295,
11,
2779,
62,
9945,
... | 2.469697 | 1,254 |
from django.contrib import admin
from .models import Question, Answer, Scrapedquestion
admin.site.register(Question)
admin.site.register(Answer)
admin.site.register(Scrapedquestion)
| [
6738,
42625,
14208,
13,
3642,
822,
1330,
13169,
198,
6738,
764,
27530,
1330,
18233,
11,
23998,
11,
1446,
31951,
25652,
198,
198,
28482,
13,
15654,
13,
30238,
7,
24361,
8,
198,
28482,
13,
15654,
13,
30238,
7,
33706,
8,
198,
28482,
13,
... | 3.588235 | 51 |
axI=n°²ÂjPÀq | [
64,
206,
87,
126,
236,
210,
218,
40,
28,
77,
200,
7200,
31185,
5523,
73,
47,
127,
222,
80
] | 0.894737 | 19 |
from django.shortcuts import render
from Crawlers.Helpers.amazon_crawler import amazon_crawl
from django import template
from Crawlers.Helpers.snapdeal_crawler import snapdeal_crawl
from Crawlers.Helpers.ebay_crawler import ebay_crawl
# Create your views here.
| [
6738,
42625,
14208,
13,
19509,
23779,
1330,
8543,
198,
6738,
20177,
8116,
13,
12621,
19276,
13,
33103,
62,
66,
39464,
1330,
716,
5168,
62,
66,
13132,
198,
6738,
42625,
14208,
1330,
11055,
198,
6738,
20177,
8116,
13,
12621,
19276,
13,
45... | 3.3 | 80 |
"""Check if userbot alive. If you change these, you become the gayest gay such that even the gay world will disown you."""
import asyncio
from telethon import events
from telethon.tl.types import ChannelParticipantsAdmins
from platform import uname
from userbot import ALIVE_NAME
from userbot.utils import admin_cmd
DEFAULTUSER = str(ALIVE_NAME) if ALIVE_NAME else "Set ALIVE_NAME in config vars in Heroku"
@command(outgoing=True, pattern="^.alive$")
async def amireallyalive(alive):
""" For .alive command, check if the bot is running. """
await alive.edit("`░█─░█ █▀▀ █── █── █▀▀█ \n░█▀▀█ █▀▀ █── █── █──█ \n░█─░█ ▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀▀ \n\nYes Sir ! I'm Alive\n\nTelethon version: 6.9.0\nPython: 3.7.3\n\n`"
f"`My Master`: {DEFAULTUSER}\n"
"`My Owner`: @irajkamboj\n\n"
"Join [Channel](https://t.me/TechnoAyanBoT/) For Latest Updates")
| [
37811,
9787,
611,
2836,
13645,
6776,
13,
1002,
345,
1487,
777,
11,
345,
1716,
262,
5650,
395,
5650,
884,
326,
772,
262,
5650,
995,
481,
595,
593,
345,
526,
15931,
198,
11748,
30351,
952,
198,
6738,
5735,
400,
261,
1330,
2995,
198,
6... | 2.341085 | 387 |
'''Setup script for lascheck'''
from setuptools import setup
__version__ = '0.1.4'
CLASSIFIERS = [
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: End Users/Desktop",
"Intended Audience :: Other Audience",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.7",
"Topic :: Scientific/Engineering",
"Topic :: System :: Filesystems",
"Topic :: Scientific/Engineering :: Information Analysis",
]
setup(name='lascheck',
version=__version__,
description="checking conformity of Log ASCII Standard (LAS) files to LAS 2.0 standard",
long_description=open("README.md", "r").read(),
long_description_content_type="text/markdown",
url="https://github.com/MandarJKulkarni/lascheck",
author="Mandar J Kulkarni.",
author_email="mjkool@gmail.com",
license="MIT",
classifiers=CLASSIFIERS,
keywords="las geophysics version",
packages=["lascheck", ],
entry_points={
'console_scripts': [
'lascheck = lascheck:version'
],
}
)
| [
7061,
6,
40786,
4226,
329,
39990,
9122,
7061,
6,
201,
198,
201,
198,
6738,
900,
37623,
10141,
1330,
9058,
201,
198,
201,
198,
834,
9641,
834,
796,
705,
15,
13,
16,
13,
19,
6,
201,
198,
201,
198,
31631,
5064,
40,
4877,
796,
685,
... | 2.534196 | 541 |
#tweepy1.py - To test trend obtaining
import sys
sys.path.append('/home/vijay/.local/lib/python2.7/site-packages')
import tweepy
import woeid
import yweather
import time
import os
import sys
reload(sys)
#Configure Tweepy API
t0 = time.time()
consumer_key = 'Osyy0PSrhMRpnIWxjBLzLJeKR'
consumer_secret = 'AYY7Qb48yl2gk4GacSmnWTrv6keikGpMAsPZaamKIRNoWYqzKI'
access_token = '220306570-Lk0wOlgGNaRBToOt8FIWbko1pTGvb3ZtyAfow5GN'
access_token_secret = 'VcNiPnSuk7LOzC2QYSJkOwgehplBmkXuzp7EwZgE69S1r'
# OAuth process, using the keys and tokens
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
tweapi = tweepy.API(auth)
#Configure Yahoo WOEID API
country_list = ['USA', 'UK', 'India', 'Canada', 'Australia']
for country in country_list:
get_trends(country)
print(country)
print("\n")
t1 = time.time()
print(t1 - t0)
| [
198,
198,
2,
83,
732,
538,
88,
16,
13,
9078,
532,
1675,
1332,
5182,
16727,
198,
198,
11748,
25064,
198,
17597,
13,
6978,
13,
33295,
10786,
14,
11195,
14,
85,
2926,
323,
11757,
12001,
14,
8019,
14,
29412,
17,
13,
22,
14,
15654,
12,... | 2.219512 | 410 |
# Author: Alejandro M. BERNARDIS
# Email alejandro.bernardis at gmail.com
# Created: 2019/11/23 08:53
# El ejemplo fue tomado de: https://github.com/viewfinderco/viewfinder
import time
from dotted.collection import DottedDict
global_manager = CounterManager()
| [
2,
6434,
25,
9300,
47983,
337,
13,
347,
28778,
49608,
198,
2,
9570,
31341,
47983,
13,
33900,
446,
271,
379,
308,
4529,
13,
785,
198,
2,
15622,
25,
13130,
14,
1157,
14,
1954,
8487,
25,
4310,
198,
198,
2,
2574,
304,
73,
18856,
78,
... | 3.044444 | 90 |
import os
from P4 import P4, P4Exception
from qtpy import QtCore, QtGui, QtWidgets
import perforce.Utils as Utils
from perforce.AppInterop import interop | [
11748,
28686,
198,
198,
6738,
350,
19,
1330,
350,
19,
11,
350,
19,
16922,
198,
6738,
10662,
83,
9078,
1330,
33734,
14055,
11,
33734,
8205,
72,
11,
33734,
54,
312,
11407,
198,
198,
11748,
583,
3174,
13,
18274,
4487,
355,
7273,
4487,
... | 2.924528 | 53 |
from logzero import logger, setup_logger, logging
import config
| [
6738,
2604,
22570,
1330,
49706,
11,
9058,
62,
6404,
1362,
11,
18931,
198,
11748,
4566,
198
] | 4 | 16 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/Users/Colin/Documents/pyqode/core/examples/notepad/forms/main_window.ui'
#
# Created by: PyQt5 UI code generator 5.4.1
#
# WARNING! All changes made in this file will be lost!
from qtpy import QtCore, QtGui, QtWidgets
from pyqode.core.widgets import FileSystemTreeView, SplittableCodeEditTabWidget
from . import resources_rc | [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
2,
5178,
7822,
7560,
422,
3555,
334,
72,
2393,
31051,
14490,
14,
5216,
259,
14,
38354,
14,
9078,
80,
1098,
14,
7295,
14,
1069,
12629,
14,
1662,
47852,
14,
23914,
... | 2.985294 | 136 |
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import permutations
a,b=input().split()
l=[]
for i in permutations(a,int(b)):
l.append("".join(i))
print(*sorted(l),sep="\n")
| [
2,
6062,
534,
2438,
994,
13,
4149,
5128,
422,
48571,
1268,
13,
12578,
5072,
284,
48571,
12425,
198,
198,
6738,
340,
861,
10141,
1330,
9943,
32855,
198,
64,
11,
65,
28,
15414,
22446,
35312,
3419,
198,
75,
28,
21737,
198,
1640,
1312,
... | 2.569767 | 86 |
from localization import L
from PyQt6.QtCore import *
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *
from resources.fonts import QXFontDB
from xlib import qt as lib_qt
from ... import backend
| [
6738,
42842,
1330,
406,
198,
6738,
9485,
48,
83,
21,
13,
48,
83,
14055,
1330,
1635,
198,
6738,
9485,
48,
83,
21,
13,
48,
83,
8205,
72,
1330,
1635,
198,
6738,
9485,
48,
83,
21,
13,
48,
83,
54,
312,
11407,
1330,
1635,
198,
6738,
... | 2.794521 | 73 |
# Fits EARM 1.3 (Gaudet et. al 2012) against a single-cell time course
# measurement of an executioner caspase reporter (a proxy for Caspase-3 activity
# i.e. PARP cleavage). The model is contained in earm_1_3_standalone.py which
# was produced via export from a PySB implementation of the model
# (pysb.examples.earm_1_3 in the PySB distribution).
import bayessb
import numpy as np
import matplotlib.pyplot as plt
import os
from earm_1_3_standalone import Model
def likelihood(mcmc, position):
"""TODO"""
global parp_initial, exp_ecrp, cparp_sim_norm, exp_ecrp_var, plateau_idx
param_values = mcmc.cur_params(position)
_, yobs = mcmc.options.model.simulate(mcmc.options.tspan, param_values,
view=True)
cparp_sim_norm = yobs['CPARP_total'] / parp_initial
likelihoods = (exp_ecrp - cparp_sim_norm) ** 2 / (2 * exp_ecrp_var ** 2)
# only fit up to the plateau start, since cparp degradation prevents a good
# fit to the plateau
return np.sum(likelihoods[:plateau_idx])
def prior(mcmc, position):
"""TODO ...mean and variance from calculate_prior_stats"""
global prior_mean, prior_var
return np.sum((position - prior_mean) ** 2 / ( 2 * prior_var))
def step(mcmc):
"""Print out some statistics every 20 steps"""
if mcmc.iter % 20 == 0:
print 'iter=%-5d sigma=%-.3f T=%-.3f acc=%-.3f, lkl=%g prior=%g post=%g' % \
(mcmc.iter, mcmc.sig_value, mcmc.T, float(mcmc.acceptance)/(mcmc.iter+1),
mcmc.accept_likelihood, mcmc.accept_prior, mcmc.accept_posterior)
def filter_params(model, prefix):
"""Return a list of model parameters whose names begin with a prefix"""
return [p for p in model.parameters if p.name.startswith(prefix)]
def sort_params(model, params):
"""Sort parameters to be consistent with the model's parameter order"""
return [p for p in model.parameters if p in params]
def param_stats(params):
"""Calculate mean and variance of log10-transformed parameter values"""
transformed_values = np.log10([p.value for p in params])
return np.mean(transformed_values), np.var(transformed_values)
def calculate_prior_stats(estimate_params, kf, kr, kc):
"""Create vectors of means and variances for calculating the prior
Mean and variance are calculated separately across each of four classes:
kf-fast, kf-slow, kr, and kc."""
kf_fast = []
kf_slow = []
for p in kf:
if p.value >= 1e-3:
kf_fast.append(p)
else:
kf_slow.append(p)
mean_kf_fast, _ = param_stats(kf_fast)
mean_kf_slow, _ = param_stats(kf_slow)
mean_kr, _ = param_stats(kr)
mean_kc, var_kc = param_stats(kc)
mean = np.empty(len(estimate_params))
var = np.empty_like(mean)
var.fill(2.0)
# note: estimate_params must be sorted here, in the same order that bayessb
# maintains the position vector
for i, p in enumerate(estimate_params):
if p in kf_fast:
mean[i] = mean_kf_fast
elif p in kf_slow:
mean[i] = mean_kf_slow
elif p in kr:
mean[i] = mean_kr
elif p in kc:
mean[i] = mean_kc
var[i] = 2 * var_kc
else:
raise RuntimeError("unexpected parameter: " + str(p))
return mean, var
if __name__ == '__main__':
global mcmc, parp_initial
# run the chain
opts = build_opts()
mcmc = bayessb.MCMC(opts)
mcmc.run()
# print some information about the maximum-likelihood estimate parameter set
print
print '%-10s %-12s %-12s %s' % ('parameter', 'original', 'fitted', 'log10(fit/orig)')
max_likelihood_pos = mcmc.positions[mcmc.likelihoods.argmin()]
fitted_values = 10 ** max_likelihood_pos
changes = np.log10(fitted_values / [p.value for p in opts.estimate_params])
for param, new_value, change in zip(opts.estimate_params, fitted_values, changes):
values = (param.name, param.value, new_value, change)
print '%-10s %-12.2g %-12.2g %-+6.2f' % values
# plot data and simulated cleaved PARP trajectories before and after the fit
_, yobs_initial = opts.model.simulate(opts.tspan, [p.value for p in opts.model.parameters])
_, yobs_final = opts.model.simulate(opts.tspan, mcmc.cur_params(mcmc.position))
plt.plot(opts.tspan, exp_ecrp, 'o', mec='red', mfc='none')
plt.plot(opts.tspan, yobs_initial['CPARP_total']/parp_initial, 'b');
plt.plot(opts.tspan, yobs_final['CPARP_total']/parp_initial, 'k');
plt.xlim(0, 2.5e4)
plt.legend(('data', 'original model', 'fitted model'), loc='upper left')
plt.show()
| [
2,
376,
896,
31834,
44,
352,
13,
18,
357,
38,
3885,
316,
2123,
13,
435,
2321,
8,
1028,
257,
2060,
12,
3846,
640,
1781,
198,
2,
15558,
286,
281,
9706,
263,
269,
5126,
589,
9095,
357,
64,
15741,
329,
327,
5126,
589,
12,
18,
3842,
... | 2.357179 | 1,971 |
##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
## Feature Engineering (quadratic fit via linear model)
## %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#%% read data
import numpy as np
data = np.loadtxt('quadratic_raw_data.csv', delimiter=',')
x = data[:,0,None]; y = data[:,1,None]
# plot
import matplotlib.pyplot as plt
plt.figure()
plt.plot(x,y, 'o')
plt.xlabel('x'), plt.ylabel('y')
#%% generate quadratic features
from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(degree=2, include_bias=False)
X_poly = poly.fit_transform(x) # X_poly: 1st column is x, 2nd column is x^2
#%% scale model inputs
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_poly)
#%% linear fit & predict
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X_poly, y)
y_predicted = model.predict(X_poly)
#%% check predictions
# plot
plt.figure()
plt.plot(x,y, 'o', label='raw data')
plt.plot(x,y_predicted, label='quadratic fit')
plt.legend()
plt.xlabel('x'), plt.ylabel('y')
# accuracy
from sklearn.metrics import r2_score
print('Fit accuracy = ', r2_score(y, y_predicted)) | [
2235,
36917,
36917,
36917,
36917,
36917,
36917,
36917,
36917,
36917,
36917,
36917,
36917,
36917,
36917,
36917,
36917,
36917,
36917,
36917,
4,
201,
198,
2235,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
... | 2.576772 | 508 |
# unit tests for rates
import math
import pynucastro.rates as rates
from pytest import approx
| [
2,
4326,
5254,
329,
3965,
198,
11748,
10688,
198,
198,
11748,
279,
2047,
1229,
459,
305,
13,
9700,
355,
3965,
198,
6738,
12972,
9288,
1330,
5561,
628,
628
] | 3.5 | 28 |
#!/usr/bin/env python
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
from ansible.module_utils.basic import AnsibleModule, json
from ansible.module_utils.viptela import viptelaModule, viptela_argument_spec
from collections import OrderedDict
if __name__ == '__main__':
main()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
198,
15037,
34563,
62,
47123,
2885,
13563,
796,
1391,
198,
220,
220,
220,
705,
38993,
62,
9641,
10354,
705,
16,
13,
16,
3256,
198,
220,
220,
220,
705,
13376,
10354,
37250,
3866,
1177,
... | 2.742188 | 128 |
def assign_latest_cp(args):
"""
From the given arguments checks the 'out_path' parameters.
Looks for a checkpoint assuming the checkpoint was saved in out_path
and the previous run was with the same training parameters.
Example:
If you run the program with these arguments;
"dataset = sha,
crop_size = 256,
wot = 0.1,
wtv = 0.01,
reg = 10.0,
num_of_iter_in_ot = 100,
norm_cood = 0"
out_path = /DM-Count
After training some epochs when auto_resume is specified
this function will look at this directort
/DM-Count/ckpts/sha_input-256_wot-0.1_wtv-0.01_reg-10.0_nIter-100_normCood-0/
Assuming checkpoints are saved in "x_ckpt.tar" format this function would assign
"/DM-Count/ckpts/sha_input-256_wot-0.1_wtv-0.01_reg-10.0_nIter-100_normCood-0/7_ckpt.tar"
path to args.resume
"""
# take a look at the checkpoints at "out_path"
import os,argparse
ckpts_path = \
os.path.join(args.out_path,'ckpts',
'{}_input-{}_wot-{}_wtv-{}_reg-{}_nIter-{}_normCood-{}'
.format(args.dataset, args.crop_size, args.wot, args.wtv,
args.reg, args.num_of_iter_in_ot, args.norm_cood))
if os.path.exists(ckpts_path):
ckpt_list = [ckpt_no(f) for f in os.listdir(ckpts_path) if ckpt_no(f) != None]
if ckpt_list:
latest_no = max(ckpt_list)
args = vars(args)
args.update({'resume':
os.path.join(ckpts_path,
"{}_ckpt.tar".format(latest_no))})
args = argparse.Namespace(**args) | [
4299,
8333,
62,
42861,
62,
13155,
7,
22046,
2599,
198,
220,
220,
220,
37227,
198,
220,
220,
220,
3574,
262,
1813,
7159,
8794,
262,
705,
448,
62,
6978,
6,
10007,
13,
198,
220,
220,
220,
29403,
329,
257,
26954,
13148,
262,
26954,
373,... | 1.935374 | 882 |
import pygame
from digicolor import colors
import numpy as np
from nasergame.lib import math3d as m3d
__all__ = ["Wireframe"]
def pairs(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
return zip(iterable[::2], iterable[1::2])
| [
11748,
12972,
6057,
198,
6738,
3100,
27045,
273,
1330,
7577,
198,
11748,
299,
32152,
355,
45941,
198,
198,
6738,
299,
6005,
6057,
13,
8019,
1330,
10688,
18,
67,
355,
285,
18,
67,
198,
198,
834,
439,
834,
796,
14631,
29451,
14535,
8973... | 2.39604 | 101 |
import numpy as np
a = np.array([[3,2,1], [5, 4, -1]])
b = np.array([[4,5,7], [-3, 4, -1]])
print(a*b)
print(a)
print(b) | [
11748,
299,
32152,
355,
45941,
198,
198,
64,
796,
45941,
13,
18747,
26933,
58,
18,
11,
17,
11,
16,
4357,
685,
20,
11,
604,
11,
532,
16,
11907,
8,
198,
65,
796,
45941,
13,
18747,
26933,
58,
19,
11,
20,
11,
22,
4357,
25915,
18,
... | 1.753623 | 69 |
"""
Serializers
"""
import datetime
import collections
from dateutil import parser
from google.appengine.ext.ndb import ModelAttribute
from exceptions import ValidationError, SerializerError
from helpers import get_key_from_urlsafe, KEY_CLASS
TYPE_MAPPING = {
'IntegerProperty': IntegerField,
'FloatProperty': FloatField,
'BooleanProperty': BooleanField,
'StringProperty': StringField,
'TextProperty': StringField,
'DateTimeProperty': DatetimeField,
'KeyProperty': KeyField
}
READ_ONLY_FIELDS = [
MethodField
]
| [
37811,
198,
32634,
11341,
198,
37811,
198,
11748,
4818,
8079,
198,
11748,
17268,
198,
198,
6738,
3128,
22602,
1330,
30751,
198,
6738,
23645,
13,
1324,
18392,
13,
2302,
13,
358,
65,
1330,
9104,
33682,
198,
198,
6738,
13269,
1330,
3254,
2... | 3.134078 | 179 |
import uuid
from fastapi import status
"""
NOTE: There are no tests for the foreign key constraints. The DELETE endpoint will need to be updated once the endpoints
are in place in order to account for this.
"""
#
# INVALID TESTS
#
#
# VALID TESTS
#
| [
11748,
334,
27112,
198,
198,
6738,
3049,
15042,
1330,
3722,
628,
198,
37811,
198,
16580,
25,
1318,
389,
645,
5254,
329,
262,
3215,
1994,
17778,
13,
383,
5550,
2538,
9328,
36123,
481,
761,
284,
307,
6153,
1752,
262,
886,
13033,
198,
53... | 3.2375 | 80 |
#!/usr/bin/env python
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
x,y,z = [], [], []
xd,yd,zd = [], [], []
x_fname = '/home/cobot/Desktop/assemble_project/track_data/assemble_0.01s/dataFile_x.txt'
x_dmp_fname = '/home/cobot/Desktop/assemble_project/track_data/assemble_0.01s/dmp_dataFile_x.txt'
with open(x_fname, 'r') as fx:#1
linesx = fx.readlines()#2
for linex in linesx:#3
valuex = [float(sx) for sx in linex.split()]#4
x.append(valuex[0])
with open(x_dmp_fname, 'r') as fxd:#1
linesxd = fxd.readlines()#2
for linexd in linesxd:#3
valuexd = [float(sxd) for sxd in linexd.split()]#4
xd.append(valuexd[0])
y_fname = '/home/cobot/Desktop/assemble_project/track_data/assemble_0.01s/dataFile_y.txt'
y_dmp_fname = '/home/cobot/Desktop/assemble_project/track_data/assemble_0.01s/dmp_dataFile_y.txt'
with open(y_fname, 'r') as fy:#1
linesy = fy.readlines()#2
for liney in linesy:#3
valuey = [float(sy) for sy in liney.split()]#4
y.append(valuey[0])
with open(y_dmp_fname, 'r') as fyd:#1
linesyd = fyd.readlines()#2
for lineyd in linesyd:#3
valueyd = [float(syd) for syd in lineyd.split()]#4
yd.append(valueyd[0])
z_fname = '/home/cobot/Desktop/assemble_project/track_data/assemble_0.01s/dataFile_z.txt'
z_dmp_fname = '/home/cobot/Desktop/assemble_project/track_data/assemble_0.01s/dmp_dataFile_z.txt'
with open(z_fname, 'r') as fz:#1
linesz = fz.readlines()#2
for linez in linesz:#3
valuez = [float(sz) for sz in linez.split()]#4
z.append(valuez[0])
with open(z_dmp_fname, 'r') as fzd:#1
lineszd = fzd.readlines()#2
for linezd in lineszd:#3
valuezd = [float(szd) for szd in linezd.split()]#4
zd.append(valuezd[0])
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_title("3D")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
figure = ax.plot(x,y,z,c='b')
figure = ax.plot(xd,yd,zd,c='g')
plt.show()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
2603,
29487,
8019,
355,
285,
489,
198,
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
198,
198,
87,
11,
88,
11,
89,
796,
685... | 2.028484 | 983 |
#!python
from timetable.timetableparser import parse
import sys
import export
import argparse
if __name__ == "__main__":
convert(*build_options())
| [
2,
0,
29412,
198,
198,
6738,
40021,
13,
16514,
316,
540,
48610,
1330,
21136,
198,
11748,
25064,
198,
11748,
10784,
198,
11748,
1822,
29572,
628,
628,
198,
198,
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
198,
220,
220,
22... | 3.204082 | 49 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 29 09:22:06 2018
@author: marvin
"""
import numpy as np
## 1. Data dimensions
### 2. Scalars: 0-dimension
height = np.array(1.79)
age = np.array(1.79, dtype=np.uint8) ##unsigned int
# age2 becomes int64
age2 = age + 3
age2 = age + np.array(3, dtype = np.uint8)
### 2. Vectors: 1 dimension
# Creating an sample in column-vector form (3x1)
sample = np.array([1.79, 20, 31])
# dimension (3, ): the matrix has only one dimension
sample.shape
# Creating a weigth vector
weight = np.array([3, 1, 8.5])
# linear combination
result = np.array(0)
for i in range(sample.size):
result = result + sample[i] * weight[i]
print(result)
#### or simple
result = np.dot(sample, weight)
print(result)
# Multipliacao de matrizes
# M1 = m x p
# M2 = p x n
# The number of columns of the first Matrix should be equal to the number of rows of the
# second
samples = np.array([[1.79, 20, 79], [1.65, 28, 45.2]])
weights = np.array([[3, 1], [1, 9], [8.5, 2]])
result = np.matmul(samples, weights)
#### How to represent a neuron???
## We can add -1 to the sample
# sample: [HEIGHT, KG, AGE]
sample = np.array([1.79, 50, 40, -1])
### And add the Activation Threshold (Limiar de ativacao) to the weights. Suppose our
### Thresholds is equal to 0.5
weight = np.array([3, 3.5, -1.5, 100])
# result = x1*w1 + x2*w2 + x3*w3 -1*theta
result = np.dot(sample, weight)
print("u = %.2f" % result)
y = step(result)
print("y = %.2f" % y)
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
37811,
198,
41972,
319,
7031,
8621,
2808,
7769,
25,
1828,
25,
3312,
2864,
198,
198,
31,
9800,
25,
1667,
7114,
198... | 2.525253 | 594 |
from __future__ import unicode_literals
from django.test import TestCase
from ..utils import partial_dict_equals
| [
6738,
11593,
37443,
834,
1330,
28000,
1098,
62,
17201,
874,
198,
198,
6738,
42625,
14208,
13,
9288,
1330,
6208,
20448,
198,
198,
6738,
11485,
26791,
1330,
13027,
62,
11600,
62,
4853,
874,
628
] | 3.515152 | 33 |
# -*- coding: utf-8 -*-
# Copyright 2015-2016 Telefónica Investigación y Desarrollo, S.A.U
#
# This file is part of FIWARE 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 License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# See the License for the specific language governing permissions and
# limitations under the License.
#
# For those usages not covered by the Apache version 2.0 License please
# contact with opensource@tid.es
__copyright__ = "Copyright 2015-2016"
__license__ = " Apache License, Version 2.0"
# GLANCE KEYSTONE SERVICE
KEYSTONE_GLANCE_SERVICE_NAME = "glance"
KEYSTONE_GLANCE_SERVICE_TYPE = "image"
# CONFIGURATION PROPERTIES
PROPERTIES_FILE = "conf/settings.json"
PROPERTIES_CONFIG_ENV = "environment"
PROPERTIES_CONFIG_ENV_NAME = "name"
PROPERTIES_CONFIG_RES = "resources"
PROPERTIES_CONFIG_RES_NAME = "name"
PROPERTIES_CONFIG_RES_url = "url"
PROPERTIES_CONFIG_CRED = "credentials"
PROPERTIES_CONFIG_CRED_TYPE = "credential_type"
PROPERTIES_CONFIG_CRED_REGION_NAME = "region_name"
PROPERTIES_CONFIG_CRED_KEYSTONE_URL = "keystone_url"
PROPERTIES_CONFIG_CRED_TENANT_ID = "tenant_id"
PROPERTIES_CONFIG_CRED_TENANT_NAME = "tenant_name"
PROPERTIES_CONFIG_CRED_USER_DOMAIN_NAME = "user_domain_name"
PROPERTIES_CONFIG_CRED_USER = "user"
PROPERTIES_CONFIG_CRED_PASS = "password"
PROPERTIES_CONFIG_CRED_HOST_NAME = "host_name"
PROPERTIES_CONFIG_CRED_HOST_USER = "host_user"
PROPERTIES_CONFIG_CRED_HOST_PASSWORD = "host_password"
PROPERTIES_CONFIG_CRED_HOST_KEY = "host_key"
PROPERTIES_CONFIG_GLANCESYNC = "glancesync"
PROPERTIES_CONFIG_GLANCESYNC_MASTER_REGION_NAME = "master_region_name"
PROPERTIES_CONFIG_GLANCESYNC_BIN_PATH = "bin_path"
PROPERTIES_CONFIG_GLANCESYNC_CONFIG_FILE = "config_file"
PROPERTIES_CONFIG_API_GLANCESYNC = "glancesync_api"
PROPERTIES_CONFIG_API_GLANCESYNC_HOST = "host"
PROPERTIES_CONFIG_API_GLANCESYNC_PROTOCOL = "protocol"
PROPERTIES_CONFIG_API_GLANCESYNC_PORT = "port"
PROPERTIES_CONFIG_API_GLANCESYNC_RESOURCE = "resource"
# RESOURCES
IMAGES_DIR = "resources/images"
# TASK TIMERS AND TIMEOUTS (in seconds)
DEFAULT_REQUEST_TIMEOUT = 60
# CREDENTIAL TYPE
CREDENTIAL_TYPE_BASE_ADMIN = "base_admin"
CREDENTIAL_TYPE_HOST = "host"
CREDENTIAL_TYPE_SECONDARY_ADMIN = "secondary_admin"
# BEHAVE FEATURES
FEATURES_NOT_EMPTY_VALUE = "[NOT_EMPTY]"
MAX_WAIT_TASK_FINISHED = 10 # 10 checks each 5 seconds
WAIT_SECONDS = 10 # seconds
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
2,
15069,
1853,
12,
5304,
14318,
69,
18840,
3970,
16203,
32009,
18840,
331,
2935,
283,
2487,
78,
11,
311,
13,
32,
13,
52,
198,
2,
198,
2,
770,
2393,
318,
636,
... | 2.566729 | 1,064 |
import itertools
import math
import random
from functools import partial
from strong_graphs.output import output
from strong_graphs.data_structure import Network
from strong_graphs.negative import (
nb_neg_arcs,
nb_neg_loop_arcs,
nb_neg_tree_arcs,
)
from strong_graphs.arc_generators import (
gen_tree_arcs,
gen_remaining_arcs,
gen_loop_arcs,
)
from strong_graphs.mapping import (
map_graph,
map_distances,
mapping_required,
)
from strong_graphs.visualise.draw import draw_graph
from strong_graphs.utils import (
nb_arcs_from_density,
shortest_path,
)
__all__ = ["build_instance"]
def arc_weight_tree(ξ, D, is_negative):
"""This will make analysing the distribution a little tricky"""
if is_negative:
x = D(ξ, b=min(0, D.keywords["b"]))
assert x <= 0, f"{x=}"
return x
else:
x = D(ξ, a=max(0, D.keywords["a"]))
assert x >= 0, f"{x=}"
return x
def arc_weight_remaining(ξ, D, δ, is_negative):
"""This will make analysing the distribution a little tricky"""
if is_negative:
x = D(ξ, a=max(δ, D.keywords["a"]), b=0)
assert x <= 0, f"{x=}"
return x
else:
x = D(ξ, a=0) + max(δ, 0)
assert x >= 0, f"{x=}"
return x
def build_instance(ξ, n, m, r, D):
"""The graph generation algorithm."""
assert n <= m <= n * (n - 1), f"invalid number of arcs {m=}"
network = Network(nodes=range(n))
# Create optimal shortest path tree
m_neg = nb_neg_arcs(n, m, r)
m_neg_tree = nb_neg_tree_arcs(ξ, n, m, m_neg)
tree_arcs = set()
source = 0
for u, v in gen_tree_arcs(ξ, n, m, m_neg_tree):
is_negative = network.number_of_arcs() < m_neg_tree
w = arc_weight_tree(ξ, D, is_negative)
tree_arcs.add((u, v))
network.add_arc(u, v, w)
distances = shortest_path(network)
m_neg_tree_loop = min(m_neg_tree, nb_current_non_pos_tree_loop(network))
m_neg_loop = nb_neg_loop_arcs(ξ, n, m, m_neg, m_neg_tree, m_neg_tree_loop)
if (mapping := mapping_required(ξ, distances, m_neg_loop)):
print("Remapping")
tree_arcs = set((mapping[u], mapping[v]) for (u, v) in tree_arcs)
network = map_graph(network, mapping)
distances = map_distances(distances, mapping)
source = mapping[source]
m_neg_loop = min(m_neg_tree, sum(1 for u, v in tree_arcs if v == (u + 1) % n and w <= 0))
# Add the remaining arcs - first the loop arcs then the remaining arcs
for (u, v, is_negative) in itertools.chain(
gen_loop_arcs(ξ, network, distances, m_neg_loop - m_neg_tree_loop),
gen_remaining_arcs(ξ, network, distances, n, m, m_neg),
):
δ = distances[v] - distances[u]
w = arc_weight_remaining(ξ, D, δ, is_negative)
assert (is_negative and w <= 0) or (not is_negative and w >= 0)
network.add_arc(u, v, w)
return network, tree_arcs, distances, mapping, source
if __name__ == "__main__":
#m = 100
s = 1
ξ = random.Random(s)
#d = ξ.random()
#n, m = determine_n_and_m(x, d)
d = 0
n = 10 #determine_n(m, d)
#m = 10000
#r = ξ.random()
r = 0.001
z = ξ.randint(1, n)
lb = ξ.randint(-10000, 0)
ub = ξ.randint(0, 10000)
D = partial(random.Random.randint, a=lb, b=ub)
m = nb_arcs_from_density(n, d)
network, tree_arcs, distances, mapping, source = build_instance(ξ, n=n, m=m, r=r, D=D)
draw_graph(network, tree_arcs, distances)
change_source_nodes(ξ, network, z)
print('complete')
output(ξ, network, 0, m, d, r, s, z, lb, ub, -1)
| [
11748,
340,
861,
10141,
198,
11748,
10688,
198,
11748,
4738,
198,
6738,
1257,
310,
10141,
1330,
13027,
198,
6738,
1913,
62,
34960,
82,
13,
22915,
1330,
5072,
198,
6738,
1913,
62,
34960,
82,
13,
7890,
62,
301,
5620,
1330,
7311,
198,
67... | 2.147356 | 1,683 |
import sys
import math
from enum import Enum
import random
number_of_cells = int(input())
game = Game()
for i in range(number_of_cells):
cell_index, richness, neigh_0, neigh_1, neigh_2, neigh_3, neigh_4, neigh_5 = [int(j) for j in input().split()]
game.board.append(Cell(cell_index, richness, [neigh_0, neigh_1, neigh_2, neigh_3, neigh_4, neigh_5]))
while True:
_day = int(input())
game.day = _day
nutrients = int(input())
game.nutrients = nutrients
sun, score = [int(i) for i in input().split()]
game.my_sun = sun
game.my_score = score
opp_sun, opp_score, opp_is_waiting = [int(i) for i in input().split()]
game.opponent_sun = opp_sun
game.opponent_score = opp_score
game.opponent_is_waiting = opp_is_waiting
number_of_trees = int(input())
game.trees.clear()
for i in range(number_of_trees):
inputs = input().split()
cell_index = int(inputs[0])
size = int(inputs[1])
is_mine = inputs[2] != "0"
is_dormant = inputs[3] != "0"
game.trees.append(Tree(cell_index, size, is_mine == 1, is_dormant))
number_of_possible_actions = int(input())
game.possible_actions.clear()
for i in range(number_of_possible_actions):
possible_action = input()
game.possible_actions.append(Action.parse(possible_action))
print(game.compute_next_action()) | [
11748,
25064,
201,
198,
11748,
10688,
201,
198,
6738,
33829,
1330,
2039,
388,
201,
198,
11748,
4738,
201,
198,
201,
198,
201,
198,
17618,
62,
1659,
62,
46342,
796,
493,
7,
15414,
28955,
201,
198,
6057,
796,
3776,
3419,
201,
198,
1640,... | 2.289176 | 619 |
# encoding: utf-8
# Copyright 2011 Tree.io Limited
# This file is part of Treeio.
# License www.tree.io/license
"""
Import/Export Contacts API
"""
import csv
from django.http import HttpResponse
import StringIO
import datetime
class ProcessTransactions():
"Import/Export Contacts"
def export_transactions(self, transactions):
"Export transactions into CSV file"
response = HttpResponse(mimetype='text/csv')
response[
'Content-Disposition'] = 'attachment; filename=Transactions_%s.csv' % datetime.date.today().isoformat()
writer = csv.writer(response)
headers = ['name', 'source', 'target', 'liability',
'category', 'account', 'datetime', 'value', 'details']
writer.writerow(headers)
for transaction in transactions:
row = []
row.append(transaction)
row.append(transaction.source)
row.append(transaction.target)
row.append(transaction.liability)
row.append(transaction.category)
row.append(transaction.account)
row.append(transaction.datetime)
row.append(transaction.get_relative_value())
row.append(transaction.details)
writer.writerow(row)
return response
def import_transactions(self, content):
"Import transactions from CSV file"
f = StringIO.StringIO(content)
transactions = csv.DictReader(f, delimiter=',')
self.parse_transactions(transactions)
def parse_transactions(self, transactions):
"Break down CSV file into transactions"
| [
2,
21004,
25,
3384,
69,
12,
23,
198,
2,
15069,
2813,
12200,
13,
952,
15302,
198,
2,
770,
2393,
318,
636,
286,
12200,
952,
13,
198,
2,
13789,
7324,
13,
21048,
13,
952,
14,
43085,
198,
198,
37811,
198,
20939,
14,
43834,
2345,
8656,
... | 2.490826 | 654 |
"""
Model building using keras library
This includes code for building the various RNN base models for our polymuse
The models are store in current directory, in hierarchy
--h5_models/
--piano/
--stateful/
--stateless/
--lead/
--stateful/
--stateless/
--drum/
--stateful/
--stateless/
--chorus/
--stateful/
--stateless/
--dense3/
--stateful/
--stateless/
The model includes the core functionality function as
load --> to load h5 models from .h5 files
octave_loss --> to calculate the octave loss, not tested
predict, predict_b, predict_dense --> predict the next note, time instance based on models and the current input
"""
import numpy, datetime, json, os
from keras.models import Sequential, load_model
from keras.layers import LSTM, Dropout, Dense, Activation, CuDNNLSTM, TimeDistributed, Flatten
from keras.callbacks import ModelCheckpoint, EarlyStopping
from keras.optimizers import Adagrad, Adam, RMSprop
import tensorflow as tf
from polymuse import dataset2 as d2
from polymuse.losses import rmsecat
from keras import backend as kback
from numpy import random
random.seed(131)
tf.set_random_seed(131)
HOME = os.getcwd()
| [
628,
628,
198,
198,
37811,
198,
17633,
2615,
1262,
41927,
292,
5888,
198,
1212,
3407,
2438,
329,
2615,
262,
2972,
371,
6144,
2779,
4981,
329,
674,
7514,
76,
1904,
220,
198,
464,
4981,
389,
3650,
287,
1459,
8619,
11,
287,
18911,
198,
... | 2.76087 | 460 |
import asyncio
import json
import logging
from datetime import date
from datetime import datetime
from datetime import time
import arrow
import telepot
from base_site.mainapp.models import Records
from django.conf import settings
from telepot.aio.loop import MessageLoop
| [
11748,
30351,
952,
198,
11748,
33918,
198,
11748,
18931,
198,
6738,
4818,
8079,
1330,
3128,
198,
6738,
4818,
8079,
1330,
4818,
8079,
198,
6738,
4818,
8079,
1330,
640,
198,
198,
11748,
15452,
198,
11748,
5735,
13059,
198,
6738,
2779,
62,
... | 3.956522 | 69 |
# Copyright (c) 2012 Advanced Micro Devices, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import print_function
from __future__ import absolute_import
from topologies.BaseTopology import BaseTopology
class Cluster(BaseTopology):
""" A cluster is a group of nodes which are all one hop from eachother
Clusters can also contain other clusters
When creating this kind of topology, return a single cluster (usually
the root cluster) from create_system in configs/ruby/<protocol>.py
"""
_num_int_links = 0
_num_ext_links = 0
_num_routers = 0
# Below methods for auto counting
@classmethod
@classmethod
@classmethod
def __init__(self, intBW=0, extBW=0, intLatency=0, extLatency=0):
""" internalBandwidth is bandwidth of all links within the cluster
externalBandwidth is bandwidth from this cluster to any cluster
connecting to it.
internal/externalLatency are similar
**** When creating a cluster with sub-clusters, the sub-cluster
external bandwidth overrides the internal bandwidth of the
super cluster
"""
self.nodes = []
self.router = None # created in makeTopology
self.intBW = intBW
self.extBW = extBW
self.intLatency = intLatency
self.extLatency = extLatency
def makeTopology(self, options, network, IntLink, ExtLink, Router):
""" Recursively make all of the links and routers
"""
# make a router to connect all of the nodes
self.router = Router(router_id=self.num_routers())
network.routers.append(self.router)
for node in self.nodes:
if type(node) == Cluster:
node.makeTopology(options, network, IntLink,
ExtLink, Router)
# connect this cluster to the router
link_out = IntLink(link_id=self.num_int_links(), src_node=self.router,
dst_node=node.router)
link_in = IntLink(link_id=self.num_int_links(), src_node=node.router,
dst_node=self.router)
if node.extBW:
link_out.bandwidth_factor = node.extBW
link_in.bandwidth_factor = node.extBW
# if there is an internal b/w for this node
# and no ext b/w to override
elif self.intBW:
link_out.bandwidth_factor = self.intBW
link_in.bandwidth_factor = self.intBW
if node.extLatency:
link_out.latency = node.extLatency
link_in.latency = node.extLatency
elif self.intLatency:
link_out.latency = self.intLatency
link_in.latency = self.intLatency
network.int_links.append(link_out)
network.int_links.append(link_in)
else:
# node is just a controller,
# connect it to the router via a ext_link
link = ExtLink(link_id=self.num_ext_links(), ext_node=node,
int_node=self.router)
if self.intBW:
link.bandwidth_factor = self.intBW
if self.intLatency:
link.latency = self.intLatency
network.ext_links.append(link)
| [
2,
15069,
357,
66,
8,
2321,
13435,
4527,
29362,
11,
3457,
13,
198,
2,
1439,
2489,
10395,
13,
198,
2,
198,
2,
2297,
396,
3890,
290,
779,
287,
2723,
290,
13934,
5107,
11,
351,
393,
1231,
198,
2,
17613,
11,
389,
10431,
2810,
326,
2... | 2.414826 | 2,037 |
from setuptools import setup, find_packages
with open('README.md') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='spotify_infosuite',
version='0.1.0',
description='Provides info about song/artist',
long_description=readme,
url='https://github.com/stevedpedersen/spotify-infosuite',
author='Andrew Lesondak & Steve Pedersen',
author_email='arlesondak@gmail.com & pedersen@sfsu.edu',
license=license,
packages=find_packages(exclude=('tests', 'docs'))
) | [
6738,
900,
37623,
10141,
1330,
9058,
11,
1064,
62,
43789,
628,
198,
4480,
1280,
10786,
15675,
11682,
13,
9132,
11537,
355,
277,
25,
198,
197,
961,
1326,
796,
277,
13,
961,
3419,
198,
198,
4480,
1280,
10786,
43,
2149,
24290,
11537,
355... | 2.722826 | 184 |
import functools
import warnings
from typing import Callable, Generic, Hashable, Type, TypeVar
from typing_extensions import ParamSpec
from ._internal import API
from ._providers.indirect import ImplementationDependency
P = ParamSpec("P")
T = TypeVar("T")
# @API.private
@API.private
| [
11748,
1257,
310,
10141,
198,
11748,
14601,
198,
6738,
19720,
1330,
4889,
540,
11,
42044,
11,
21059,
540,
11,
5994,
11,
5994,
19852,
198,
198,
6738,
19720,
62,
2302,
5736,
1330,
25139,
22882,
198,
198,
6738,
47540,
32538,
1330,
7824,
19... | 3.464286 | 84 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2020-09-04 08:33
from __future__ import unicode_literals
import bluebottle.files.validators
from django.db import migrations, models
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
2980,
515,
416,
37770,
352,
13,
1157,
13,
1314,
319,
12131,
12,
2931,
12,
3023,
8487,
25,
2091,
198,
6738,
11593,
37443,
834,
1330,
28000,
1098,
62,
17201,
874,
198... | 2.865672 | 67 |
# Uses Python 2.7
print "This program will allow you to easily edit the quiz data."
print "It assumes that a folder named 'Website' is in the same directory\n and that the folder structure matches that of the"
print "one located at https://github.com/nichwall/LASA-Engineering-Design-Quizzes."
print "\nThe quiz data is stored in a Tab Seperated File (.tsv), and follows the format"
print "of the included file at the above link."
print "**********"
raw_input("Press enter to continue...")
quizSrc = "quizData.tsv"
appSrc = "Website/finalVersion.py"
print "Reading quiz data...",
quizFile = open(quizSrc,'r')
readed = quizFile.read().split("\n")
quizFile.close()
print "Done!"
print "Reading application data...",
appFile = open(appSrc,'r')
appIn = appFile.read().split("\n")
appFile.close()
print "Done!"
qTitles = []
for i in range(6):
qTitles.append(raw_input("Enter Quiz %s Name: " % i))
outStr = ""
curLine = 0
while appIn[curLine].find("###") == -1:
outStr += appIn[curLine] + "\n"
curLine+=1
outStr += "### BEGIN CONFIG\n"
# Rename quizzes
outStr += '\n# Titles of the quizzes\nquizTitles = ['
for i in qTitles:
outStr += '"%s",' % i
outStr = outStr[:-1]+"]"
# Get counts of questions in the quizzes
qLens = []
curLen = 1
for i in range(1,len(readed)-2):
qNum = readed[i].split("\t")[0]
if int(qNum) == int(readed[i+1].split("\t")[0]):
curLen+=1
else:
qLens.append(curLen)
curLen = 1
qLens.append(curLen)
outStr += "\n\n# Number of questions in the quiz\nquizLengths = ["
for i in qLens:
outStr += '%s,' % i
outStr = outStr[:-1]
outStr += "]"
outStr += '\n\n# Variable to control the quizzes.\nquizDatas = """'
for i in readed:
outStr += i + "\n"
outStr = outStr[:-1]
outStr += '"""\n\n### END CONFIG\n'
# Add the rest of it back in...
curLine += 1
while appIn[curLine].find("###") == -1:
curLine+=1
for i in range(curLine+1,len(appIn)-1):
outStr += appIn[i] + "\n"
# Write to file!
file = open(appSrc,'w')
file.write(outStr)
file.close()
| [
2,
36965,
11361,
362,
13,
22,
198,
198,
4798,
366,
1212,
1430,
481,
1249,
345,
284,
3538,
4370,
262,
38964,
1366,
526,
198,
4798,
366,
1026,
18533,
326,
257,
9483,
3706,
705,
33420,
6,
318,
287,
262,
976,
8619,
59,
77,
290,
326,
2... | 2.573472 | 769 |
from django.contrib.auth import get_user_model
from django.test import TestCase
from ..profilefields import ProfileFields
User = get_user_model()
| [
6738,
42625,
14208,
13,
3642,
822,
13,
18439,
1330,
651,
62,
7220,
62,
19849,
198,
6738,
42625,
14208,
13,
9288,
1330,
6208,
20448,
198,
198,
6738,
11485,
13317,
25747,
1330,
13118,
15878,
82,
198,
198,
12982,
796,
651,
62,
7220,
62,
... | 3.386364 | 44 |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Takes a linked list and reverses it.
| [
2,
30396,
329,
1702,
306,
12,
25614,
1351,
13,
198,
2,
1398,
7343,
19667,
25,
198,
2,
220,
220,
220,
220,
825,
11593,
15003,
834,
7,
944,
11,
1188,
28,
15,
11,
1306,
28,
14202,
2599,
198,
2,
220,
220,
220,
220,
220,
220,
220,
... | 2.228261 | 92 |
#-----------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------
#-------------------------------B-SPLINE EXAMPLE CODE-------------------------------
#-----------------------------------------------------------------------------------
#--------------------------------Benjamin D. Donovan--------------------------------
#-----------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------
#Before this example can work, one must compile the bSplineEv.f95 with f2py.
#Change directories to the location of bSplineEv.f95, then perform:
#f2py -c -m bSplineEv bSplineEv.f95
from numpy import *
import bSplineEv as b
import scipy.interpolate
def bSplineExample(xData, yData, zData, x, y):
'''
Evaluates the bivariate B-spline interpolation at a coordinate (x,y).
Parameters
----------
xData : 1D array
The array of x-coordinates to be interpolated.
yData : 1D array
The array of y-coordinates to be interpolated.
zData : 1D array
The array of z-coordinates to be interpolated.
x : float
The x-coordinate at which to evaluate the interpolation.
y : float
The y-coordinate at which to evaluate the interpolation.
Returns
-------
'''
#Peform the interpolation.
interp = scipy.interpolate.SmoothBivariateSpline(xData, yData, zData)
#Get the knot vectors and the coefficient vector.
xKnots, yKnots = interp.get_knots()
coeffs = interp.get_coeffs()
#Reshape the coefficient vector.
coeffs = reshape(coeffs,(4,4))
#Evaluate the bivariate B-spline interpolation at the coordinate (x,y).
interpVal = b.bivariatebsplineev(x, y, xKnots, yKnots, coeffs, 0, 0)
dxVal = b.bivariatebsplineev(x, y, xKnots, yKnots, coeffs, 1, 0)
dyVal = b.bivariatebsplineev(x, y, xKnots, yKnots, coeffs, 0, 1)
return interpVal, dxVal, dyVal | [
2,
10097,
1783,
6329,
198,
2,
10097,
1783,
6329,
198,
2,
1783,
24305,
33,
12,
4303,
24027,
7788,
2390,
16437,
42714,
1783,
24305,
198,
2,
10097,
1783,
6329,
198,
2,
3880,
11696,
13337,
360,
13,
31565,
3880,
198,
2,
10097,
1783,
6329,
... | 3.059942 | 684 |
import random
HEADERS = {
'Host': 'bet.hkjc.com',
'User-Agent': getheaders(),
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
}
| [
11748,
4738,
201,
198,
201,
198,
37682,
4877,
796,
1391,
201,
198,
220,
220,
220,
220,
220,
220,
220,
705,
17932,
10354,
705,
11181,
13,
71,
42421,
66,
13,
785,
3256,
201,
198,
220,
220,
220,
220,
220,
220,
220,
705,
12982,
12,
36... | 1.812227 | 229 |
# -*- coding: utf-8 -*-
""" Module summary description.
More detailed description.
"""
from pyrasta.crs import srs_from
from pyrasta.io_.files import RasterTempFile, VrtTempFile
from pyrasta.tools import _gdal_temp_dataset, _return_raster
from osgeo import gdal_array
import affine
import gdal
@_return_raster
def _align_raster(in_raster, out_file, on_raster):
""" Align raster on other raster
"""
out_ds = _gdal_temp_dataset(out_file, in_raster._gdal_driver,
on_raster._gdal_dataset.GetProjection(),
on_raster.x_size, on_raster.y_size, in_raster.nb_band,
on_raster.geo_transform, in_raster.data_type, in_raster.no_data)
gdal.Warp(out_ds, in_raster._gdal_dataset)
# Close dataset
out_ds = None
def _array_to_raster(raster_class, array, crs, bounds,
gdal_driver, no_data):
""" Convert array to (north up) raster
Parameters
----------
array: numpy.ndarray
crs: pyproj.CRS
bounds: tuple
Image boundaries as (xmin, ymin, xmax, ymax)
gdal_driver: osgeo.gdal.Driver
no_data
Returns
-------
"""
if array.ndim == 2:
nb_band = 1
x_size = array.shape[1]
y_size = array.shape[0]
else:
nb_band = array.shape[0]
x_size = array.shape[2]
y_size = array.shape[1]
xmin, ymin, xmax, ymax = bounds
geo_transform = (xmin, (xmax - xmin)/x_size, 0,
ymax, 0, -(ymax - ymin)/y_size)
with RasterTempFile(gdal_driver.GetMetadata()['DMD_EXTENSION']) as out_file:
out_ds = _gdal_temp_dataset(out_file.path,
gdal_driver,
crs.to_wkt(),
x_size,
y_size,
nb_band,
geo_transform,
gdal_array.NumericTypeCodeToGDALTypeCode(array.dtype),
no_data)
if nb_band == 1:
out_ds.GetRasterBand(nb_band).WriteArray(array)
else:
for band in range(nb_band):
out_ds.GetRasterBand(band + 1).WriteArray(array[band, :, :])
# Close dataset
out_ds = None
raster = raster_class(out_file.path)
raster._temp_file = out_file
return raster
@_return_raster
def _xy_to_2d_index(raster, x, y):
""" Convert x/y map coordinates to 2d index
"""
forward_transform = affine.Affine.from_gdal(*raster.geo_transform)
reverse_transform = ~forward_transform
px, py = reverse_transform * (x, y)
return int(px), int(py)
def _merge_bands(raster_class, sources, resolution, gdal_driver, data_type, no_data):
""" Merge multiple bands into one raster
"""
with RasterTempFile(gdal_driver.GetMetadata()['DMD_EXTENSION']) as out_file:
vrt_ds = gdal.BuildVRT(VrtTempFile().path, [src._gdal_dataset for src in sources],
resolution=resolution, separate=True, VRTNodata=no_data)
out_ds = gdal.Translate(out_file.path, vrt_ds, outputType=data_type)
# Close dataset
out_ds = None
return raster_class(out_file.path)
@_return_raster
def _padding(raster, out_file, pad_x, pad_y, pad_value):
""" Add pad values around raster
Description
-----------
Parameters
----------
raster: RasterBase
raster to pad
out_file: str
output file to which to write new raster
pad_x: int
x padding size (new width will therefore be RasterXSize + 2 * pad_x)
pad_y: int
y padding size (new height will therefore be RasterYSize + 2 * pad_y)
pad_value: int or float
value to set to pad area around raster
Returns
-------
"""
geo_transform = (raster.x_origin - pad_x * raster.resolution[0], raster.resolution[0], 0,
raster.y_origin + pad_y * raster.resolution[1], 0, -raster.resolution[1])
out_ds = _gdal_temp_dataset(out_file,
raster._gdal_driver,
raster._gdal_dataset.GetProjection(),
raster.x_size + 2 * pad_x,
raster.y_size + 2 * pad_y,
raster.nb_band,
geo_transform,
raster.data_type,
raster.no_data)
for band in range(1, raster.nb_band + 1):
out_ds.GetRasterBand(band).Fill(pad_value)
gdal.Warp(out_ds, raster._gdal_dataset)
# Close dataset
out_ds = None
@_return_raster
def _project_raster(raster, out_file, new_crs):
""" Project raster onto new CRS
"""
gdal.Warp(out_file, raster._gdal_dataset, dstSRS=srs_from(new_crs))
def _read_array(raster, band, bounds):
""" Read array from raster
"""
if bounds is None:
return raster._gdal_dataset.ReadAsArray()
else:
x_min, y_min, x_max, y_max = bounds
forward_transform = affine.Affine.from_gdal(*raster.geo_transform)
reverse_transform = ~forward_transform
px_min, py_max = reverse_transform * (x_min, y_min)
px_max, py_min = reverse_transform * (x_max, y_max)
x_size = int(px_max - px_min) + 1
y_size = int(py_max - py_min) + 1
if band is not None:
return raster._gdal_dataset.GetRasterBand(band).ReadAsArray(int(px_min),
int(py_min),
x_size,
y_size)
else:
return raster._gdal_dataset.ReadAsArray(int(px_min),
int(py_min),
x_size,
y_size)
def _read_value_at(raster, x, y):
""" Read value at lat/lon map coordinates
"""
forward_transform = affine.Affine.from_gdal(*raster.geo_transform)
reverse_transform = ~forward_transform
xoff, yoff = reverse_transform * (x, y)
value = raster._gdal_dataset.ReadAsArray(xoff, yoff, 1, 1)
if value.size > 1:
return value
else:
return value[0, 0]
@_return_raster
def _resample_raster(raster, out_file, factor):
""" Resample raster
Parameters
----------
raster: RasterBase
raster to resample
out_file: str
output file to which to write new raster
factor: int or float
Resampling factor
"""
geo_transform = (raster.x_origin, raster.resolution[0] / factor, 0,
raster.y_origin, 0, -raster.resolution[1] / factor)
out_ds = _gdal_temp_dataset(out_file,
raster._gdal_driver,
raster._gdal_dataset.GetProjection(),
raster.x_size * factor,
raster.y_size * factor,
raster.nb_band,
geo_transform,
raster.data_type,
raster.no_data)
for band in range(1, raster.nb_band+1):
gdal.RegenerateOverview(raster._gdal_dataset.GetRasterBand(band),
out_ds.GetRasterBand(band), 'mode')
# Close dataset
out_ds = None
@_return_raster
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
37811,
19937,
10638,
6764,
13,
198,
198,
5167,
6496,
6764,
13,
198,
37811,
198,
6738,
279,
2417,
40197,
13,
66,
3808,
1330,
264,
3808,
62,
6738,
198,
6738,
279,
2... | 1.859162 | 4,104 |
import sys, imp;
# Check if psutil is installed
try:
f, pathname, desc = imp.find_module("psutil", sys.path[1:])
except ImportError:
print("Install psutil with \"pip install --user psutil\"")
sys.exit(0)
import psutil, time, threading, ctypes # An included library with Python install.
mm = MemoryMonitor()
mm.monitor() | [
11748,
25064,
11,
848,
26,
198,
198,
2,
6822,
611,
26692,
22602,
318,
6589,
198,
28311,
25,
198,
220,
220,
220,
277,
11,
3108,
3672,
11,
1715,
796,
848,
13,
19796,
62,
21412,
7203,
862,
22602,
1600,
25064,
13,
6978,
58,
16,
25,
12... | 2.834711 | 121 |
a,b,c,d = 1,2,3,4
f= input()
if(f.count("V")%2 != 0):
a, b, c, d = b, a, d, c
if(f.count("H")%2 != 0):
a, b, c, d = c, d, a, b
print(a,b)
print(c,d)
| [
64,
11,
65,
11,
66,
11,
67,
796,
352,
11,
17,
11,
18,
11,
19,
198,
69,
28,
5128,
3419,
198,
361,
7,
69,
13,
9127,
7203,
53,
4943,
4,
17,
14512,
657,
2599,
198,
220,
257,
11,
275,
11,
269,
11,
288,
796,
275,
11,
257,
11,
... | 1.565657 | 99 |
# This work is based on original code developed and copyrighted by TNO 2020.
# Subsequent contributions are licensed to you by the developers of such code and are
# made available to the Project under one or several contributor license agreements.
#
# This work is licensed to you under the Apache License, Version 2.0.
# You may obtain a copy of the license at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Contributors:
# TNO - Initial implementation
# Manager:
# TNO
import os
EPS_WEB_HOST = os.getenv("EPS_WEB_HOST", "http://epsweb:3401")
ESDL_AGGREGATOR_HOST = os.getenv("ESDL_AGGREGATOR_HOST", "http://esdl-aggregator:3490")
esdl_config = {
"control_strategies": [
{"name": "DrivenByDemand", "applies_to": "Conversion", "connect_to": "OutPort"},
{"name": "DrivenBySupply", "applies_to": "Conversion", "connect_to": "InPort"},
{
"name": "StorageStrategy",
"applies_to": "Storage",
"parameters": [
{"name": "marginalChargeCosts", "type": "SingleValue"},
{"name": "marginalDischargeCosts", "type": "SingleValue"},
],
},
],
"predefined_quantity_and_units": [
{
"id": "eb07bccb-203f-407e-af98-e687656a221d",
"description": "Energy in GJ",
"physicalQuantity": "ENERGY",
"multiplier": "GIGA",
"unit": "JOULE",
},
{
"id": "cc224fa0-4c45-46c0-9c6c-2dba44aaaacc",
"description": "Energy in TJ",
"physicalQuantity": "ENERGY",
"multiplier": "TERRA",
"unit": "JOULE",
},
{
"id": "e9405fc8-5e57-4df5-8584-4babee7cdf1a",
"description": "Power in kW",
"physicalQuantity": "POWER",
"multiplier": "KILO",
"unit": "WATT",
},
{
"id": "e9405fc8-5e57-4df5-8584-4babee7cdf1b",
"description": "Power in MW",
"physicalQuantity": "POWER",
"multiplier": "MEGA",
"unit": "WATT",
},
{
"id": "e9405fc8-5e57-4df5-8584-4babee7cdf1c",
"description": "Power in VA",
"physicalQuantity": "POWER",
"unit": "VOLT_AMPERE",
},
{
"id": "6279c72a-228b-4c2c-8924-6b794c81778c",
"description": "Reactive power in VAR",
"physicalQuantity": "POWER",
"unit": "VOLT_AMPERE_REACTIVE",
},
],
"predefined_esdl_services": [
{
"id": "18d106cf-2af1-407d-8697-0dae23a0ac3e",
"name": "Get PICO wind potential",
"explanation": "This queries the Geodan wind potential service for a certain area",
"url": "https://pico.geodan.nl/pico/api/v1/<area_scope>/<area_id>/windturbinegebied",
"http_method": "get",
"headers": {
"Accept": "application/esdl+xml",
"User-Agent": "ESDL Mapeditor/0.1",
},
"type": "geo_query",
"result": [{"code": 200, "action": "esdl"}],
"geographical_scope": {
"url_area_scope": "<area_scope>",
"url_area_id": "<area_id>",
"area_scopes": [
{"scope": "PROVINCE", "url_value": "provincies"},
{"scope": "REGION", "url_value": "resgebieden"},
{"scope": "MUNICIPALITY", "url_value": "gemeenten"},
],
},
"query_parameters": [
{
"name": "Distance to buildings",
"description": "Minimum distance to the built environment (in meters)",
"parameter_name": "bebouwingsafstand",
"type": "integer",
},
{
"name": "Restriction",
"description": "",
"parameter_name": "restrictie",
"type": "multi-selection",
"possible_values": [
"natuur",
"vliegveld",
"infrastructuur",
"agrarisch",
"turbines",
],
},
{
"name": "Preference",
"description": "",
"parameter_name": "preferentie",
"type": "multi-selection",
"possible_values": [
"natuur",
"vliegveld",
"infrastructuur",
"agrarisch",
"turbines",
],
},
{
"name": "Include geometry in ESDL",
"description": "",
"parameter_name": "geometrie",
"type": "boolean",
},
],
},
{
"id": "50fa716f-f3b0-464c-bf9f-1acffb24f76a",
"name": "Get PICO solar field potential",
"explanation": "This queries the Geodan solar field potential service for a certain area",
"url": "https://pico.geodan.nl/pico/api/v1/<area_scope>/<area_id>/zonneveldgebied",
"http_method": "get",
"headers": {
"Accept": "application/esdl+xml",
"User-Agent": "ESDL Mapeditor/0.1",
},
"type": "geo_query",
"result": [{"code": 200, "action": "esdl"}],
"geographical_scope": {
"url_area_scope": "<area_scope>",
"url_area_id": "<area_id>",
"area_scopes": [
{"scope": "PROVINCE", "url_value": "provincies"},
{"scope": "REGION", "url_value": "resgebieden"},
{"scope": "MUNICIPALITY", "url_value": "gemeenten"},
],
},
"query_parameters": [
{
"name": "Distance to buildings (m)",
"description": "Minimum distance to the built environment (in meters)",
"parameter_name": "bebouwingsafstand",
"type": "integer",
},
{
"name": "Restriction",
"description": "",
"parameter_name": "restrictie",
"type": "multi-selection",
"possible_values": [
"natuur",
"vliegveld",
"infrastructuur",
"agrarisch",
"turbines",
],
},
{
"name": "Preference",
"description": "",
"parameter_name": "preferentie",
"type": "multi-selection",
"possible_values": [
"natuur",
"vliegveld",
"infrastructuur",
"agrarisch",
"turbines",
],
},
{
"name": "Include geometry in ESDL",
"description": "",
"parameter_name": "geometrie",
"type": "boolean",
},
],
},
{
"id": "c1c209e9-67ff-4201-81f6-0dd7a185ff06",
"name": "Get PICO rooftop solar potential",
"explanation": "This queries the Geodan rooftop solar potential service for a certain area",
"url": "https://pico.geodan.nl/pico/api/v1/<area_scope>/<area_id>/zonopdak?geometrie=false",
"http_method": "get",
"headers": {
"Accept": "application/esdl+xml",
"User-Agent": "ESDL Mapeditor/0.1",
},
"type": "geo_query",
"result": [{"code": 200, "action": "esdl"}],
"geographical_scope": {
"url_area_scope": "<area_scope>",
"url_area_id": "<area_id>",
"area_scopes": [
{"scope": "PROVINCE", "url_value": "provincies"},
{"scope": "REGION", "url_value": "resgebieden"},
{"scope": "MUNICIPALITY", "url_value": "gemeenten"},
],
},
"query_parameters": [],
},
{
"id": "42c584b1-43c1-4369-9001-c89ba80d8370",
"name": "Get PICO Startanalyse results",
"explanation": "This queries the Geodan start analyse service for a certain area",
"url": "https://pico.geodan.nl/pico/api/v1/<area_scope>/<area_id>/startanalyse",
"http_method": "get",
"headers": {
"Accept": "application/esdl+xml",
"User-Agent": "ESDL Mapeditor/0.1",
},
"type": "geo_query",
"result": [{"code": 200, "action": "esdl"}],
"geographical_scope": {
"url_area_scope": "<area_scope>",
"url_area_id": "<area_id>",
"area_scopes": [
{"scope": "MUNICIPALITY", "url_value": "gemeenten"},
{"scope": "NEIGHBOURHOOD", "url_value": "buurt"},
],
},
"query_parameters": [
{
"name": "Strategie",
"description": "",
"parameter_name": "strategie",
"type": "selection",
"possible_values": [
"S1a",
"S1b",
"S2a",
"S2b",
"S2c",
"S2d",
"S3a",
"S3b",
"S3c",
"S3d",
"S4a",
"S5a",
],
}
],
},
{
"id": "7f8722a9-669c-499d-8d75-4a1960e0429f",
"name": "Create ETM scenario",
"explanation": "This service sends the ESDL information to the ETM and tries to generate an ETM scenario out of it.",
"url": "http://beta-esdl.energytransitionmodel.com/api/v1/EnergySystem/",
# "url": "http://localhost:5000/api/v1/EnergySystem/",
"http_method": "post",
"headers": {"Content-Type": "application/x-www-form-urlencoded"},
"type": "send_esdl",
"body": "url_encoded",
"send_email_in_post_body_parameter": "account",
"query_parameters": [
{
"name": "Environment",
"description": "",
"parameter_name": "environment",
"location": "body",
"type": "selection",
"possible_values": ["pro", "beta"],
}
],
"result": [{"code": 200, "action": "print"}],
},
{
"id": "912c4a2b-8eee-46f7-a225-87c5f85e645f",
"name": "ESDL Validator",
"explanation": "This service allows you validate an ESDL against a certain schema",
"type": "vueworkflow",
"workflow": [
{
"name": "Select schema",
"description": "",
"type": "select-query",
"multiple": False,
"source": {
"url": "http://10.30.2.1:3011/schema",
"http_method": "get",
"label_fields": ["name"],
"value_field": "id",
},
"target_variable": "schema",
"next_step": 1,
},
{
"name": "Schema validation",
"description": "",
"type": "service",
"state_params": {"schemas": "schema.id"},
"service": {
"id": "64c9d1a2-c92a-46ed-a7e4-9931971cbb27",
"name": "Validate ESDL against scehema",
"headers": {
"User-Agent": "ESDL Mapeditor/0.1",
"Content-Type": "application/xml",
},
"url": "http://10.30.2.1:3011/validationToMessages/",
"http_method": "post",
"type": "send_esdl",
"query_parameters": [
{
"name": "Schemas",
"description": "ID of the schema to validate this ESDL against",
"parameter_name": "schemas",
}
],
"body": "",
"result": [{"code": 200, "action": "asset_feedback"}],
"with_jwt_token": False,
"state_params": True,
},
},
],
},
],
"role_based_esdl_services": {
"eps": [
{
"id": "9951c271-f9b6-4c4e-873f-b309dff19e03",
"name": "Energy Potential Scan",
"explanation": "This workflow allows you to run the EPS web service and view the EPS results.",
"type": "vueworkflow",
"workflow": [
{
# 0
"name": "Begin",
"description": "How would you like to proceed?",
"type": "choice",
"options": [
{
"name": "Create a new EPS project",
"next_step": 1,
"type": "primary",
},
{
"name": "Adjust EPS input",
"next_step": 13,
"type": "default",
},
{"name": "Run EPS", "next_step": 4, "type": "primary"},
{
"name": "Inspect EPS results",
"next_step": 6,
"type": "primary",
},
{
"name": "Aggregate ESDL buildings for ESSIM",
"next_step": 12,
"type": "default",
},
],
},
{
# 1
"name": "Create Project",
"description": "",
"type": "custom",
"component": "eps-create-project",
"url": f"{EPS_WEB_HOST}/api/projects/",
"next_step": 0,
},
{
# 2
"name": "Select existing project",
"description": "Please select the project for which you would like to upload a project file.",
"type": "select-query",
"multiple": False,
"source": {
"url": f"{EPS_WEB_HOST}/api/projects/",
"http_method": "get",
"choices_attr": "projects",
"label_fields": ["name"],
"value_field": "id",
},
"target_variable": "project_id",
"next_step": 3,
},
{
# 3
"name": "Upload project file",
"description": "Note: When uploading a project file with the same name as a previous project "
"file, the previous file will be overwritten!",
"type": "upload_file",
"target": {
"url": f"{EPS_WEB_HOST}/api/uploads/",
"request_params": {"project_id": "project.id"},
"response_params": {"name": "file_name"},
},
"next_step": 0,
},
{
# 4
"name": "Select existing project",
"description": "",
"type": "select-query",
"multiple": False,
"source": {
"url": f"{EPS_WEB_HOST}/api/projects/",
"http_method": "get",
"choices_attr": "projects",
"label_fields": ["name"],
"value_field": "id",
},
"target_variable": "project",
"next_step": 5,
},
{
# 5
"name": "Run the EPS",
"description": "",
"type": "custom",
"component": "eps-service",
"url": f"{EPS_WEB_HOST}/api/eps/",
"target": {
"request_params": {"project_id": "project.id"},
"user_response_spec": {
"0": {"message": "Failed starting the EPS."},
"200": {
"message": "EPS started successfully! It can take up to 45 minutes for the EPS to complete. When it is complete, the results can be found under 'Inspect results'."
},
"429": {
"message": "It is currently busy on the server. We cannot start an EPS execution "
"at this time. Please try again at a later time. "
},
},
},
},
{
# 6
"name": "EPS execution",
"description": "",
"label": "Select EPS execution to inspect:",
"type": "select-query",
"multiple": False,
"source": {
"url": f"{EPS_WEB_HOST}/api/eps/",
"http_method": "get",
"choices_attr": "executions",
"label_fields": ["project", "id", "success"],
"value_field": "id",
},
"target_variable": "execution",
"next_step": 7,
},
{
# 7
"name": "Execution selected",
"description": "How would you like to proceed?",
"type": "choice",
"options": [
{
"name": "Load EPS result",
"descriptipn": "Load the results as ESDL on the map. Your current layers will be overwritten!",
"type": "primary",
"enable_if_state": "execution.success",
"next_step": 10,
},
{
"name": "Inspect EPS results",
"type": "default",
"enable_if_state": "execution.success",
"next_step": 11,
},
{
"name": "Download project file",
"type": "default",
"next_step": 9,
},
# {
# "name": "View progress",
# "type": "default",
# "disable_if_state": "execution.finished_on",
# "next_step": 8,
# },
],
},
{
# 8
"name": "EPS execution progress",
"description": "",
"type": "progress",
"refresh": 30,
"source": {
"url": f"{EPS_WEB_HOST}/api/eps/progress",
"request_params": {"execution_id": "execution.id"},
"progress_field": "latest_progress",
"message_field": "latest_message",
},
},
{
# 9
"name": "Download project file",
"description": "The project file that was used as input to perform this EPS analysis can be "
"downloaded here.",
"type": "download_file",
"source": {
"url": EPS_WEB_HOST + "/api/eps/{execution_id}/input",
"request_params": {"execution_id": "execution.id"},
},
},
{
# 10
"name": "Load EPS results",
"description": "Please wait a moment while we load an ESDL with the EPS results. When the EPS "
"is loaded, please continue.",
"type": "service",
"state_params": {"execution_id": "execution.id"},
"service": {
"id": "9bd2f969-f240-4b26-ace5-2e03fbc04b12",
"name": "Visualize EPS",
"headers": {
"Accept": "application/esdl+xml",
"User-Agent": "ESDL Mapeditor/0.1",
},
"url": f"{EPS_WEB_HOST}/api/eps/<execution_id>/esdl",
"auto": True,
"clearLayers": True,
"http_method": "get",
"type": "",
"result": [{"code": 200, "action": "esdl"}],
"query_parameters": [
{
"name": "File Name",
"location": "url",
"parameter_name": "execution_id",
}
],
"with_jwt_token": True,
"state_params": True,
}
},
{
# 11
"name": "Inspect EPS results",
"description": "",
"type": "custom",
"component": "eps-inspect-result",
"custom_data": {
"url": EPS_WEB_HOST
+ "/api/eps/{execution_id}/pand/{pand_bagid}"
},
},
{
# 12
"name": "Aggregate ESDL buildings for ESSIM",
"description": "The ESDL generated by the EPS contains every building individually. This "
"causes unnecessarily long processing time if buildings have the same "
"profiles. With this service, similar buildings are combined into aggregated "
"buildings, which will make it faster to run ESSIM and easier to interpret "
"results. Note: This will create a new ESDL layer.",
"type": "service",
"service": {
"id": "9bd2f969-f240-4b26-ace5-2e03fbc04b13",
"name": "Aggregate ESDL buildings for ESSIM",
"headers": {
"Content-Type": "application/json",
"User-Agent": "ESDL Mapeditor/0.1",
},
"type": "send_esdl_json",
"body": "base64_encoded",
"url": f"{ESDL_AGGREGATOR_HOST}/aggregate",
"http_method": "post",
"result": [{"code": 200, "action": "esdl"}],
"with_jwt_token": True,
},
"next_step": 0,
},
{
# 13
"name": "Adjust EPS input",
"description": "",
"type": "choice",
"options": [
{
"name": "Download project file",
"description": "If you want to inspect the KvK data or modify input data, you can download a project file.",
"next_step": 14,
"type": "primary",
},
{
"name": "Upload project file",
"description": "A project file can be uploaded to serve as input for a new EPS run.",
"next_step": 2,
"type": "primary",
},
],
},
{
# 14
"name": "Select existing project",
"description": "Please select the project for which you would like to download a project file.",
"type": "select-query",
"multiple": False,
"source": {
"url": f"{EPS_WEB_HOST}/api/projects/",
"http_method": "get",
"choices_attr": "projects",
"label_fields": ["name"],
"value_field": "id",
},
"target_variable": "project",
"next_step": 15,
},
{
# 15
"name": "Select project file",
"description": "Please select the project file you would like to download.",
"type": "select-query",
"multiple": False,
"source": {
"url": EPS_WEB_HOST + "/api/projects/{project_id}/files",
"request_params": {"project_id": "project.id"},
"http_method": "get",
"choices_attr": "file_names",
"label_fields": ["name"],
"value_field": "id",
},
"target_variable": "file_name",
"next_step": 16,
},
{
# 16
"name": "Download project file",
"description": "By clicking the button below you can download the selected project file.",
"type": "download_file",
"source": {
"url": EPS_WEB_HOST
+ "/api/projects/{project_id}/files/{file_name}",
"request_params": {
"project_id": "project.id",
"file_name": "file_name.id",
},
},
"next_step": 0,
},
],
}
]
},
}
| [
2,
220,
770,
670,
318,
1912,
319,
2656,
2438,
4166,
290,
33696,
416,
309,
15285,
12131,
13,
198,
2,
220,
3834,
44399,
9284,
389,
11971,
284,
345,
416,
262,
6505,
286,
884,
2438,
290,
389,
198,
2,
220,
925,
1695,
284,
262,
4935,
73... | 1.538636 | 19,011 |
import os
import json
import copy
import pype.api
from avalon import io
PSDImage = None
| [
11748,
28686,
198,
11748,
33918,
198,
11748,
4866,
198,
11748,
279,
2981,
13,
15042,
198,
6738,
37441,
261,
1330,
33245,
198,
198,
3705,
35,
5159,
796,
6045,
628
] | 3.214286 | 28 |
__author__ = 'tiantong'
| [
834,
9800,
834,
796,
705,
83,
3014,
506,
6,
198
] | 2.4 | 10 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'procstep.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
2,
5178,
7822,
7560,
422,
3555,
334,
72,
2393,
705,
36942,
9662,
13,
9019,
6,
198,
2,
198,
2,
15622,
416,
25,
9485,
48,
83,
20,
12454,
2438,
17301,
642,
13,
2... | 2.433333 | 180 |
import collections
import contextlib
import cProfile
import inspect
import gc
import multiprocessing
import os
import random
import sys
import time
import unittest
import warnings
from io import StringIO
from unittest import result, runner, signals, suite, loader, case
from .loader import TestLoader
from numba.core import config
try:
from multiprocessing import TimeoutError
except ImportError:
from Queue import Empty as TimeoutError
def make_tag_decorator(known_tags):
"""
Create a decorator allowing tests to be tagged with the *known_tags*.
"""
def tag(*tags):
"""
Tag a test method with the given tags.
Can be used in conjunction with the --tags command-line argument
for runtests.py.
"""
for t in tags:
if t not in known_tags:
raise ValueError("unknown tag: %r" % (t,))
return decorate
return tag
def cuda_sensitive_mtime(x):
"""
Return a key for sorting tests bases on mtime and test name. For CUDA
tests, interleaving tests from different classes is dangerous as the CUDA
context might get reset unexpectedly between methods of a class, so for
CUDA tests the key prioritises the test module and class ahead of the
mtime.
"""
cls = x.__class__
key = str(os.path.getmtime(inspect.getfile(cls))) + str(x)
from numba.cuda.testing import CUDATestCase
if CUDATestCase in cls.mro():
key = "%s.%s %s" % (str(cls.__module__), str(cls.__name__), key)
return key
def parse_slice(useslice):
"""Parses the argument string "useslice" as the arguments to the `slice()`
constructor and returns a slice object that's been instantiated with those
arguments. i.e. input useslice="1,20,2" leads to output `slice(1, 20, 2)`.
"""
try:
l = {}
exec("sl = slice(%s)" % useslice, l)
return l['sl']
except Exception:
msg = ("Expected arguments consumable by 'slice' to follow "
"option `-j`, found '%s'" % useslice)
raise ValueError(msg)
class TestLister(object):
"""Simply list available tests rather than running them."""
class SerialSuite(unittest.TestSuite):
"""A simple marker to make sure tests in this suite are run serially.
Note: As the suite is going through internals of unittest,
it may get unpacked and stuffed into a plain TestSuite.
We need to set an attribute on the TestCase objects to
remember they should not be run in parallel.
"""
# "unittest.main" is really the TestProgram class!
# (defined in a module named itself "unittest.main"...)
class NumbaTestProgram(unittest.main):
"""
A TestProgram subclass adding the following options:
* a -R option to enable reference leak detection
* a --profile option to enable profiling of the test run
* a -m option for parallel execution
* a -l option to (only) list tests
Currently the options are only added in 3.4+.
"""
refleak = False
profile = False
multiprocess = False
useslice = None
list = False
tags = None
exclude_tags = None
random_select = None
random_seed = 42
# These are tests which are generated and injected into the test suite, what
# gets injected depends on features of the test environment, e.g. TBB presence
# it's important for doing the CI "slice tests" that these are run at the end
# See notes in `_flatten_suite` for why. Simple substring matching is used to
# determine a match.
_GENERATED = (
"numba.cuda.tests.cudapy.test_libdevice.TestLibdeviceCompilation",
"numba.tests.test_num_threads",
"numba.tests.test_parallel_backend",
"numba.tests.test_svml",
"numba.tests.test_ufuncs",
)
def _flatten_suite_inner(test):
"""
Workhorse for _flatten_suite
"""
tests = []
if isinstance(test, (unittest.TestSuite, list, tuple)):
for x in test:
tests.extend(_flatten_suite_inner(x))
else:
tests.append(test)
return tests
def _flatten_suite(test):
"""
Expand nested suite into list of test cases.
"""
tests = _flatten_suite_inner(test)
# Strip out generated tests and stick them at the end, this is to make sure
# that tests appear in a consistent order regardless of features available.
# This is so that a slice through the test suite e.g. (1::N) would likely be
# consistent up to the point of the generated tests, which rely on specific
# features.
generated = set()
for t in tests:
for g in _GENERATED:
if g in str(t):
generated.add(t)
normal = set(tests) - generated
tests = sorted(normal, key=key)
tests.extend(sorted(list(generated), key=key))
return tests
def _choose_tagged_tests(tests, tags, mode='include'):
"""
Select tests that are tagged/not tagged with at least one of the given tags.
Set mode to 'include' to include the tests with tags, or 'exclude' to
exclude the tests with the tags.
"""
selected = []
tags = set(tags)
for test in _flatten_suite(tests):
assert isinstance(test, unittest.TestCase)
func = getattr(test, test._testMethodName)
try:
# Look up the method's underlying function (Python 2)
func = func.im_func
except AttributeError:
pass
found_tags = getattr(func, 'tags', None)
# only include the test if the tags *are* present
if mode == 'include':
if found_tags is not None and found_tags & tags:
selected.append(test)
elif mode == 'exclude':
# only include the test if the tags *are not* present
if found_tags is None or not (found_tags & tags):
selected.append(test)
else:
raise ValueError("Invalid 'mode' supplied: %s." % mode)
return unittest.TestSuite(selected)
def _choose_random_tests(tests, ratio, seed):
"""
Choose a given proportion of tests at random.
"""
rnd = random.Random()
rnd.seed(seed)
if isinstance(tests, unittest.TestSuite):
tests = _flatten_suite(tests)
tests = rnd.sample(tests, int(len(tests) * ratio))
tests = sorted(tests, key=lambda case: case.id())
return unittest.TestSuite(tests)
# The reference leak detection code is liberally taken and adapted from
# Python's own Lib/test/regrtest.py.
class ParallelTestResult(runner.TextTestResult):
"""
A TestResult able to inject results from other results.
"""
def add_results(self, result):
"""
Add the results from the other *result* to this result.
"""
self.stream.write(result.stream.getvalue())
self.stream.flush()
self.testsRun += result.testsRun
self.failures.extend(result.failures)
self.errors.extend(result.errors)
self.skipped.extend(result.skipped)
self.expectedFailures.extend(result.expectedFailures)
self.unexpectedSuccesses.extend(result.unexpectedSuccesses)
class _MinimalResult(object):
"""
A minimal, picklable TestResult-alike object.
"""
__slots__ = (
'failures', 'errors', 'skipped', 'expectedFailures',
'unexpectedSuccesses', 'stream', 'shouldStop', 'testsRun',
'test_id')
def fixup_case(self, case):
"""
Remove any unpicklable attributes from TestCase instance *case*.
"""
# Python 3.3 doesn't reset this one.
case._outcomeForDoCleanups = None
class _FakeStringIO(object):
"""
A trivial picklable StringIO-alike for Python 2.
"""
class _MinimalRunner(object):
"""
A minimal picklable object able to instantiate a runner in a
child process and run a test case with it.
"""
# Python 2 doesn't know how to pickle instance methods, so we use __call__
# instead.
@contextlib.contextmanager
def cleanup_object(self, test):
"""
A context manager which cleans up unwanted attributes on a test case
(or any other object).
"""
vanilla_attrs = set(test.__dict__)
try:
yield test
finally:
spurious_attrs = set(test.__dict__) - vanilla_attrs
for name in spurious_attrs:
del test.__dict__[name]
def _split_nonparallel_tests(test, sliced=slice(None)):
"""
Split test suite into parallel and serial tests.
"""
ptests = []
stests = []
flat = _flatten_suite(test)[sliced]
for t in flat:
if is_parallelizable_test_case(t):
ptests.append(t)
else:
stests.append(t)
return ptests, stests
# A test can't run longer than 10 minutes
_TIMEOUT = 600
class ParallelTestRunner(runner.TextTestRunner):
"""
A test runner which delegates the actual running to a pool of child
processes.
"""
resultclass = ParallelTestResult
timeout = _TIMEOUT
| [
11748,
17268,
198,
11748,
4732,
8019,
198,
11748,
269,
37046,
198,
11748,
10104,
198,
11748,
308,
66,
198,
11748,
18540,
305,
919,
278,
198,
11748,
28686,
198,
11748,
4738,
198,
11748,
25064,
198,
11748,
640,
198,
11748,
555,
715,
395,
... | 2.615988 | 3,440 |
# -*- coding: utf-8 -*-
"""
This example demonstrates how solutions to the TOA calibration
problem may be found using multi-dimensional scaling. The example
sets 10 anchors in space and the recreates their position based
on their mutual distances and a set of constraints
"""
import matplotlib.pylab as plt
import numpy as np
import utilities as util
from classes import AnchorCalibrator
from mpl_toolkits.mplot3d import Axes3D, proj3d
import sys
# True data
numberOfAnchors = 20
anchors = np.array([[1, 8, 8],
[0, 0, 0],
[2, 6, 3],
[2, 2, 3],
[6, 2, 3],
[5, 6, 7],
[0, 2, 4],
[2, 5, 3],
[2, 4, 3],
[3, 5, 6],
[2, 9, 9],
[1, 1, 1],
[3, 7, 4],
[3, 3, 4],
[7, 3, 4],
[6, 7, 8],
[1, 3, 5],
[3, 6, 4],
[3, 5, 4],
[4, 6, 5]])
# Define an anchor calibrator object
calibrator = AnchorCalibrator(numberOfAnchors)
if len(sys.argv) == 1:
print 'Provide a string argument, either "true" or "noisy".'
else:
if sys.argv[1] == 'true':
# Here we assume perfect knowledge of the distances between the anchors
Dsq = util.get_distance_matrix_squared(anchors)
calibrator.set_distance_matrix_squared(Dsq)
elif sys.argv[1] == 'noisy':
# Include measurements as the come
for ii in range(10000):
i = np.random.randint(20)
j = np.random.randint(20)
if i != j:
noise = np.random.normal(0.01,0.01)
distance = np.linalg.norm(anchors[i,:] - anchors[j,:]) + noise
dataPoint = ((i, j), distance)
# include new data
calibrator.include_data_point(dataPoint)
# Process data
calibrator.process_data()
# The index of the point which is to be the origin in the estimated coordinates
origin = 1
calibrator.set_origin(1)
# A three nodes spanning a plane (here xy) used to determine the z-axis safely
plane = ((2,3,4),'xy') # from 2 to 3
calibrator.set_plane(plane)
# A two nodes residing on the same unit axis (here x)
axis = ((3,2),'y') # from index 3 to index 2
calibrator.set_axis(axis)
# mirror
normal = ((3,4),'x') # from index 3 to index 4
calibrator.set_mirror(normal)
# Calibrate
calibrator()
# Extract estimate
estimate = calibrator.anchorPositions
# TODO add one more constraint to mirror correctly
#estimate[:,0] *= -1.0;
###############################################################################
### plot true and estimated anchors, compute residual ###
###############################################################################
fig = plt.figure(1)
util.plot_anchors(anchors,
fig, 121, 'True anchor positions', 'red')
util.plot_anchors(estimate,
fig, 122, 'Estimated anchor positions', 'green')
print "Residual accross all anchors: {0:.17f}".format(np.linalg.norm(estimate - anchors))
plt.show() | [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
37811,
198,
1212,
1672,
15687,
703,
8136,
284,
262,
5390,
32,
36537,
198,
45573,
743,
307,
1043,
1262,
5021,
12,
19577,
20796,
13,
383,
1672,
198,
28709,
838,
43360,
287... | 2.087011 | 1,609 |
# Copyright 2014 Red Hat, 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova.objects import base as obj_base
from nova.objects import fields
EVENT_NAMES = [
# Network has changed for this instance, rebuild info_cache
'network-changed',
# VIF plugging notifications, tag is port_id
'network-vif-plugged',
'network-vif-unplugged',
'network-vif-deleted',
]
EVENT_STATUSES = ['failed', 'completed', 'in-progress']
# TODO(berrange): Remove NovaObjectDictCompat
@obj_base.NovaObjectRegistry.register
| [
2,
220,
220,
220,
15069,
1946,
2297,
10983,
11,
3457,
13,
198,
2,
198,
2,
220,
220,
220,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
345,
743,
198,
2,
220,
220,
220,
407,
779,
428,
2393,
... | 3.089855 | 345 |
#!/usr/bin/env python3
from irrp_with_class import IRRP
irrp = IRRP(gpio=18, filename="codes", post=130, no_confirm=True)
irrp.record("light:on")
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
198,
6738,
4173,
81,
79,
62,
4480,
62,
4871,
1330,
14826,
20031,
628,
198,
343,
81,
79,
796,
14826,
20031,
7,
31197,
952,
28,
1507,
11,
29472,
2625,
40148,
1600,
1281,
28,
12952,... | 2.365079 | 63 |
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
"""Pipeline parameters and conditions for workflow."""
from __future__ import absolute_import
from enum import Enum
from typing import List
import attr
from sagemaker.workflow.entities import Entity, DefaultEnumMeta, RequestType
DEFAULT_BACKOFF_RATE = 2.0
DEFAULT_INTERVAL_SECONDS = 1
MAX_ATTEMPTS_CAP = 20
MAX_EXPIRE_AFTER_MIN = 14400
class StepExceptionTypeEnum(Enum, metaclass=DefaultEnumMeta):
"""Step ExceptionType enum."""
SERVICE_FAULT = "Step.SERVICE_FAULT"
THROTTLING = "Step.THROTTLING"
class SageMakerJobExceptionTypeEnum(Enum, metaclass=DefaultEnumMeta):
"""SageMaker Job ExceptionType enum."""
INTERNAL_ERROR = "SageMaker.JOB_INTERNAL_ERROR"
CAPACITY_ERROR = "SageMaker.CAPACITY_ERROR"
RESOURCE_LIMIT = "SageMaker.RESOURCE_LIMIT"
@attr.s
class RetryPolicy(Entity):
"""RetryPolicy base class
Attributes:
backoff_rate (float): The multiplier by which the retry interval increases
during each attempt (default: 2.0)
interval_seconds (int): An integer that represents the number of seconds before the
first retry attempt (default: 1)
max_attempts (int): A positive integer that represents the maximum
number of retry attempts. (default: None)
expire_after_mins (int): A positive integer that represents the maximum minute
to expire any further retry attempt (default: None)
"""
backoff_rate: float = attr.ib(default=DEFAULT_BACKOFF_RATE)
interval_seconds: int = attr.ib(default=DEFAULT_INTERVAL_SECONDS)
max_attempts: int = attr.ib(default=None)
expire_after_mins: int = attr.ib(default=None)
@backoff_rate.validator
def validate_backoff_rate(self, _, value):
"""Validate the input back off rate type"""
if value:
assert value >= 0.0, "backoff_rate should be non-negative"
@interval_seconds.validator
def validate_interval_seconds(self, _, value):
"""Validate the input interval seconds"""
if value:
assert value >= 0.0, "interval_seconds rate should be non-negative"
@max_attempts.validator
def validate_max_attempts(self, _, value):
"""Validate the input max attempts"""
if value:
assert (
MAX_ATTEMPTS_CAP >= value >= 1
), f"max_attempts must in range of (0, {MAX_ATTEMPTS_CAP}] attempts"
@expire_after_mins.validator
def validate_expire_after_mins(self, _, value):
"""Validate expire after mins"""
if value:
assert (
MAX_EXPIRE_AFTER_MIN >= value >= 0
), f"expire_after_mins must in range of (0, {MAX_EXPIRE_AFTER_MIN}] minutes"
def to_request(self) -> RequestType:
"""Get the request structure for workflow service calls."""
if (self.max_attempts is None) == self.expire_after_mins is None:
raise ValueError("Only one of [max_attempts] and [expire_after_mins] can be given.")
request = {
"BackoffRate": self.backoff_rate,
"IntervalSeconds": self.interval_seconds,
}
if self.max_attempts:
request["MaxAttempts"] = self.max_attempts
if self.expire_after_mins:
request["ExpireAfterMin"] = self.expire_after_mins
return request
class StepRetryPolicy(RetryPolicy):
"""RetryPolicy for a retryable step. The pipeline service will retry
`sagemaker.workflow.retry.StepRetryExceptionTypeEnum.SERVICE_FAULT` and
`sagemaker.workflow.retry.StepRetryExceptionTypeEnum.THROTTLING` regardless of
pipeline step type by default. However, for step defined as retryable, you can override them
by specifying a StepRetryPolicy.
Attributes:
exception_types (List[StepExceptionTypeEnum]): the exception types to match for this policy
backoff_rate (float): The multiplier by which the retry interval increases
during each attempt (default: 2.0)
interval_seconds (int): An integer that represents the number of seconds before the
first retry attempt (default: 1)
max_attempts (int): A positive integer that represents the maximum
number of retry attempts. (default: None)
expire_after_mins (int): A positive integer that represents the maximum minute
to expire any further retry attempt (default: None)
"""
def to_request(self) -> RequestType:
"""Gets the request structure for retry policy."""
request = super().to_request()
request["ExceptionType"] = [e.value for e in self.exception_types]
return request
def __hash__(self):
"""Hash function for StepRetryPolicy types"""
return hash(tuple(self.to_request()))
class SageMakerJobStepRetryPolicy(RetryPolicy):
"""RetryPolicy for exception thrown by SageMaker Job.
Attributes:
exception_types (List[SageMakerJobExceptionTypeEnum]):
The SageMaker exception to match for this policy. The SageMaker exceptions
captured here are the exceptions thrown by synchronously
creating the job. For instance the resource limit exception.
failure_reason_types (List[SageMakerJobExceptionTypeEnum]): the SageMaker
failure reason types to match for this policy. The failure reason type
is presented in FailureReason field of the Describe response, it indicates
the runtime failure reason for a job.
backoff_rate (float): The multiplier by which the retry interval increases
during each attempt (default: 2.0)
interval_seconds (int): An integer that represents the number of seconds before the
first retry attempt (default: 1)
max_attempts (int): A positive integer that represents the maximum
number of retry attempts. (default: None)
expire_after_mins (int): A positive integer that represents the maximum minute
to expire any further retry attempt (default: None)
"""
def to_request(self) -> RequestType:
"""Gets the request structure for retry policy."""
request = super().to_request()
request["ExceptionType"] = [e.value for e in self.exception_type_list]
return request
def __hash__(self):
"""Hash function for SageMakerJobStepRetryPolicy types"""
return hash(tuple(self.to_request()))
| [
2,
15069,
6186,
13,
785,
11,
3457,
13,
393,
663,
29116,
13,
1439,
6923,
33876,
13,
198,
2,
198,
2,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
11074,
921,
198,
2,
743,
407,
779,
428,
2393,
2845,
... | 2.737461 | 2,552 |
import pandas as pd
import os
import re
# function to procure the absolute path of the file to be read
if __name__ == "__main__":
# Table 1 - Current In-Place Rents #
# tab seperated file - hence named with .tsv extension
rev_fname = r'source/rev_curr_inplace_rents_inp.tsv'
rev_fpath = get_file_path(rev_fname)
# read the source data and generate the calculated fields
process_rev_data(rev_fpath)
# Table 2 - Post-Renovation Rents #
renov_data_fname = r'rev_curr_inplace_rents_op.csv'
renov_data_fpath = get_file_path(renov_data_fname)
process_post_renov_rent(renov_data_fpath)
| [
11748,
19798,
292,
355,
279,
67,
198,
11748,
28686,
198,
11748,
302,
628,
198,
2,
2163,
284,
23364,
262,
4112,
3108,
286,
262,
2393,
284,
307,
1100,
628,
220,
220,
220,
220,
628,
198,
220,
220,
220,
220,
628,
628,
198,
198,
361,
1... | 2.52549 | 255 |
__all__ = ['Fit_Motion','FitFunction_Motion','FitFunction_Motion_Scandir','Jacobian_Motion',\
'Jacobian_Motion_Scandir','Partial_Motion_no_Mass','Jac_Motion_Index' ]
from scipy.optimize import least_squares
import numpy as np
from MLG.Microlensing.const import const_Einsteinradius
from MLG.StellarMotion import getSun,t_0,stars_position_micro
from MLG.Math import sindeg,cosdeg, unitFac
import time
def Fit_Motion(obs,num_vec, time_vec,obs_error = None, sc_scandir = None, loc_vec = None, unit_obs = 'deg', \
unit_pos = 'deg', unit_pm = 'mas/yr', unit_px = 'mas', exact = False,**kwargs):
'''------------------------------------------------------------
Description:
---------------------------------------------------------------
Input:
---------------------------------------------------------------
Output:
------------------------------------------------------------'''
obs_error = None
if obs_error is None:
obs_error = np.ones(len(num_vec))
# translate units from and to mas
unit_pos_fac = unitFac('mas',unit_pos)
unit_pm_fac = unitFac('mas',unit_pm)
unit_px_fac = unitFac('mas',unit_px)
unit_obs_fac = unitFac(unit_obs, 'mas')
# calculate earth vector
# calculate sin(ra),cos(ra),sin(dec),cos(dec)
scsc = sindeg(obs[0,0] * unit_obs_fac / 3.6e6) , cosdeg(obs[0,0] * unit_obs_fac / 3.6e6),\
sindeg(obs[0,1] * unit_obs_fac / 3.6e6) , cosdeg(obs[0,1] * unit_obs_fac / 3.6e6)
if loc_vec is None:
earth = getSun(t_0 + time_vec)
loc_vec = np.stack([(scsc[0] * earth[0] - scsc[1] * earth[1])/ max(scsc[3], 1e-6),\
scsc[1] * scsc[2] * earth[0] + scsc[0] * scsc[2] * earth[1] - scsc[3] * earth[2]]).T
#switch to relative coordinates by subtracting ra0,dec0 (first observation)
radec_0 = obs[0,:]
obs_rel = (obs - radec_0.reshape(-1,2))*unit_obs_fac
#reorder numtimeloc_vec
ntl_vec = [num_vec,time_vec,loc_vec]
#setup starting value for par and par0
#par = [0.5, ra1,dec1, 0,0,0]
par = np.zeros(max(num_vec + 1) * 5)
par0 = np.zeros(max(num_vec + 1) * 5)
par0[0::5] = radec_0[0] * unit_obs_fac
par0[1::5] = radec_0[1] * unit_obs_fac
q = [np.where(num_vec == i )[0] for i in range(max(num_vec + 1))]
index_0 = [i[0] if len(i) > 0 else -1 for i in q ]
par[0::5] = obs_rel[index_0, 0]
par[1::5] = obs_rel[index_0, 1]
qq = np.array([False if len(i) > 0 else True for i in q ])
#fitting residual function
if sc_scandir is None:
par_res = least_squares(FitFunction_Motion,par, xtol = 3e-16 ,jac = Jacobian_Motion, \
args = (ntl_vec, obs_rel, obs_error, scsc[3]))
else:
par_res = least_squares(FitFunction_Motion_Scandir,par, xtol = 3e-16 ,jac = Jacobian_Motion_Scandir, \
args = (ntl_vec, sc_scandir, obs_rel, obs_error, scsc[3]))
#return parameter in requested units
par_res.x[0::5] = (par_res.x[0::5] + par0[0::5]) * unit_pos_fac
par_res.x[1::5] = (par_res.x[1::5] + par0[1::5]) * unit_pos_fac
par_res.x[2::5] = (par_res.x[2::5] + par0[2::5]) * unit_pm_fac
par_res.x[3::5] = (par_res.x[3::5] + par0[3::5]) * unit_pm_fac
par_res.x[4::5] = (par_res.x[4::5] + par0[4::5]) * unit_px_fac
if qq.any():
par_res.x[1+5*np.where(qq)[0]] = None
par_res.x[2+5*np.where(qq)[0]] = None
par_res.x[3+5*np.where(qq)[0]] = None
par_res.x[4+5*np.where(qq)[0]] = None
par_res.x[5+5*np.where(qq)[0]] = None
return par_res
def FitFunction_Motion(par, numtimeloc_vec, obs, obs_error, cd):
'''------------------------------------------------------------
Description:
---------------------------------------------------------------
Input:
---------------------------------------------------------------
Output:
------------------------------------------------------------'''
'''
expect coordinates in mas
par = parameter: 5 parameter for each star
numtimeloc_vec = explanation for obs data: Which star at wich epoch from wich position
obs = observational imput
cd = cos(dec)
'''
c2 = const_Einsteinradius * const_Einsteinradius
if cd == 0: cd = 1e-6 #avoid devision by 0
cd_vec = np.array([cd,1])
par = np.array(par)
num_vec = numtimeloc_vec[0]
time_vec = numtimeloc_vec[1].reshape((-1,1))
loc_vec = numtimeloc_vec[2]
#order parameter
astrometry =par.reshape((-1,5))
radec = astrometry[:,0:2]
pm_radec = astrometry[:,2:4]
px = astrometry[:,4]
# setup parameter for each observation point
radec_vec = radec[num_vec]
pm_vec = pm_radec[num_vec]
px_vec = px[num_vec].reshape((-1,1))
radec_lens_vec = radec[[np.zeros(len(num_vec), int)]]
pm_lens_vec = pm_radec[[np.zeros(len(num_vec), int)]]
px_lens_vec = px[[np.zeros(len(num_vec), int)]].reshape((-1,1))
res = np.sqrt(np.sum(np.square(\
((radec_vec + pm_vec / cd_vec * time_vec + px_vec * loc_vec) \
- obs) * cd_vec ),axis= 1) / obs_error ** 2).reshape((-1,1))
return res
def FitFunction_Motion_Scandir(par, numtimeloc_vec, sc_scandir, obs, obs_error, cd):
'''------------------------------------------------------------
Description:
---------------------------------------------------------------
Input:
---------------------------------------------------------------
Output:
------------------------------------------------------------'''
'''
expect coordinates in mas
par = parameter: 5 parameter for each star
numtimeloc_vec = explanation for obs data: Which star at wich epoch from wich position
obs = observational imput
cd = cos(dec)
'''
c2 = const_Einsteinradius * const_Einsteinradius
if cd == 0: cd = 1e-6 #avoid devision by 0
cd_vec = np.array([cd,1])
par = np.array(par)
num_vec = numtimeloc_vec[0]
time_vec = numtimeloc_vec[1].reshape((-1,1))
loc_vec = numtimeloc_vec[2]
#order parameter
astrometry = par.reshape((-1,5))
radec = astrometry[:,0:2]
pm_radec = astrometry[:,2:4]
px = astrometry[:,4]
# setup parameter for each observation point
radec_vec = radec[num_vec]
pm_vec = pm_radec[num_vec]
px_vec = px[num_vec].reshape((-1,1))
radec_lens_vec = radec[[np.zeros(len(num_vec), int)]]
pm_lens_vec = pm_radec[[np.zeros(len(num_vec), int)]]
px_lens_vec = px[[np.zeros(len(num_vec), int)]].reshape((-1,1))
res = np.sum(sc_scandir \
* (((radec_vec + pm_vec / cd_vec * time_vec + px_vec * loc_vec) \
- obs) * cd_vec),axis= 1) / obs_error
return res
def Jacobian_Motion(par, numtimeloc_vec, obs, obs_error, cd):
'''------------------------------------------------------------
Description:
---------------------------------------------------------------
Input:
---------------------------------------------------------------
Output:
------------------------------------------------------------'''
'''
Determine the jacobian matrix for the Residual FitFunction.
input:
par = fitparameter
numtimeloc_vec = explanation for obs data: Which star at wich epoch from wich position:
obs = observed/simulated data
cd = cos(dec) for the field
returns: Jacobian matrix dFi/dxj
calculation: dFi/dxj = 1/Fi*2(delta_ra_i*d_delta_ra_i/dxj+delta_dec_i*d_delta_ra_i/dxj)
'''
# setup variable and constants
if cd == 0: cd = 1e-6
cd_vec = np.array([cd,1])
c2 = const_Einsteinradius * const_Einsteinradius
par = np.array(par)
num_vec = numtimeloc_vec[0]
time_vec = numtimeloc_vec[1].reshape((-1,1))
loc_vec = numtimeloc_vec[2]
# order parameters
astrometry = par.reshape((-1,5))
radec = astrometry[:,0:2]
pm_radec = astrometry[:,2:4]
px = astrometry[:,4]
# setup parameter for each observation point
radec_vec = radec[num_vec]
pm_vec = pm_radec[num_vec]
px_vec = px[num_vec].reshape((-1,1))
radec_lens_vec=radec[[np.zeros(len(num_vec), int)]]
pm_lens_vec=pm_radec[[np.zeros(len(num_vec), int)]]
px_lens_vec=px[[np.zeros(len(num_vec), int)]].reshape((-1,1))
# calculat partial derivertivs d_delta_ra_i/dxj,d_delta_dec_i/dxj for Motion and microlensing
# cross terms dF(star_i)/ dpar(star_j) for (i != j and j != 0) are equal 0
Motion = Partial_Motion_no_Mass(time_vec, loc_vec, cd,exact)
# calculate F_i (see FitFunction)
f_of_x = np.sqrt(np.sum(np.square(\
((radec_vec + pm_vec / cd_vec * time_vec + px_vec * loc_vec) \
- obs) * cd_vec ),axis= 1) / obs_error ** 2).reshape((-1,1))
# calculate delta_ra_i,delta_dec_i
a_d = (((radec_vec + pm_vec / cd_vec * time_vec + px_vec * loc_vec)\
- obs) * [cd,1]).reshape((-1,1,2)) / obs_error
# calculate dFi/dxj
partial = (1 / np.maximum(f_of_x,1e-6) * (np.sum(a_d * (Motion) , axis = 2))).reshape(-1)
# reshape matrix to include all cross terms
jac = np.zeros(len(par) * len(num_vec))
ind_par, ind_jac = Jac_Motion_Index(num_vec, len(par))
jac[ind_jac] = partial[ind_par]
return jac.reshape(-1, len(par))
def Jacobian_Motion_Scandir(par, numtimeloc_vec, sc_scandir, obs, obs_error, cd ):
'''------------------------------------------------------------
Description:
---------------------------------------------------------------
Input:
---------------------------------------------------------------
Output:
------------------------------------------------------------'''
'''
Determine the jacobian matrix for the Residual FitFunction.
input:
par = fitparameter
numtimeloc_vec = explanation for obs data: Which star at wich epoch from wich position:
obs = observed/simulated data
cd = cos(dec) for the field
returns: Jacobian matrix dFi/dxj
calculation: dFi/dxj = 1/Fi*(delta_ra_i*d_delta_ra_i/dxj+delta_dec_i*d_delta_dec_i/dxj)
'''
# setup variable and constants
if cd == 0: cd = 1e-6
cd_vec = np.array([cd,1])
par = np.array(par)
num_vec = numtimeloc_vec[0]
time_vec = numtimeloc_vec[1].reshape((-1,1))
loc_vec = numtimeloc_vec[2]
# order parameters
astrometry = par.reshape((-1,5))
radec = astrometry[:,0:2]
pm_radec = astrometry[:,2:4]
px = astrometry[:,4]
# setup parameter for each observation point
radec_vec = radec[num_vec]
pm_vec = pm_radec[num_vec]
px_vec = px[num_vec].reshape((-1,1))
# calculat partial derivertivs d_delta_ra_i/dxj,d_delta_dec_i/dxj for Motion and microlensing
# cross terms dF(star_i)/ dpar(star_j) for (i != j and j == 0) are equal 0
Motion = Partial_Motion_no_Mass(time_vec, loc_vec, cd)
# calculate dFi/dxj
partial = np.sum(sc_scandir.reshape(-1,1,2) * Motion / obs_error.reshape(-1,1,1), axis = 2).reshape(-1)
# reshape matrix to include all cross terms
jac = np.zeros(len(par) * len(num_vec))
ind_par, ind_jac = Jac_Motion_Index(num_vec, len(par))
jac[ind_jac] = partial[ind_par]
if np.isnan(jac.any()): print(2)
return jac.reshape(-1, len(par))
def Partial_Motion_no_Mass(time_vec, loc_vec, cd):
'''------------------------------------------------------------
Description:
---------------------------------------------------------------
Input:
---------------------------------------------------------------
Output:
------------------------------------------------------------'''
'''
calculat partial derivertiv for the Motion term
ra_dec = ra_dec_0+pm * t + parallax * loc_vec
use t,loc_vec is constant for each observation
first 6 zeros entries are for cross terms with the lens.
'''
one = np.ones(len(time_vec[:,0]))
zero = np.zeros(len(time_vec[:,0]))
alpha = np.array([zero, zero, zero, zero, zero, one * cd, zero, time_vec[:,0], zero, loc_vec[:,0] * cd])
delta = np.array([zero, zero, zero, zero, zero, zero, one, zero, time_vec[:,0], loc_vec[:,1]])
return np.array([alpha, delta]).T
def Jac_Motion_Index(num_vec, len_par):
'''------------------------------------------------------------
Description:
---------------------------------------------------------------
Input:
---------------------------------------------------------------
Output:
------------------------------------------------------------'''
#determine which indices in the jacobian are not equal 0
i_par= np.arange(len(num_vec)).reshape(-1,1) * 10
i_jac= np.arange(len(num_vec)).reshape(-1,1) * len_par
e0 = np.where(num_vec == 0)
ne0 = np.where(num_vec != 0)
ind_jac0 = i_jac[e0] + np.arange(0,5) + 5 * num_vec[e0].reshape(-1,1)
ind_par0 = i_par[e0] + np.arange(5,10)
ind_jac1 = i_jac[ne0] + np.concatenate((np.arange(0,5) * np.ones((len(ne0[0]),1), int),\
np.arange(0,5) + 5 * num_vec[ne0].reshape(-1,1)), axis = 1)
ind_par1 = i_par[ne0] + np.arange(10)
ind_jac = np.concatenate((ind_jac0,ind_jac1), axis= None)
ind_par = np.concatenate((ind_par0,ind_par1), axis= None)
return ind_par,ind_jac
| [
834,
439,
834,
796,
37250,
31805,
62,
45740,
41707,
31805,
22203,
62,
45740,
41707,
31805,
22203,
62,
45740,
62,
3351,
392,
343,
41707,
46751,
666,
62,
45740,
3256,
59,
198,
197,
197,
6,
46751,
666,
62,
45740,
62,
3351,
392,
343,
4170... | 2.528143 | 4,868 |