content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
from src.blockchain.block import Transaction from src.blockchain.blockchain import Blockchain transactions = [Transaction("Justus", "Jonas", 10.0), Transaction("Bernd", "Harald", 5.0)] blockchain = Blockchain() blockchain.add_block(transactions)
[ 6738, 12351, 13, 9967, 7983, 13, 9967, 1330, 45389, 201, 198, 6738, 12351, 13, 9967, 7983, 13, 9967, 7983, 1330, 29724, 201, 198, 201, 198, 7645, 4658, 796, 685, 48720, 7203, 5703, 385, 1600, 366, 18219, 292, 1600, 838, 13, 15, 828, ...
2.945055
91
from pykafka import KafkaClient import json from datetime import datetime import uuid import time input_file = open('./data/bus2.json') json_array = json.load(input_file) coordinates = json_array['features'][0]['geometry']['coordinates'] # Generate uuid # Kafaka producer client = KafkaClient(hosts="localhost:9092") topic = client.topics['bus-lines'] producer = topic.get_sync_producer() # Generate all coordinates generate_coordinates(coordinates) print('every thing works fine')
[ 6738, 12972, 74, 1878, 4914, 1330, 46906, 11792, 198, 11748, 33918, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 334, 27112, 198, 11748, 640, 628, 198, 15414, 62, 7753, 796, 1280, 7, 4458, 14, 7890, 14, 10885, 17, 13, 17752, 1...
3.113208
159
from classes.DatabaseConnection import DatabaseConnection
[ 6738, 6097, 13, 38105, 32048, 1330, 24047, 32048 ]
7.125
8
from datetime import datetime from taegis_sdk_python import ServiceCore from taegis_sdk_python.services.investigations.mutations import InvestigationMutation from taegis_sdk_python.services.investigations.queries import InvestigationQuery
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 20486, 1533, 271, 62, 21282, 74, 62, 29412, 1330, 4809, 14055, 198, 6738, 20486, 1533, 271, 62, 21282, 74, 62, 29412, 13, 30416, 13, 24859, 328, 602, 13, 21973, 602, 1330, 21505, 44,...
3.651515
66
from time import time from math import factorial from logging import getLogger from collections import deque from itertools import permutations, repeat from random import sample, randint from typing import List, Optional, Callable from networkx import DiGraph from numpy.random import choice import numpy as np # Local imports from cspy.algorithms.path_base import PathBase from cspy.checking import check_time_limit_breached log = getLogger(__name__) class GRASP(PathBase): """ Greedy Randomised Adaptive Search Procedure for the (resource) constrained shortest path problem. Adapted from `Ferone et al 2019`_. Parameters ---------- G : object instance :class:`nx.Digraph()` must have ``n_res`` graph attribute and all edges must have ``res_cost`` attribute. Also, the number of nodes must be :math:`\geq 5`. max_res : list of floats :math:`[M_1, M_2, ..., M_{n\_res}]` upper bounds for resource usage. min_res : list of floats :math:`[L_1, L_2, ..., L_{n\_res}]` lower bounds for resource usage. preprocess : bool, optional enables preprocessing routine. Default : False. max_iter : int, optional Maximum number of iterations for algorithm. Default : 100. max_localiter : int, optional Maximum number of local search iterations. Default : 10. time_limit : int, optional time limit in seconds. Default: None threshold : float, optional specify a threshold for a an acceptable resource feasible path with total cost <= threshold. Note this typically causes the search to terminate early. Default: None alpha : float, optional Greediness factor 0 (random) --> 1 (greedy). Default : 0.2. REF_callback : REFCallback, optional Custom resource extension callback. See `REFs`_ for more details. Default : None .. _REFs : https://cspy.readthedocs.io/en/latest/ref.html .. _Ferone et al 2019: https://www.tandfonline.com/doi/full/10.1080/10556788.2018.1548015 Raises ------ Exception if no resource feasible path is found """ def run(self): """ Calculate shortest path with resource constraints. """ start = time() while (self.it < self.max_iter and not self.stop and not check_time_limit_breached(start, self.time_limit)): self._algorithm() self.it += 1 if not self.best_solution.path: raise Exception("No resource feasible path has been found") def _check_path(self, solution=None): """ Returns True if solution.path is valid and resource feasible, False otherwise """ if solution: path, cost = solution.path, solution.cost if (len(path) > 2 and cost < 1e10 and path[0] == 'Source' and path[-1] == 'Sink'): self.st_path = path return self.check_feasibility(return_edge=False) else: return False else: return False @staticmethod def _find_alternative_paths(G, path, rng=None): """ Static Method used in local search to randomly generate valid paths. Using a subset of edges, it generates a connected path starting at the source node. """ # get all edges involving only these nodes poss_edges = G.subgraph(path).edges() if poss_edges: sample_size = randint(1, len(poss_edges)) if rng: tmp = np.empty(len(poss_edges), dtype='object') tmp[:] = poss_edges selection = rng.choice(tmp, replace=False, size=sample_size).tolist() else: selection = sample(deque(poss_edges), sample_size) # will use last value tried with given key path_edges = dict([edge for edge in selection if edge in G.edges()]) elem = 'Source' # start point in the new list new_list = [] for _ in path_edges: try: new_list.append((elem, path_edges[elem])) elem = path_edges[elem] except KeyError: pass if new_list: nodes_to_keep = [t[0] for t in new_list] nodes_to_keep.append(new_list[-1][1]) else: nodes_to_keep = [] else: nodes_to_keep = [] return nodes_to_keep class Solution(object): """ Object for solutions and candidates during GRASP iterations. Parameters ---------- path : list list of nodes in current path cost : float cost of solution """
[ 6738, 640, 1330, 640, 198, 6738, 10688, 1330, 1109, 5132, 198, 6738, 18931, 1330, 651, 11187, 1362, 198, 6738, 17268, 1330, 390, 4188, 198, 6738, 340, 861, 10141, 1330, 9943, 32855, 11, 9585, 198, 6738, 4738, 1330, 6291, 11, 43720, 600,...
2.300709
2,115
#!/usr/bin/python import sys import logging logging.basicConfig(stream=sys.stderr) sys.path.insert(0,"/var/www/dash/") from dash import app as application application.secret_key = 'Add your secret key'
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 11748, 25064, 198, 11748, 18931, 198, 6404, 2667, 13, 35487, 16934, 7, 5532, 28, 17597, 13, 301, 1082, 81, 8, 198, 17597, 13, 6978, 13, 28463, 7, 15, 553, 14, 7785, 14, 2503, 14, 42460, 1...
3.029851
67
# This an autogenerated file # # Generated with ISO19901_7Filter from typing import Dict,Sequence,List from dmt.entity import Entity from dmt.blueprint import Blueprint from .blueprints.iso19901_7filter import ISO19901_7FilterBlueprint from typing import Dict from sima.post.consequenceclass import ConsequenceClass from sima.post.controlsignalinputslot import ControlSignalInputSlot from sima.post.inputslot import InputSlot from sima.post.iso19901_7_analysis import ISO19901_7_analysis from sima.post.mooringtype import MooringType from sima.post.operationnode import OperationNode from sima.post.outputslot import OutputSlot from sima.sima.scriptablevalue import ScriptableValue class ISO19901_7Filter(OperationNode): """ Keyword arguments ----------------- name : str (default "") description : str (default "") _id : str (default "") scriptableValues : List[ScriptableValue] x : int (default 0) y : int (default 0) h : int (default 0) w : int (default 0) controlSignalInputSlots : List[ControlSignalInputSlot] filterInputSlots : List[InputSlot] filterOutputSlots : List[OutputSlot] breakingStrength : float Breaking strength(default 0.0) customSafetyFactor : float Safety factor(default 0.0) analysis : ISO19901_7_analysis mooringType : MooringType consequenceClass : ConsequenceClass useCustomSafetyFactor : bool (default False) """ @property def blueprint(self) -> Blueprint: """Return blueprint that this entity represents""" return ISO19901_7FilterBlueprint() @property def name(self) -> str: """""" return self.__name @name.setter def name(self, value: str): """Set name""" self.__name = str(value) @property def description(self) -> str: """""" return self.__description @description.setter def description(self, value: str): """Set description""" self.__description = str(value) @property def _id(self) -> str: """""" return self.___id @_id.setter def _id(self, value: str): """Set _id""" self.___id = str(value) @property def scriptableValues(self) -> List[ScriptableValue]: """""" return self.__scriptableValues @scriptableValues.setter def scriptableValues(self, value: List[ScriptableValue]): """Set scriptableValues""" if not isinstance(value, Sequence): raise Exception("Expected sequense, but was " , type(value)) self.__scriptableValues = value @property def x(self) -> int: """""" return self.__x @x.setter def x(self, value: int): """Set x""" self.__x = int(value) @property def y(self) -> int: """""" return self.__y @y.setter def y(self, value: int): """Set y""" self.__y = int(value) @property def h(self) -> int: """""" return self.__h @h.setter def h(self, value: int): """Set h""" self.__h = int(value) @property def w(self) -> int: """""" return self.__w @w.setter def w(self, value: int): """Set w""" self.__w = int(value) @property def controlSignalInputSlots(self) -> List[ControlSignalInputSlot]: """""" return self.__controlSignalInputSlots @controlSignalInputSlots.setter def controlSignalInputSlots(self, value: List[ControlSignalInputSlot]): """Set controlSignalInputSlots""" if not isinstance(value, Sequence): raise Exception("Expected sequense, but was " , type(value)) self.__controlSignalInputSlots = value @property def filterInputSlots(self) -> List[InputSlot]: """""" return self.__filterInputSlots @filterInputSlots.setter def filterInputSlots(self, value: List[InputSlot]): """Set filterInputSlots""" if not isinstance(value, Sequence): raise Exception("Expected sequense, but was " , type(value)) self.__filterInputSlots = value @property def filterOutputSlots(self) -> List[OutputSlot]: """""" return self.__filterOutputSlots @filterOutputSlots.setter def filterOutputSlots(self, value: List[OutputSlot]): """Set filterOutputSlots""" if not isinstance(value, Sequence): raise Exception("Expected sequense, but was " , type(value)) self.__filterOutputSlots = value @property def breakingStrength(self) -> float: """Breaking strength""" return self.__breakingStrength @breakingStrength.setter def breakingStrength(self, value: float): """Set breakingStrength""" self.__breakingStrength = float(value) @property def customSafetyFactor(self) -> float: """Safety factor""" return self.__customSafetyFactor @customSafetyFactor.setter def customSafetyFactor(self, value: float): """Set customSafetyFactor""" self.__customSafetyFactor = float(value) @property def analysis(self) -> ISO19901_7_analysis: """""" return self.__analysis @analysis.setter def analysis(self, value: ISO19901_7_analysis): """Set analysis""" self.__analysis = value @property def mooringType(self) -> MooringType: """""" return self.__mooringType @mooringType.setter def mooringType(self, value: MooringType): """Set mooringType""" self.__mooringType = value @property def consequenceClass(self) -> ConsequenceClass: """""" return self.__consequenceClass @consequenceClass.setter def consequenceClass(self, value: ConsequenceClass): """Set consequenceClass""" self.__consequenceClass = value @property def useCustomSafetyFactor(self) -> bool: """""" return self.__useCustomSafetyFactor @useCustomSafetyFactor.setter def useCustomSafetyFactor(self, value: bool): """Set useCustomSafetyFactor""" self.__useCustomSafetyFactor = bool(value)
[ 2, 770, 281, 1960, 519, 877, 515, 2393, 198, 2, 220, 198, 2, 2980, 515, 351, 19694, 19104, 486, 62, 22, 22417, 198, 6738, 19720, 1330, 360, 713, 11, 44015, 594, 11, 8053, 198, 6738, 288, 16762, 13, 26858, 1330, 20885, 198, 6738, 2...
2.472856
2,542
#! /usr/bin/env python3 import argparse import logging import dotenv import dl_hathi import dl_ia if __name__ == "__main__": main()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 1822, 29572, 198, 11748, 18931, 198, 11748, 16605, 24330, 198, 198, 11748, 288, 75, 62, 71, 44202, 198, 11748, 288, 75, 62, 544, 628, 628, 198, 198, 361, 11593, 367...
2.508772
57
############################################################################# ## ## Copyright (C) 2016 The Qt Company Ltd. ## Contact: http://www.qt.io/licensing/ ## ## This file is part of the Qt for Python examples of the Qt Toolkit. ## ## $QT_BEGIN_LICENSE:BSD$ ## You may use this file under the terms of the BSD license as follows: ## ## "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 Qt Company Ltd 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." ## ## $QT_END_LICENSE$ ## ############################################################################# # PySide2 tutorial 8 import sys from PySide2 import QtCore, QtGui, QtWidgets app = QtWidgets.QApplication(sys.argv) widget = MyWidget() widget.setGeometry(100, 100, 500, 355) widget.show() sys.exit(app.exec_())
[ 198, 29113, 29113, 7804, 4242, 2, 198, 2235, 198, 2235, 15069, 357, 34, 8, 1584, 383, 33734, 5834, 12052, 13, 198, 2235, 14039, 25, 2638, 1378, 2503, 13, 39568, 13, 952, 14, 677, 26426, 14, 198, 2235, 198, 2235, 770, 2393, 318, 636,...
3.485669
628
from .aco import AntColonyOptimization from .ga import GeneticAlgorithm from .lp import LinearIntegerProgram from .pso import ParticleSwarmOptimization from .sa import SimulatedAnnealing from .two_opt import TwoOpt
[ 6738, 764, 10602, 1330, 3738, 5216, 1647, 27871, 320, 1634, 198, 6738, 764, 4908, 1330, 42295, 2348, 42289, 198, 6738, 764, 34431, 1330, 44800, 46541, 15167, 198, 6738, 764, 79, 568, 1330, 2142, 1548, 10462, 1670, 27871, 320, 1634, 198, ...
3.706897
58
import math import sys import time import torch from ..utils import utils from ..utils.metric_logger import MetricLogger, SmoothedValue @torch.no_grad() import numpy as np def get_model_scores(pred_boxes): """Creates a dictionary of from model_scores to image ids. Args: pred_boxes (dict): dict of dicts of 'boxes' and 'scores' Returns: dict: keys are model_scores and values are image ids (usually filenames) """ model_score = {} for img_id, val in pred_boxes.items(): for score in val['scores']: if score not in model_score.keys(): model_score[score] = [img_id] else: model_score[score].append(img_id) return model_score def calc_precision_recall(image_results): """Calculates precision and recall from the set of images Args: img_results (dict): dictionary formatted like: { 'img_id1': {'true_pos': int, 'false_pos': int, 'false_neg': int}, 'img_id2': ... ... } Returns: tuple: of floats of (precision, recall) """ tp, fp, fn = 0, 0, 0 precision, recall = 0, 0 for img_id, res in image_results.items(): tp += res['TP'] fp += res['FP'] fn += res['FN'] try: precision = tp / (tp + fp) except ZeroDivisionError: precision = 0.0 try: recall = tp / (tp + fn) except ZeroDivisionError: recall = 0.0 return precision, recall def get_single_image_results(gt_boxes, pred_boxes, iou_thr): """Calculates number of true_pos, false_pos, false_neg from single batch of boxes. Args: gt_boxes (list of list of floats): list of locations of ground truth objects as [xmin, ymin, xmax, ymax] pred_boxes (dict): dict of dicts of 'boxes' (formatted like `gt_boxes`) and 'scores' iou_thr (float): value of IoU to consider as threshold for a true prediction. Returns: dict: true positives (int), false positives (int), false negatives (int) """ all_pred_indices = range(len(pred_boxes)) all_gt_indices = range(len(gt_boxes)) if len(all_pred_indices) == 0: tp = 0 fp = 0 fn = 0 return {'true_positive': tp, 'false_positive': fp, 'false_negative': fn} if len(all_gt_indices) == 0: tp = 0 fp = 0 fn = 0 return {'true_positive': tp, 'false_positive': fp, 'false_negative': fn} gt_idx_thr = [] pred_idx_thr = [] ious = [] for ipb, pred_box in enumerate(pred_boxes): for igb, gt_box in enumerate(gt_boxes): iou = calc_iou(gt_box, pred_box) if iou > iou_thr: gt_idx_thr.append(igb) pred_idx_thr.append(ipb) ious.append(iou) iou_sort = np.argsort(ious)[::1] if len(iou_sort) == 0: tp = 0 fp = 0 fn = 0 return {'true_positive': tp, 'false_positive': fp, 'false_negative': fn} else: gt_match_idx = [] pred_match_idx = [] for idx in iou_sort: gt_idx = gt_idx_thr[idx] pr_idx = pred_idx_thr[idx] # If the boxes are unmatched, add them to matches if (gt_idx not in gt_match_idx) and (pr_idx not in pred_match_idx): gt_match_idx.append(gt_idx) pred_match_idx.append(pr_idx) tp = len(gt_match_idx) fp = len(pred_boxes) - len(pred_match_idx) fn = len(gt_boxes) - len(gt_match_idx) return {'true_positive': tp, 'false_positive': fp, 'false_negative': fn}
[ 11748, 10688, 198, 11748, 25064, 198, 11748, 640, 198, 198, 11748, 28034, 198, 198, 6738, 11485, 26791, 1330, 3384, 4487, 198, 6738, 11485, 26791, 13, 4164, 1173, 62, 6404, 1362, 1330, 3395, 1173, 11187, 1362, 11, 2439, 1025, 704, 11395, ...
2.022392
1,831
from springpython.context import * from springpython.config import * from pika_client import * from amqplib_client import * from ticker_system import * from buy_low_sell_high import *
[ 6738, 6076, 29412, 13, 22866, 1330, 1635, 198, 6738, 6076, 29412, 13, 11250, 1330, 1635, 198, 198, 6738, 279, 9232, 62, 16366, 1330, 1635, 198, 6738, 716, 80, 489, 571, 62, 16366, 1330, 1635, 198, 6738, 4378, 263, 62, 10057, 1330, 163...
3.425926
54
from colors import * from utils import font_height
[ 6738, 7577, 1330, 1635, 198, 6738, 3384, 4487, 1330, 10369, 62, 17015, 198 ]
3.923077
13
#!/usr/bin/env python # coding: utf-8 # In[51]: # Generic Libraries from PIL import Image from keras.preprocessing.text import Tokenizer import os import pandas as pd import numpy as np import re,string,unicodedata import cv2 import requests import csv import pickle #Tesseract Library import pytesseract pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' #Warnings import warnings warnings.filterwarnings("ignore") #Garbage Collection import gc #Gensim Library for Text Processing import gensim.parsing.preprocessing as gsp from gensim.parsing.preprocessing import remove_stopwords from gensim import utils #TextBlob Library (Sentiment Analysis) from textblob import TextBlob, Word #Plotting Libraries import matplotlib.pyplot as plt import seaborn as sns # In[52]: #Define Directory Path #sample_images = r'C:\Users\calli\Downloads\train_images' test_images = r'C:\Users\calli\Documents\MATLAB\archive\bow_sample' # In[53]: #Custom Function to Traverse the folder # In[54]: #Traversing the folders #traverse(sample_images) traverse(test_images) # In[55]: ex_txt = [] #list to store the extracted text txt4bow = [] #list to use for bag of words #Function to Extract Text def TxtExtract(directory): """ This function will handle the core OCR processing of images. """ for subdir, dirs, files in os.walk(directory): for file in files: filepath = subdir + os.sep + file img_cv = cv2.imread(filepath) img_rgb = cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB) text = pytesseract.image_to_string(img_rgb) x = re.sub(r'\n{2, 10}', '\n', text) ifspace = text.isspace() if ifspace == True: print(file) print("image does not have text") else: print(file) ex_txt.extend([[file, filepath, (x.rstrip("\n"))]]) txt4bow.extend([text]) print(x.rstrip("\n")) fol_nm = os.path.split(os.path.dirname(subdir))[-1] print(f"Text Extracted from the files in '{fol_nm}' folder & saved to list..") # In[56]: #Extracting Text from JPG files in Sample Image Folder #TxtExtract(sample_images) #Extracting Text from JPG files in Dataset Folder TxtExtract(test_images) # In[57]: with open('OCR.csv', 'w', newline='', encoding='utf-8') as f: header = ['FileName', 'Filepath', 'Text'] writer = csv.writer(f) writer.writerow(header) writer.writerows(ex_txt) # In[62]: #BOW filtered_txt = [] for n in range(len(txt4bow)): #remove stopwords filtered_sentence = remove_stopwords(txt4bow[n]) filtered_txt.extend([filtered_sentence]) # using tokenizer model = Tokenizer() model.fit_on_texts(filtered_txt) keys = model.word_index.keys() #print keys print(f'keys: {list(keys)}\n') #create bag of words representation rep = model.texts_to_matrix(filtered_txt, mode='count') print(rep) # In[63]: with open('BOW.csv', 'w', newline='', encoding='utf-8') as f: header = [keys] writer = csv.writer(f) writer.writerow(header) writer.writerows(rep) # In[85]: #Free up memory gc.collect() # In[ ]:
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 554, 58, 4349, 5974, 628, 198, 2, 42044, 46267, 198, 6738, 350, 4146, 1330, 7412, 198, 6738, 41927, 292, 13, 3866, 36948, 13, 5239, 133...
2.316936
1,423
import os import sys import unittest from contextlib import contextmanager from functools import partial from pathlib import Path from typing import Any, Iterator, List, Optional, Tuple import black from black.debug import DebugVisitor from black.mode import TargetVersion from black.output import diff, err, out THIS_DIR = Path(__file__).parent DATA_DIR = THIS_DIR / "data" PROJECT_ROOT = THIS_DIR.parent EMPTY_LINE = "# EMPTY LINE WITH WHITESPACE" + " (this comment will be removed)" DETERMINISTIC_HEADER = "[Deterministic header]" PY36_VERSIONS = { TargetVersion.PY36, TargetVersion.PY37, TargetVersion.PY38, TargetVersion.PY39, } DEFAULT_MODE = black.Mode() ff = partial(black.format_file_in_place, mode=DEFAULT_MODE, fast=True) fs = partial(black.format_str, mode=DEFAULT_MODE) def assert_format( source: str, expected: str, mode: black.Mode = DEFAULT_MODE, *, fast: bool = False, minimum_version: Optional[Tuple[int, int]] = None, ) -> None: """Convenience function to check that Black formats as expected. You can pass @minimum_version if you're passing code with newer syntax to guard safety guards so they don't just crash with a SyntaxError. Please note this is separate from TargetVerson Mode configuration. """ actual = black.format_str(source, mode=mode) _assert_format_equal(expected, actual) # It's not useful to run safety checks if we're expecting no changes anyway. The # assertion right above will raise if reality does actually make changes. This just # avoids wasted CPU cycles. if not fast and source != expected: # Unfortunately the AST equivalence check relies on the built-in ast module # being able to parse the code being formatted. This doesn't always work out # when checking modern code on older versions. if minimum_version is None or sys.version_info >= minimum_version: black.assert_equivalent(source, actual) black.assert_stable(source, actual, mode=mode) def read_data(name: str, data: bool = True) -> Tuple[str, str]: """read_data('test_name') -> 'input', 'output'""" if not name.endswith((".py", ".pyi", ".out", ".diff")): name += ".py" base_dir = DATA_DIR if data else PROJECT_ROOT return read_data_from_file(base_dir / name) @contextmanager def change_directory(path: Path) -> Iterator[None]: """Context manager to temporarily chdir to a different directory.""" previous_dir = os.getcwd() try: os.chdir(path) yield finally: os.chdir(previous_dir)
[ 11748, 28686, 198, 11748, 25064, 198, 11748, 555, 715, 395, 198, 6738, 4732, 8019, 1330, 4732, 37153, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 4377, 11, 40806, 1352, 11, 7343, ...
2.932356
887
# Copyright (c) 2018 ISP RAS (http://www.ispras.ru) # Ivannikov Institute for System Programming of the Russian Academy of Sciences # # 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. import os import pytest import shutil import tempfile from clade import Clade from clade.intercept import intercept from tests.test_intercept import test_project_make, test_project @pytest.fixture(scope="session") @pytest.fixture(scope="session") @pytest.fixture(scope="session")
[ 2, 15069, 357, 66, 8, 2864, 33086, 371, 1921, 357, 4023, 1378, 2503, 13, 271, 1050, 292, 13, 622, 8, 198, 2, 16975, 1236, 1134, 709, 5136, 329, 4482, 30297, 286, 262, 3394, 8581, 286, 13473, 198, 2, 198, 2, 49962, 739, 262, 24843,...
3.594796
269
import numpy as np import tensorflow as tf _VGG_MEAN = [103.939, 116.779, 123.68] class Vgg19: """ The network configuration: - RGB 224x224x3 - conv3-64 - conv3-64 - maxpool - (112x112x128) - conv3-128 - conv3-128 - maxpool - (56x56x256) - conv3-256 - conv3-256 - conv3-256 - conv3-256 (vs. vgg16) - maxpool - (28x28x512) - conv3-512 - conv3-512 - conv3-512 - conv3-512 (vs. vgg16) - maxpool - (14x14x512) - conv3-512 - conv3-512 - conv3-512 - conv3-512 (vs.vgg16) - maxpool - (7x7x512x4096) - fc-4096 - (4096x4096) - fc-4096 - (4096x1000) - fc-1000 - softmax """ WIDTH = 224 HEIGHT = 224 CHANNELS = 3 LABELS = 1000 model = {} model_save_path = None model_save_iter_freq = 0 learning_rate = 0.05 _inputRGB = None _inputBGR = None _inputNormalizedBGR = None _conv1_1 = None _conv1_2 = None _pool = None _conv2_1 = None _conv2_2 = None _pool2 = None _conv3_1 = None _conv3_2 = None _conv3_3 = None _conv3_4 = None _pool3 = None _conv4_1 = None _conv4_2 = None _conv4_3 = None _conv4_4 = None _pool4 = None _conv5_1 = None _conv5_2 = None _conv5_3 = None _conv5_4 = None _pool5 = None _fc6 = None _relu6 = None _fc7 = None _relu7 = None _fc8 = None _preds = None # in [? 1000] shape _loss = None _optimizer = None _train_labels = None @property def inputRGB(self): """of shape [?, 224, 224, 3] in RGB order""" return self._inputRGB @property @property @property
[ 11748, 299, 32152, 355, 45941, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 198, 62, 53, 11190, 62, 11682, 1565, 796, 685, 15197, 13, 24, 2670, 11, 18693, 13, 40393, 11, 17031, 13, 3104, 60, 198, 198, 4871, 569, 1130, 1129, 25, 1...
1.956081
888
from django.conf.urls import patterns, include, url from django.conf import settings from django.views.generic import TemplateView from jsonrpc import jsonrpc_site import dd_auth.views # Uncomment the next line for overwriting templates #from django.views.generic.simple import direct_to_template # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', #Admin Urls #url(r'^dd_auth_admin/doc/', include('django.contrib.admindocs.urls')), url(r'^dd_auth_admin/dd_invitation/token/make$', 'dd_invitation.admin_views.make_tokens'), url(r'^dd_auth_admin/', include(admin.site.urls)), url(r'^accounts/i18n/', include('django.conf.urls.i18n'), name="set_language"), url(r'^accounts/lang/$', TemplateView.as_view(template_name='account/setlang.html')), url(r'^accounts/remote/access_denied/$', TemplateView.as_view(template_name='account/access_denied.html')), # JSON-RPC URLs # url(r'^authapi/browse/', 'jsonrpc.views.browse', name="jsonrpc_browser"), url(r'^authapi/$', jsonrpc_site.dispatch, name="jsonrpc_mountpoint"), url(r'^accounts/', include('allauth.urls')), url(r'^accounts/remote/sign_in/$', 'dd_auth.views.sign_in', {'template_name': 'account/sign_in.html'}, name='remote_sign_in'), url(r'^accounts/remote/sign_up/$', 'dd_auth.views.sign_up', {'template_name': 'account/sign_up.html'}, name='remote_sign_up'), url(r'^accounts/remote/reset/$', 'dd_auth.views.reset_password', {'template_name': 'account/reset.html'}, name='remote_reset_password'), url(r'^accounts/remote/sign_out/$', 'dd_auth.views.sign_out', name='remote_sign_out'), #url(r'^accounts/remote/set_email/$', 'dd_auth.views.set_email', name='remote_set_email') ) if getattr(settings, 'DD_SERVE_STATIC', False): from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns()
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 7572, 11, 2291, 11, 19016, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 37350, 7680, 628, 198, 6738, 33918, 81, 14751, 1330, 3391...
2.639946
736
# Generated by Django 2.1.1 on 2018-10-05 00:59 from django.db import migrations, models import django.utils.timezone
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 16, 319, 2864, 12, 940, 12, 2713, 3571, 25, 3270, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 26791, 13, 2435, 11340, 628 ]
2.926829
41
import os import requests import colorific from PIL import Image from . import Validador STEAM_OWNERS_MIN = int(os.environ['STEAM_OWNERS_MIN']) STEAM_GAMES_LIMIT = int(os.environ['STEAM_GAMES_LIMIT'])
[ 11748, 28686, 198, 11748, 7007, 198, 11748, 3124, 811, 198, 6738, 350, 4146, 1330, 7412, 198, 6738, 764, 1330, 48951, 7079, 198, 198, 30516, 2390, 62, 14165, 4877, 62, 23678, 796, 493, 7, 418, 13, 268, 2268, 17816, 30516, 2390, 62, 14...
2.636364
77
#!/usr/bin/python import Board import os import time import sys from Loader import glider_gun dimension = 15 if len(sys.argv) > 1: dimension = int(sys.argv[1]) foo = Board.Board(dimension) # for key, cell in foo.board.iteritems(): # cell.state = False # for i in range(len(glider_gun)): # for j in range(len(glider_gun[i])): # key = str(i)+','+str(j) # foo.board[key].state = glider_gun[i][j] == 1 first = [] second = [] turns = 0 firstup = True while True: turns += 1 os.system('cls' if os.name == 'nt' else 'clear') foo.print_printable() if turns == 1: first = foo.printable[:] foo.print_board() if turns == 2: second = first[:] first = foo.printable[:] foo.print_board() if turns > 2: second = first[:] first = foo.printable[:] foo.print_board() if check(foo.printable, second): os.system('cls' if os.name == 'nt' else 'clear') print "\nIterations: " + str(turns) exit() print "\nIterations: " + str(turns) foo.take_turn() time.sleep(.125) print "\n\n"
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 5926, 198, 11748, 28686, 198, 11748, 640, 198, 11748, 25064, 198, 6738, 8778, 263, 1330, 1278, 1304, 62, 7145, 628, 198, 198, 46156, 796, 1315, 198, 361, 18896, 7, 17597, 13, 853,...
2.157197
528
import linecache path = '/home/nevronas/Projects/Personal-Projects/Dhruv/OffensEval/dataset/train-v1/offenseval-training-v1.tsv' maxi = 0 with open(path, "r") as f: for line in f: contents = line.split("\t") l = len(contents[1].split(" ")[1:]) print(l) if(l > maxi): maxi = l print("\n",maxi)
[ 11748, 1627, 23870, 198, 6978, 796, 31051, 11195, 14, 710, 85, 1313, 292, 14, 16775, 82, 14, 30228, 12, 16775, 82, 14, 35, 71, 622, 85, 14, 9362, 641, 36, 2100, 14, 19608, 292, 316, 14, 27432, 12, 85, 16, 14, 2364, 1072, 2100, 1...
1.965517
174
from tokens import Token
[ 6738, 16326, 1330, 29130, 628, 628 ]
4.666667
6
"""This script disovers and tests OpenCV bioinspired module's API. Author: Yuhuang Hu Email : yuhuang.hu@uzh.ch """ import cv2 from moviepy.video.io.ffmpeg_reader import FFMPEG_VideoReader from simretina import dataset, gui, retina option = "test-movie-py" if option == "test-builtin-image": # testing for builtin dataset frame, size = dataset.get_lenna() print frame.shape print size if option == "test-builtin-video": # testing for builtin video frames, size_v = dataset.get_taichi() print len(frames) print size_v if option == "test-bgr2rgb-sequence": frames, size = dataset.get_horse_riding() new_frames = gui.trans_bgr2rgb_seq(frames) for frame in new_frames: cv2.imshow("test", frame) cv2.waitKey(delay=0) print len(new_frames) if option == "test-ratio-keep-resize": frame, size = dataset.get_lenna() frame = gui.resize(frame, (400, 300), ratio_keep=True) print frame.shape if option == "test-dict-compare": para_dict_old = {} para_dict_old["a"] = 1 para_dict_old["b"] = 2 para_dict_new = {} para_dict_new["a"] = 1 para_dict_new["b"] = 2 print retina.compare_para_dict(para_dict_old, para_dict_new) if option == "test-setup-function": eye = retina.init_retina((300, 200)) print type(eye.setupOPLandIPLParvoChannel) print type(eye.setupIPLMagnoChannel) print eye.getInputSize() if option == "test-movie-py": video = FFMPEG_VideoReader("./simretina/retina-data/HorseRiding.avi") frame = video.read_frame() for i in range(video.nframes): frame = video.read_frame() cv2.imshow("test", frame) cv2.waitKey(0)
[ 37811, 1212, 4226, 595, 13801, 290, 5254, 4946, 33538, 13401, 24194, 8265, 338, 7824, 13, 198, 198, 13838, 25, 575, 7456, 84, 648, 11256, 198, 15333, 1058, 331, 7456, 84, 648, 13, 13415, 31, 10277, 71, 13, 354, 198, 37811, 198, 198, ...
2.437048
691
import logging import os from logging.handlers import SMTPHandler, RotatingFileHandler from flask import Flask, g from flask_security import Security, SQLAlchemyUserDatastore from flask_sqlalchemy import SQLAlchemy from turbo_flask import Turbo from config import Config __all__ = [ 'app', 'db', 'turbo', ] app = Flask(__name__) app.config.from_object(Config) # Setup logging and error reporting if not app.debug and not app.testing: if app.config['MAIL_SERVER']: auth = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = None if app.config['MAIL_USE_TLS']: secure = () mail_handler = SMTPHandler( mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr='no-reply@' + app.config['MAIL_SERVER'], toaddrs=app.config['ADMINS'], subject='Newsledger Failure', credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/newsledger.log', maxBytes=10240, backupCount=10) file_handler.setFormatter(logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info('Newsledger startup.') # Initialize add ons db = SQLAlchemy(app) turbo = Turbo(app) # Set up flask-security from nl.models.auth import Role, User app.user_datastore = SQLAlchemyUserDatastore(db, User, Role) app.security = Security(app, app.user_datastore) # Register main glue blueprint from nl import main app.register_blueprint(main.bp) # Register administration blueprint from nl import admin app.register_blueprint(admin.bp) # Register customers blueprint from nl import customers app.register_blueprint(customers.bp) # Register routes blueprint from nl import routes app.register_blueprint(routes.bp) # Register stores and racks blueprint from nl import stores app.register_blueprint(stores.bp) from nl import models from nl.models import auth from nl.models import config from nl.models import customers from nl.models import routes
[ 198, 11748, 18931, 198, 11748, 28686, 198, 6738, 18931, 13, 4993, 8116, 1330, 9447, 7250, 25060, 11, 18481, 803, 8979, 25060, 198, 198, 6738, 42903, 1330, 46947, 11, 308, 198, 6738, 42903, 62, 12961, 1330, 4765, 11, 16363, 2348, 26599, ...
2.547445
959
#!/usr/bin/env python """ A GTK quick message popup program. Allows users to quickly share messages with others on their own screen. Useful for when you need to be silent but want to communicate with the person sitting next to you, e.g. for games of hangman during lectures. TODO: allow multi-lines """ __author__ = 'Ali Scott' import pygtk pygtk.require('2.0') import gtk import pango X_PADDING = 40 Y_PADDING = 20 X_MARGIN = 60 FONT_FACE = 'lucida sans unicode' FONT_SIZE = '62' BG_COLOR = '#000' TEXT_COLOR = '#fff' OPACITY = 0.8 class QuickText: """ Draws the window and handles the key events. """ def __init__(self): """ Sets up the window and the text area. """ self.window = self._setup_window() self.textarea = self._setup_textarea() self.window.connect('destroy', gtk.main_quit) self.window.connect('key_press_event', self._on_key_press) self.textarea.connect('changed', self._text_changed) font_desc = pango.FontDescription(FONT_FACE + ' ' + FONT_SIZE) self.textarea.modify_font(font_desc) # layout used for finding pixel size of font self.layout = pango.Layout(gtk.Widget \ .create_pango_context(self.window)) self.layout.set_font_description(font_desc) (w, h) = self.layout.get_pixel_size() # set starting height of the text area to be the height of the font self.textarea.set_size_request(w, h) # add padding to the size of the window self.window.resize(w + X_PADDING, h + Y_PADDING) self.window.add(self.textarea) self.textarea.show() self.window.show() def _setup_window(self): """ Styles the window. """ w = gtk.Window(gtk.WINDOW_TOPLEVEL) w.set_position(gtk.WIN_POS_CENTER_ALWAYS) w.set_decorated(False) w.set_has_frame(False) w.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(BG_COLOR)) w.set_opacity(OPACITY) return w def _setup_textarea(self): """ Styles the text area. """ t = gtk.Entry() t.set_alignment(0.5) t.set_has_frame(False) t.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse(BG_COLOR)) t.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(BG_COLOR)) t.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse(TEXT_COLOR)) return t def _on_key_press(self, widget, event): """ Handles key press events. Quits when the enter key is pressed. """ if gtk.gdk.keyval_name(event.keyval) == 'Return': gtk.Widget.destroy(self.window) def _text_changed(self, widget): """ Handles resizing of window when text is written. """ # get size of text self.layout.set_text(self.textarea.get_text()) (w, h) = self.layout.get_pixel_size() # resize window and text area to fit text and screen size max_width = gtk.gdk.screen_width() - X_MARGIN self.textarea.set_size_request(min(w, max_width - X_PADDING), h) self.window.resize(min(w + X_PADDING, max_width), h + Y_PADDING) def main(self): """ Runs the program. """ gtk.main() if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 198, 32, 7963, 42, 2068, 3275, 46207, 1430, 13, 198, 198, 34934, 2985, 284, 2952, 2648, 6218, 351, 1854, 319, 511, 898, 3159, 13, 49511, 198, 1640, 618, 345, 761, 284, 30...
2.167529
1,546
# coding=utf-8 # !/usr/bin/env python import sys try: from setuptools import setup except ImportError: sys.stderr.write('using distutils\n') from distutils.core import setup with open('requirements.txt') as f: required = f.read().splitlines() setup( name='amber-python-drivers', packages=[ 'amberdriver', 'amberdriver.common', 'amberdriver.dummy', 'amberdriver.hokuyo', 'amberdriver.drive_to_point', 'amberdriver.collision_avoidance', 'amberdriver.null', 'amberdriver.tools', 'amberdriver.tests' ], package_dir={ 'amberdriver': 'src/amberdriver', 'amberdriver.common': 'src/amberdriver/common', 'amberdriver.dummy': 'src/amberdriver/dummy', 'amberdriver.hokuyo': 'src/amberdriver/hokuyo', 'amberdriver.drive_to_point': 'src/amberdriver/drive_to_point', 'amberdriver.collision_avoidance': 'src/amberdriver/collision_avoidance', 'amberdriver.null': 'src/amberdriver/null', 'amberdriver.tools': 'src/amberdriver/tools', 'amberdriver.tests': 'src/amberdriver/tests' }, package_data={'': [ 'src/amberdriver/common/amber.ini', 'src/amberdriver/dummy/dummy.ini', 'src/amberdriver/hokuyo/hokuyo.ini', 'src/amberdriver/drive_to_point/drive_to_point.ini', 'src/amberdriver/collision_avoidance/collision_avoidance.ini', 'src/amberdriver/tools/main.ini' ]}, data_files=[ ('', [ 'src/amberdriver/common/amber.ini', 'src/amberdriver/dummy/dummy.ini', 'src/amberdriver/hokuyo/hokuyo.ini', 'src/amberdriver/drive_to_point/drive_to_point.ini', 'src/amberdriver/collision_avoidance/collision_avoidance.ini', 'src/amberdriver/tools/main.ini' ]), ], test_suite="amberdriver.tests", include_package_data=True, install_requires=required, version='1.17', description='Amber drivers in python', author=u'Paweł Suder', author_email='pawel@suder.info', url='http://project-capo.github.io/', download_url='http://github.com/project-capo/amber-python-drivers/', keywords=[ 'amber', 'dummy', 'hokuyo', 'drive to point', 'collision avoidance', 'panda' ], classifiers=[ 'Programming Language :: Python', 'Development Status :: 4 - Beta', 'Environment :: Other Environment', 'Intended Audience :: Developers', 'License :: Other/Proprietary License', 'Operating System :: OS Independent', ], long_description='''\ ''' )
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 5145, 14, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 25064, 198, 198, 28311, 25, 198, 220, 220, 220, 422, 900, 37623, 10141, 1330, 9058, 198, 16341, 17267, 12331, 25, 198, 220, 220, 220, 2506...
2.239531
1,194
# USAGE # python superpixel.py --image cactus.jpg import torch import matplotlib.pyplot as plt from skimage import io from skimage.segmentation import quickshift, mark_boundaries # 导入mark_boundaries 以绘制实际的超像素分割 # 导入必要的包 from skimage.segmentation import slic # 导入包以使用SLIC superpixel segmentation from skimage.util import img_as_float my_input = torch.rand([128, 128]).numpy() print('my_input.shape', my_input.shape) image_path = './sample_1_image.png' image = img_as_float(io.imread(image_path)) plt.imshow(image) # 遍历超像素段的数量 研究3种尺寸不断增加的段,100、200、300 for numSegments in (350, 400): # 执行SLTC 超像素分割,该功能仅获取原始图像并覆盖我们的超像素段。 # 仅有一个必需参数: # image:待执行SLTC超像素分割的图像 # n_segments: 定义我们要生成多少个超像素段的参数,默认100 # sigma:在分割之前应用的平滑高斯核 segments = superpixel_segmentation(image, numSegments) # 绘制SLTC 的分割结果 fig = plt.figure("Superpixels -- %d segments" % (numSegments)) ax = fig.add_subplot(1, 1, 1) ax.imshow(mark_boundaries(image, segments)) plt.axis("off") # 展示图像 plt.show()
[ 2, 220, 1294, 11879, 198, 2, 220, 21015, 2208, 32515, 13, 9078, 1377, 9060, 269, 34144, 13, 9479, 198, 11748, 28034, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 1341, 9060, 1330, 33245, 198, 6738, 1341, 90...
1.543645
653
import requests_cache USER_AGENT = "ask_the_duck v0.0.1" SESSION = requests_cache.CachedSession(expire_after=5 * 60, backend="memory") SESSION.headers = {"User-Agent": USER_AGENT}
[ 11748, 7007, 62, 23870, 198, 29904, 62, 4760, 3525, 796, 366, 2093, 62, 1169, 62, 646, 694, 410, 15, 13, 15, 13, 16, 1, 198, 50, 47621, 796, 7007, 62, 23870, 13, 34, 2317, 36044, 7, 1069, 5111, 62, 8499, 28, 20, 1635, 3126, 11, ...
2.712121
66
from sklearn import preprocessing, metrics import lightgbm as lgb import pandas as pd import numpy as np from sklearn.model_selection import StratifiedKFold, KFold, RepeatedKFold, GroupKFold, GridSearchCV, train_test_split, TimeSeriesSplit from datetime import datetime import copy import os import fire import glob import pdb ##### import all Feature engineering functions from util_feat_m5 import * if __name__ == "__main__": import fire fire.Fire() """ import util_feat_m5 # df_meta= col_name, col_type, file_path def featurestore_generate_feature(dir_in, dir_out, my_fun_features) : # from util_feat_m5 import lag_featrues # featurestore_generate_feature(dir_in, dir_out, lag_featrues) train_df = pd.read_csv( dir_in + "/sales_train_val.csv.zip") calendar_df = pd.read_csv(dir_in + "/calendar.csv") price_df = pd.read_csv(dir_in + "/sell_prices.csv") dfnew = my_fun_features(train_df, calendar_df, price_df) : dfnew.to_parquet( dir_out +"/mfeaturesXXXX.parquet") def featurestore_filter_features(mode="random") : cols_cat0 = [ "feat1", "fewat2" ] if mode == "random" : ### Random selection cols_cat = cols_cat0[ np.random.c = hoice( 5, len(cols_cat) ) ] cols_num = cols_num0[ np.random.c = hoice( 5, len(cols_num) ) ] return cols_cat, col_num if mode == "all" : pass if mode == "smartway" : pass def train(model, pars={} ) : data_pars = {} model_pars = {} for ii in range(n_experiments) : cols_cat, cols_num = featurestore_filter_features() df = featurestore_get_feature_fromcolname(path, cols_cat + cols_num, "train") dftest = featurestore_get_feature_fromcolname(path, cols_cat + cols_num, 'test') X_train = X_transform( df, cols_num, cols_cat, pars) # select sri y_train = y_transform(df, coly) X_test = X_transform( dftest, cols_num, cols_cat, pars) # select variables y_test = y_transform(dftest, coly) lgbm = lgb.LGBMRegressor() lgbm.fit( X_train, y_train) # prediction + metrics y_test_pred = lgbm.predict(X_test) metric_val = metrics_calc(y_test, y_test_pred) ### Store in metrics : # run_id, feat_name, feat_name_long, feat_type, model_params, metric_name, metric_val # 3,roling_demand,Mean of the variable estimates,lag_features,params = {"objective" : "poisson","metric" :"rmse","force_row_wise" : True,"learning_rate" : 0.075, "sub_row" : 0.75,"bagging_freq" : 1,"lambda_l2" : 0.1,"metric": ["rmse"],'verbosity': 1,'num_iterations' : 250, },rmse,1.16548 df_metrics['run_id'] = time() df_metrics['cols'].append( ",".join( cols_num + cols_cat )) df_metrics['metrics_val'].append(metric_val) def test_old(): from util_feat_m5 import lag_featrues train_df = pd.read_csv("sales_train_val.csv") calendar_df = pd.read_csv("calendar.csv") price_df = pd.read_csv("sell_prices.csv") sample = pd.read_csv("sample_submi.csv") calendar_df["date_dt"] = pd.to_datetime(calendar_df["date"]) train = train_df.copy() price = price_df.copy() calendar = calendar_df.copy() Train_data = train.iloc[:,:-56] Val_data = train.iloc[:,:-28] X_train = lag_featrues(Train_data).iloc[:,5:] # select variables y_train = train.iloc[:,-56] X_test = lag_featrues(Val_data).iloc[:,5:] y_test = train.iloc[:,-28] # Create instance lgbm = lgb.LGBMRegressor() # Training and score learning_rate = [0.15, 0.2, 0.25] max_depth = [15, 20, 25] param_grid = {'learning_rate': learning_rate, 'max_depth': max_depth} # Fitting cv_lgbm = GridSearchCV(lgbm, param_grid, cv=10, n_jobs =1) cv_lgbm.fit(X_train, y_train) print("Best params:{}".format(cv_lgbm.best_params_)) # best params best_lg = cv_lgbm.best_estimator_ # prediction y_train_pred_lg = best_lg.predict(X_train) y_test_pred_lg = best_lg.predict(X_test) print("MSE train:{}".format(mean_squared_error(y_train, y_train_pred_lg))) print("MSE test;{}".format(mean_squared_error(y_test, y_test_pred_lg))) print("R2 score train:{}".format(r2_score(y_train, y_train_pred_lg))) print("R2 score test:{}".format(r2_score(y_test, y_test_pred_lg))) #Predict using only variables with an importance of 1 or higher. importance = best_lg.feature_importances_ indices = np.argsort(importance)[::-1] # print importance importance_df = pd.DataFrame({}) columns = [] importance_ = [] for f in range(X_train.shape[1]): print("%2d) %-*s %.2f" %(f+1, 30, X_train.columns[indices[f]], importance[indices[f]])) col = X_train.columns[indices[f]] imp = importance[indices[f]] columns.append(col) importance_.append(imp) importance_df["col_name"] = columns importance_df["importance"] = importance_ importance = best_lg.feature_importances_ indices = np.argsort(importance)[::-1] # importance columns (>0) imp_col = importance_df[importance_df["importance"]>0]["col_name"].values # Train test split, select by imp_col X_train = lag_featrues(Train_data).iloc[:,5:][imp_col] # select variables y_train = train.iloc[:,-56] X_test = lag_featrues(Val_data).iloc[:,5:][imp_col] y_test = train.iloc[:,-28] # Create instance lgbm = lgb.LGBMRegressor() # Training and score learning_rate = [0.15, 0.2, 0.25] max_depth = [15, 20, 25] param_grid = {'learning_rate': learning_rate, 'max_depth': max_depth} # Fitting cv_lgbm = GridSearchCV(lgbm, param_grid, cv=10, n_jobs =1) cv_lgbm.fit(X_train, y_train) print("Best params:{}".format(cv_lgbm.best_params_)) # best params best_lg = cv_lgbm.best_estimator_ # prediction y_train_pred_lg = best_lg.predict(X_train) y_test_pred_lg = best_lg.predict(X_test) print("MSE train:{}".format(mean_squared_error(y_train, y_train_pred_lg))) print("MSE test;{}".format(mean_squared_error(y_test, y_test_pred_lg))) print("R2 score train:{}".format(r2_score(y_train, y_train_pred_lg))) print("R2 score test:{}".format(r2_score(y_test, y_test_pred_lg))) run_id=list(range(300)) df_metrics=pd.DataFrame(run_id,columns=['run_id']) df_metrics['feat_name'] = pd.Series(X_train.columns[0:300], index=dataframe.index) df_metrics['feat_type']=df_metrics.feat_name df_metrics.replace({'feat_type': r'^lag_.*'}, {'feat_type': 'lag'}, regex=True,inplace=True) df_metrics.replace({'feat_type': r'^rolling.*'}, {'feat_type': 'rolling'}, regex=True,inplace=True) df_metrics['parameter'] = pd.Series(best_lg, index=dataframe.index) df_metrics['metric_name'] ="MSE" df_metrics['metric_val'] = pd.Series(pred_mse[:300], index=dataframe.index) df_metrics.to_csv("train.csv") """
[ 6738, 1341, 35720, 1330, 662, 36948, 11, 20731, 198, 11748, 1657, 70, 20475, 355, 300, 22296, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 29186, 1431, 42,...
2.269457
3,058
# coding: utf-8 # pylint: disable= too-many-lines, redefined-builtin, protected-access """NDArray API of mxnet.""" from __future__ import absolute_import from __future__ import division import ctypes import warnings import sys import functools import operator import numpy as np from .base import _LIB, string_types, numeric_types from .base import c_array, mx_float, py_str, c_str, mx_real_t from .base import mx_uint, NDArrayHandle, FunctionHandle from .base import ctypes2buffer from .base import check_call, ctypes2docstring from .context import Context from . import _ndarray_internal as _internal # pylint: disable= no-member _DTYPE_NP_TO_MX = { np.float32 : 0, np.float64 : 1, np.float16 : 2, np.uint8 : 3, np.int32 : 4 } _DTYPE_MX_TO_NP = { 0 : np.float32, 1 : np.float64, 2 : np.float16, 3 : np.uint8, 4 : np.int32 } # pylint: enable= no-member def _new_empty_handle(): """Return a new empty handle. Empty handle can be used to hold result Returns ------- a new empty ndarray handle """ hdl = NDArrayHandle() check_call(_LIB.MXNDArrayCreateNone(ctypes.byref(hdl))) return hdl def _new_alloc_handle(shape, ctx, delay_alloc, dtype=mx_real_t): """Return a new handle with specified shape and context. Empty handle is only used to hold results Returns ------- a new empty ndarray handle """ hdl = NDArrayHandle() check_call(_LIB.MXNDArrayCreateEx( c_array(mx_uint, shape), mx_uint(len(shape)), ctypes.c_int(ctx.device_typeid), ctypes.c_int(ctx.device_id), ctypes.c_int(int(delay_alloc)), ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dtype).type])), ctypes.byref(hdl))) return hdl def waitall(): """Wait all async operation to finish in MXNet This function is used for benchmark only """ check_call(_LIB.MXNDArrayWaitAll()) class NDArray(object): """NDArray object in mxnet. NDArray is basic ndarray/Tensor like data structure in mxnet. """ # pylint: disable= no-member def __init__(self, handle, writable=True): """initialize a new NDArray Parameters ---------- handle : NDArrayHandle NDArray handle of C API """ assert isinstance(handle, NDArrayHandle) self.handle = handle self.writable = writable def __setitem__(self, in_slice, value): """Set ndarray value. `value` can be a scalar, an `NDArray` or numpy array of compatible shape. The following modes are supported: - `array[:] = value`: set all the contents - `array[i] = value`: set the i-th slice. If the array is of dimension `(d1, d2, d3)`, it sets value of a slice of shape `(1, d2, d3)`. - `array[i:j] = value`: similarly, if the array is of dimension `(d1, d2, d3)`, it sets value of a slice of shape `(j-i, d2, d3)`. Fully-dimensional indexing is also supported. For example, if array is of shape `(d1, d2, d3)`, one can do - `array[:, :, :] = value`: achieving the same effect of `array[:] = value` - `array[:, i, j:k] = value`: each index could be a python slice or an int. """ # pylint: disable=too-many-branches if not self.writable: raise ValueError('trying to assign to a readonly NDArray') if isinstance(in_slice, int): sliced_arr = self._at(in_slice) sliced_arr[:] = value return if isinstance(in_slice, slice): if in_slice.step is not None: raise ValueError('NDArray only support continuous slicing on axis 0') if in_slice.start is not None or in_slice.stop is not None: sliced_arr = self._slice(in_slice.start, in_slice.stop) sliced_arr[:] = value return if isinstance(value, NDArray): if value.handle is not self.handle: value.copyto(self) elif isinstance(value, numeric_types): _internal._set_value(float(value), out=self) elif isinstance(value, (np.ndarray, np.generic)): self._sync_copyfrom(value) else: raise TypeError('type %s not supported' % str(type(value))) if isinstance(in_slice, tuple): # multi-dimension indexing my_shape = self.shape assert len(in_slice) == len(my_shape) for slice_i in in_slice: assert isinstance(slice_i, (slice, int)) begin = [0 for _ in my_shape] end = [x for x in my_shape] for i, slice_i in enumerate(in_slice): if isinstance(slice_i, int): assert slice_i < my_shape[i] begin[i] = slice_i end[i] = slice_i + 1 if isinstance(slice_i, slice): # only support continuous slicing assert slice_i.step is None begin[i] = slice_i.start or 0 end[i] = slice_i.stop or my_shape[i] assert begin[i] < end[i] assert end[i] <= my_shape[i] begin = tuple(begin) end = tuple(end) if isinstance(value, NDArray): value = value.as_in_context(self.context) _internal._crop_assign(self, value, out=self, begin=begin, end=end) elif isinstance(value, numeric_types): _internal._crop_assign_scalar(self, out=self, begin=begin, end=end, scalar=value) elif isinstance(value, (np.ndarray, np.generic)): value = array(value, ctx=self.context) _internal._crop_assign(self, value, out=self, begin=begin, end=end) else: raise TypeError('type %s not supported' % str(type(value))) # pylint: enable=too-many-branches def __getitem__(self, in_slice): """Get ndarray""" if isinstance(in_slice, int): return self._at(in_slice) if not isinstance(in_slice, slice) or in_slice.step is not None: raise ValueError('NDArray only support continuous slicing on axis 0') if in_slice.start is not None or in_slice.stop is not None: return self._slice(in_slice.start, in_slice.stop) else: return self def _sync_copyfrom(self, source_array): """Peform an synchronize copy from the array. Parameters ---------- source_array : array_like The data source we should like to copy from. """ if not isinstance(source_array, np.ndarray): try: source_array = np.array(source_array, dtype=self.dtype) except: raise TypeError('array must be an array_like data,' + 'type %s is not supported' % str(type(array))) source_array = np.ascontiguousarray(source_array, dtype=self.dtype) if source_array.shape != self.shape: raise ValueError('Shape inconsistant: expected %s vs got %s'%( str(self.shape), str(source_array.shape))) check_call(_LIB.MXNDArraySyncCopyFromCPU( self.handle, source_array.ctypes.data_as(ctypes.c_void_p), ctypes.c_size_t(source_array.size))) def _slice(self, start, stop): """Return a sliced NDArray that shares memory with current one. Parameters ---------- start : int Starting index of slice. stop : int Finishing index of slice. """ handle = NDArrayHandle() start = mx_uint(start) if start else mx_uint(0) stop = mx_uint(stop) if stop else mx_uint(self.shape[0]) check_call(_LIB.MXNDArraySlice( self.handle, start, stop, ctypes.byref(handle))) return NDArray(handle=handle, writable=self.writable) def _at(self, idx): """Return a sub NDArray that shares memory with current one. Parameters ---------- idx : int index of sub array. """ handle = NDArrayHandle() idx = mx_uint(idx) check_call(_LIB.MXNDArrayAt( self.handle, idx, ctypes.byref(handle))) return NDArray(handle=handle, writable=self.writable) def reshape(self, new_shape): """Return a reshaped NDArray that shares memory with current one. Parameters ---------- new_shape : iterable of int new shape of NDArray """ handle = NDArrayHandle() check_call(_LIB.MXNDArrayReshape(self.handle, len(new_shape), c_array(ctypes.c_int, new_shape), ctypes.byref(handle))) return NDArray(handle=handle, writable=self.writable) # pylint: disable= undefined-variable def broadcast_to(self, shape): """ Broadcasting the current NDArray into the given shape. The semantics is the same with `numpy`'s broadcasting Parameters --------- shape : the shape to broadcast the broadcast shape """ cur_shape = self.shape err_str = 'operands could not be broadcast together with remapped shapes' \ '[original->remapped]: {} and requested shape {}'.format(cur_shape, shape) if len(shape) < len(cur_shape): raise ValueError(err_str) cur_shape = (1,) * (len(shape) - len(cur_shape)) + cur_shape cur_shape_arr = np.array(cur_shape) broadcasting_axes = np.nonzero(cur_shape_arr != np.array(shape)) if (cur_shape_arr[broadcasting_axes] != 1).any(): raise ValueError(err_str) if cur_shape != self.shape: return broadcast_to(self.reshape(cur_shape), shape=shape) else: return broadcast_to(self, shape=tuple(shape)) # pylint: enable= undefined-variable def wait_to_read(self): """Block until all pending writes operations on current NDArray are finished. This function will return when all the pending writes to the current NDArray finishes. There can still be pending read going on when the function returns. """ check_call(_LIB.MXNDArrayWaitToRead(self.handle)) @property def shape(self): """Get shape of current NDArray. Returns ------- a tuple representing shape of current ndarray """ ndim = mx_uint() pdata = ctypes.POINTER(mx_uint)() check_call(_LIB.MXNDArrayGetShape( self.handle, ctypes.byref(ndim), ctypes.byref(pdata))) return tuple(pdata[:ndim.value]) @property def size(self): """Get size of current NDArray. Returns ------- an int representing size of current ndarray """ return np.prod(self.shape) @property def context(self): """Get context of current NDArray. Returns ------- context : mxnet.Context The context of current NDArray. """ dev_typeid = ctypes.c_int() dev_id = ctypes.c_int() check_call(_LIB.MXNDArrayGetContext( self.handle, ctypes.byref(dev_typeid), ctypes.byref(dev_id))) return Context(Context.devtype2str[dev_typeid.value], dev_id.value) @property def dtype(self): """Get data type of current NDArray. Returns ------- an numpy.dtype object representing type of current ndarray """ mx_dtype = ctypes.c_int() check_call(_LIB.MXNDArrayGetDType( self.handle, ctypes.byref(mx_dtype))) return _DTYPE_MX_TO_NP[mx_dtype.value] @property # pylint: disable= invalid-name, undefined-variable def T(self): """Get transpose of current NDArray""" if len(self.shape) != 2: raise ValueError('Only 2D matrix is allowed to be transposed') return transpose(self) # pylint: enable= invalid-name, undefined-variable def asnumpy(self): """Return a copied numpy array of current array. Returns ------- array : numpy.ndarray A copy of array content. """ data = np.empty(self.shape, dtype=self.dtype) check_call(_LIB.MXNDArraySyncCopyToCPU( self.handle, data.ctypes.data_as(ctypes.c_void_p), ctypes.c_size_t(data.size))) return data def asscalar(self): """Return a CPU scalar(float) of current ndarray. This ndarray must have shape (1,) Returns ------- scalar : np.float The scalar representation of the ndarray. """ if self.shape != (1,): raise ValueError("The current array is not a scalar") return self.asnumpy()[0] def astype(self, dtype): """Return a copied numpy array of current array with specified type. Parameters ---------- dtype : numpy.dtype or string Desired type of result array. Returns ------- array : numpy.ndarray A copy of array content. """ res = empty(self.shape, ctx=self.context, dtype=dtype) self.copyto(res) return res def copyto(self, other): """Copy the content of current array to other. When other is NDArray, the content is copied over. When other is a Context, a new NDArray in the context will be created as target Parameters ---------- other : NDArray or Context Target NDArray or context we want to copy data to. Returns ------- dst : NDArray The copy target NDArray """ if isinstance(other, NDArray): if other.handle is self.handle: warnings.warn('copy an array to itself, is it intended?', RuntimeWarning) return return _internal._copyto(self, out=other) elif isinstance(other, Context): hret = NDArray(_new_alloc_handle(self.shape, other, True, self.dtype)) return _internal._copyto(self, out=hret) else: raise TypeError('copyto do not support type ' + str(type(other))) def copy(self): """Make a copy of the current ndarray on the same context Return ------ cpy : NDArray The copy """ return self.copyto(self.context) # pylint: enable= no-member def as_in_context(self, context): """Return an `NDArray` that lives in the target context. If the array is already in that context, `self` is returned. Otherwise, a copy is made. Parameters ---------- context : Context The target context we want the return value to live in. Returns ------- A copy or `self` as an `NDArray` that lives in the target context. """ if self.context == context: return self return self.copyto(context) def onehot_encode(indices, out): """One hot encoding indices into matrix out. Parameters ---------- indices: NDArray An NDArray containing indices of the categorical features. out: NDArray The result holder of the encoding. Returns ------- out: Array Same as out. """ # pylint: disable= no-member, protected-access return _internal._onehot_encode(indices, out, out=out) # pylint: enable= no-member, protected-access def empty(shape, ctx=None, dtype=mx_real_t): """Create an empty uninitialized new NDArray, with specified shape. Parameters ---------- shape : tuple shape of the NDArray. ctx : Context, optional The context of the NDArray, default to current default context. Returns ------- out: Array The created NDArray. """ if isinstance(shape, int): shape = (shape, ) if ctx is None: ctx = Context.default_ctx return NDArray(handle=_new_alloc_handle(shape, ctx, False, dtype)) #pylint: disable= too-many-arguments, no-member, protected-access def _ufunc_helper(lhs, rhs, fn_array, fn_scalar, lfn_scalar, rfn_scalar=None): """ Helper function for element-wise operation The function will perform numpy-like broadcasting if needed and call different functions Parameters ---------- lhs : NDArray or numeric value left hande side operand rhs : NDArray or numeric value right hand side operand fn_array : function function to be called if both lhs and rhs are of NDArray type fn_scalar : function function to be called if both lhs and rhs are numeric values lfn_scalar : function function to be called if lhs is NDArray while rhs is numeric value rfn_scalar : function function to be called if lhs is numeric value while rhs is NDArray; if none is provided, then the function is commutative, so rfn_scalar is equal to lfn_scalar Returns ------- out: NDArray result array """ if isinstance(lhs, numeric_types): if isinstance(rhs, numeric_types): return fn_scalar(lhs, rhs) else: if rfn_scalar is None: # commutative function return lfn_scalar(rhs, float(lhs)) else: return rfn_scalar(rhs, float(lhs)) elif isinstance(rhs, numeric_types): return lfn_scalar(lhs, float(rhs)) elif isinstance(rhs, NDArray): # check whether broadcasting is needed lsize = functools.reduce(operator.mul, lhs.shape) rsize = functools.reduce(operator.mul, rhs.shape) if lsize < rsize: lhs = lhs.broadcast_to(rhs.shape) elif lsize > rsize: rhs = rhs.broadcast_to(lhs.shape) return fn_array(lhs, rhs) else: raise TypeError('type %s not supported' % str(type(rhs))) #pylint: enable= too-many-arguments, no-member, protected-access def add(lhs, rhs): """ Perform element-wise addition Parameters ---------- lhs : Array or float value left hand side operand rhs : Array of float value right hand side operand Returns ------- out: Array result array """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, _internal._plus, operator.add, _internal._plus_scalar, None) # pylint: enable= no-member, protected-access def subtract(lhs, rhs): """ Perform element-wise subtract Parameters ---------- lhs : Array or float value left hand side operand rhs : Array of float value right hand side operand Returns ------- out: Array result array """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, _internal._minus, operator.sub, _internal._minus_scalar, _internal._rminus_scalar) # pylint: enable= no-member, protected-access def multiply(lhs, rhs): """ Perform element-wise multiplication Parameters ---------- lhs : Array or float value left hand side operand rhs : Array of float value right hand side operand Returns ------- out: Array result array """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, _internal._mul, operator.mul, _internal._mul_scalar, None) # pylint: enable= no-member, protected-access def divide(lhs, rhs): """ Perform element-wise divide Parameters ---------- lhs : Array or float value left hand side operand rhs : Array of float value right hand side operand Returns ------- out: Array result array """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, _internal._div, operator.truediv, _internal._div_scalar, _internal._rdiv_scalar) # pylint: enable= no-member, protected-access def power(lhs, rhs): """ Perform power operator Parameters ---------- lhs : Array or float value left hand side operand rhs : Array of float value right hand side operand Returns ------- out: Array result array """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, _internal._power, operator.pow, _internal._power_scalar, _internal._rpower_scalar) # pylint: enable= no-member, protected-access def maximum(lhs, rhs): """ Perform maximum operator Parameters ---------- lhs : Array or float value left hand side operand rhs : Array of float value right hand side operand Returns ------- out: Array result array """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, _internal._maximum, lambda x, y: x if x > y else y, _internal._maximum_scalar, None) # pylint: enable= no-member, protected-access def minimum(lhs, rhs): """ Perform minimum operator Parameters ---------- lhs : Array or float value left hand side operand rhs : Array of float value right hand side operand Returns ------- out: Array result array """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, _internal._minimum, lambda x, y: x if x < y else y, _internal._minimum_scalar, None) # pylint: enable= no-member, protected-access def true_divide(lhs, rhs): """ Same as numpy's true_divide. It adjusts the output type to present the best answer, regardless of input types. """ return divide(lhs, rhs) def negative(arr): """ Return the negation of array values """ return multiply(arr, -1.0) def zeros(shape, ctx=None, dtype=mx_real_t): """Create a new NDArray filled with 0, with specified shape. Parameters ---------- shape : tuple shape of the NDArray. ctx : Context, optional. The context of the NDArray, default to current default context. Returns ------- out: Array The created NDArray. """ arr = empty(shape, ctx, dtype) arr[:] = 0.0 return arr def ones(shape, ctx=None, dtype=mx_real_t): """Create a new NDArray filled with 1, with specified shape. Parameters ---------- shape : tuple shape of the NDArray. ctx : Context, optional The context of the NDArray, default to current default context. Returns ------- out: Array The created NDArray. """ arr = empty(shape, ctx, dtype) arr[:] = 1.0 return arr def full(shape, val, ctx=None): """Create a new NDArray filled with given value, with specified shape. Parameters ---------- shape : tuple shape of the NDArray. val : float value to be filled with. ctx : Context, optional The context of the NDArray, default to current default context. Returns ------- out: Array The created NDArray. """ arr = empty(shape, ctx) arr[:] = val return arr def array(source_array, ctx=None, dtype=mx_real_t): """Create a new NDArray that copies content from source_array. Parameters ---------- source_array : array_like Source data to create NDArray from. ctx : Context, optional The context of the NDArray, default to current default context. Returns ------- out: Array The created NDArray. """ if not isinstance(source_array, np.ndarray): try: source_array = np.array(source_array, dtype=dtype) except: raise TypeError('source_array must be array like object') arr = empty(source_array.shape, ctx, dtype) arr[:] = source_array return arr def concatenate(arrays, axis=0, always_copy=True): """Concatenate a list of NDArrays along the first dimension. Parameters ---------- arrays : list of NDArray Arrays to be concatenate. They must have identical shape except the first dimension. They also must have the same data type. axis : int The axis along which to concatenate. always_copy : bool Default `True`. When not `True`, if the arrays only contain one `NDArray`, that element will be returned directly, avoid copying. Returns ------- An `NDArray` that lives on the same context as `arrays[0].context`. """ assert isinstance(arrays, list) assert len(arrays) > 0 assert isinstance(arrays[0], NDArray) if not always_copy and len(arrays) == 1: return arrays[0] shape_axis = arrays[0].shape[axis] shape_rest1 = arrays[0].shape[0:axis] shape_rest2 = arrays[0].shape[axis+1:] dtype = arrays[0].dtype for arr in arrays[1:]: shape_axis += arr.shape[axis] assert shape_rest1 == arr.shape[0:axis] assert shape_rest2 == arr.shape[axis+1:] assert dtype == arr.dtype ret_shape = shape_rest1 + (shape_axis,) + shape_rest2 ret = empty(ret_shape, ctx=arrays[0].context, dtype=dtype) idx = 0 begin = [0 for _ in ret_shape] end = list(ret_shape) for arr in arrays: if axis == 0: ret[idx:idx+arr.shape[0]] = arr else: begin[axis] = idx end[axis] = idx+arr.shape[axis] # pylint: disable=no-member,protected-access _internal._crop_assign(ret, arr, out=ret, begin=tuple(begin), end=tuple(end)) # pylint: enable=no-member,protected-access idx += arr.shape[axis] return ret def load(fname): """Load ndarray from binary file. You can also use pickle to do the job if you only work on python. The advantage of load/save is the file is language agnostic. This means the file saved using save can be loaded by other language binding of mxnet. You also get the benefit being able to directly load/save from cloud storage(S3, HDFS) Parameters ---------- fname : str The name of the file.Can be S3 or HDFS address (remember built with S3 support). Example of fname: - `s3://my-bucket/path/my-s3-ndarray` - `hdfs://my-bucket/path/my-hdfs-ndarray` - `/path-to/my-local-ndarray` Returns ------- out : list of NDArray or dict of str to NDArray List of NDArray or dict of str->NDArray, depending on what was saved. """ if not isinstance(fname, string_types): raise TypeError('fname need to be string') out_size = mx_uint() out_name_size = mx_uint() handles = ctypes.POINTER(NDArrayHandle)() names = ctypes.POINTER(ctypes.c_char_p)() check_call(_LIB.MXNDArrayLoad(c_str(fname), ctypes.byref(out_size), ctypes.byref(handles), ctypes.byref(out_name_size), ctypes.byref(names))) if out_name_size.value == 0: return [NDArray(NDArrayHandle(handles[i])) for i in range(out_size.value)] else: assert out_name_size.value == out_size.value return dict( (py_str(names[i]), NDArray(NDArrayHandle(handles[i]))) for i in range(out_size.value)) def save(fname, data): """Save list of NDArray or dict of str->NDArray to binary file. You can also use pickle to do the job if you only work on python. The advantage of load/save is the file is language agnostic. This means the file saved using save can be loaded by other language binding of mxnet. You also get the benefit being able to directly load/save from cloud storage(S3, HDFS) Parameters ---------- fname : str The name of the file.Can be S3 or HDFS address (remember built with S3 support). Example of fname: - `s3://my-bucket/path/my-s3-ndarray` - `hdfs://my-bucket/path/my-hdfs-ndarray` - `/path-to/my-local-ndarray` data : list of NDArray or dict of str to NDArray The data to be saved. """ handles = [] if isinstance(data, dict): keys = [] for key, val in data.items(): if not isinstance(key, string_types): raise TypeError('save only accept dict str->NDArray or list of NDArray') if not isinstance(val, NDArray): raise TypeError('save only accept dict str->NDArray or list of NDArray') keys.append(c_str(key)) handles.append(val.handle) keys = c_array(ctypes.c_char_p, keys) else: for val in data: if not isinstance(val, NDArray): raise TypeError('save only accept dict str->NDArray or list of NDArray') handles.append(val.handle) keys = None check_call(_LIB.MXNDArraySave(c_str(fname), mx_uint(len(handles)), c_array(NDArrayHandle, handles), keys)) def imdecode(str_img, clip_rect=(0, 0, 0, 0), out=None, index=0, channels=3, mean=None): """Decode an image from string. Requires OpenCV to work. Parameters ---------- str_img : str binary image data clip_rect : iterable of 4 int clip decoded image to rectangle (x0, y0, x1, y1) out : NDArray output buffer. can be 3 dimensional (c, h, w) or 4 dimensional (n, c, h, w) index : int output decoded image to i-th slice of 4 dimensional buffer channels : int number of channels to output. Decode to grey scale when channels = 1. mean : NDArray subtract mean from decode image before outputing. """ # pylint: disable= no-member, protected-access, too-many-arguments if mean is None: mean = NDArray(_new_empty_handle()) if out is None: return _internal._imdecode(mean, index, clip_rect[0], clip_rect[1], clip_rect[2], clip_rect[3], channels, len(str_img), str_img=str_img) else: return _internal._imdecode(mean, index, clip_rect[0], clip_rect[1], clip_rect[2], clip_rect[3], channels, len(str_img), str_img=str_img, out=out) # pylint: disable=too-many-locals, invalid-name def _make_ndarray_function(handle): """Create a NDArray function from the FunctionHandle.""" NDARRAY_ARG_BEFORE_SCALAR = 1 ACCEPT_EMPTY_MUTATE_TARGET = 1 << 2 # Get the property of NDArray n_used_vars = mx_uint() n_scalars = mx_uint() n_mutate_vars = mx_uint() type_mask = ctypes.c_int() check_call(_LIB.MXFuncDescribe( handle, ctypes.byref(n_used_vars), ctypes.byref(n_scalars), ctypes.byref(n_mutate_vars), ctypes.byref(type_mask))) n_mutate_vars = n_mutate_vars.value n_used_vars = n_used_vars.value n_scalars = n_scalars.value type_mask = type_mask.value accept_empty_mutate = (type_mask & ACCEPT_EMPTY_MUTATE_TARGET) != 0 # infer type of the function if (type_mask & NDARRAY_ARG_BEFORE_SCALAR) != 0: use_vars_range = range(0, n_used_vars) scalar_range = range(n_used_vars, n_used_vars + n_scalars) else: scalar_range = range(0, n_scalars) use_vars_range = range(n_scalars, n_used_vars + n_scalars) # Get the information from the function name = ctypes.c_char_p() desc = ctypes.c_char_p() num_args = mx_uint() arg_names = ctypes.POINTER(ctypes.c_char_p)() arg_types = ctypes.POINTER(ctypes.c_char_p)() arg_descs = ctypes.POINTER(ctypes.c_char_p)() ret_type = ctypes.c_char_p() check_call(_LIB.MXFuncGetInfo( handle, ctypes.byref(name), ctypes.byref(desc), ctypes.byref(num_args), ctypes.byref(arg_names), ctypes.byref(arg_types), ctypes.byref(arg_descs), ctypes.byref(ret_type))) func_name = py_str(name.value) param_str = ctypes2docstring(num_args, arg_names, arg_types, arg_descs) doc_str = ('%s\n\n' + '%s\n' + 'out : NDArray, optional\n' + ' The output NDArray to hold the result.\n\n'+ 'Returns\n' + '-------\n' + 'out : NDArray\n'+ ' The output of binary function.') doc_str = doc_str % (py_str(desc.value), param_str) # Definition of internal functions. def binary_ndarray_function(lhs, rhs, out=None, **kwargs): """Internal binary function """ if out: if not isinstance(out, NDArray): raise TypeError('out must be NDArray') if not out.writable: raise TypeError('out must be writable') else: if not accept_empty_mutate: raise TypeError('argument out is required to call %s' % func_name) out = NDArray(_new_empty_handle()) check_call(_LIB.MXFuncInvokeEx( \ handle, \ c_array(NDArrayHandle, (lhs.handle, rhs.handle)), \ c_array(mx_float, ()), \ c_array(NDArrayHandle, (out.handle,)), \ ctypes.c_int(len(kwargs)), \ c_array(ctypes.c_char_p, [c_str(key) for key in kwargs.keys()]), \ c_array(ctypes.c_char_p, [c_str(str(i)) for i in kwargs.values()]))) return out def unary_ndarray_function(src, out=None, *args, **kwargs): """internal NDArray function""" if out: if not isinstance(out, NDArray): raise TypeError('out must be NDArray') if not out.writable: raise TypeError('out must be writable') else: if not accept_empty_mutate: raise TypeError('argument out is required to call %s' % func_name) out = NDArray(_new_empty_handle()) check_call(_LIB.MXFuncInvokeEx( \ handle, \ c_array(NDArrayHandle, (src.handle,)), \ c_array(mx_float, [args[i] for i in scalar_range]), \ c_array(NDArrayHandle, (out.handle,)), \ ctypes.c_int(len(kwargs)), \ c_array(ctypes.c_char_p, [c_str(key) for key in kwargs.keys()]), \ c_array(ctypes.c_char_p, [c_str(str(i)) for i in kwargs.values()]))) return out def generic_ndarray_function(*args, **kwargs): """Invoke this function by passing in parameters Parameters ---------- *args Positional arguments of input scalars and NDArray out : NDArray or tuple of NDArray, optional Output NDArray, used to hold the output result. Returns ------- out : NDArray The result NDArray(tuple) of result of computation. """ if 'out' in kwargs: mutate_vars = kwargs['out'] if isinstance(mutate_vars, NDArray): mutate_vars = (mutate_vars,) if len(mutate_vars) != n_mutate_vars: raise TypeError('expect %d out in %s', n_mutate_vars, func_name) del kwargs['out'] else: if accept_empty_mutate: mutate_vars = tuple( NDArray(_new_empty_handle()) for i in range(n_mutate_vars)) else: raise TypeError('argument out is required to call %s' % func_name) check_call(_LIB.MXFuncInvokeEx( \ handle, \ c_array(NDArrayHandle, [args[i].handle for i in use_vars_range]), \ c_array(mx_float, [args[i] for i in scalar_range]), \ c_array(NDArrayHandle, [v.handle for v in mutate_vars]), \ ctypes.c_int(len(kwargs)), \ c_array(ctypes.c_char_p, [c_str(key) for key in kwargs.keys()]), \ c_array(ctypes.c_char_p, [c_str(str(i)) for i in kwargs.values()]))) if n_mutate_vars == 1: return mutate_vars[0] else: return mutate_vars # End of function declaration if n_mutate_vars == 1 and n_used_vars == 2 and n_scalars == 0: ret_function = binary_ndarray_function elif n_mutate_vars == 1 and n_used_vars == 1 and n_scalars == 0: ret_function = unary_ndarray_function else: ret_function = generic_ndarray_function ret_function.__name__ = func_name ret_function.__doc__ = doc_str return ret_function # pylint: enable=too-many-locals, invalid-name def _init_ndarray_module(): """List and add all the ndarray functions to current module.""" plist = ctypes.POINTER(FunctionHandle)() size = ctypes.c_uint() check_call(_LIB.MXListFunctions(ctypes.byref(size), ctypes.byref(plist))) module_obj = sys.modules[__name__] module_internal = sys.modules["mxnet._ndarray_internal"] for i in range(size.value): hdl = FunctionHandle(plist[i]) function = _make_ndarray_function(hdl) # if function name starts with underscore, register as internal namespace if function.__name__.startswith('_'): setattr(module_internal, function.__name__, function) else: fname = function.__name__ fn_obj = getattr(module_obj, fname, None) if fn_obj is None: setattr(module_obj, fname, function) else: setattr(module_obj, fname + '_internal', function) # Initialize the NDArray module _init_ndarray_module()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 2, 279, 2645, 600, 25, 15560, 28, 1165, 12, 21834, 12, 6615, 11, 2266, 18156, 12, 18780, 259, 11, 6861, 12, 15526, 198, 37811, 8575, 19182, 7824, 286, 285, 87, 3262, 526, 15931, 198, 6738, 1159...
2.171309
17,915
from flask import request from flask_babelex import gettext from project import app, babel @babel.localeselector
[ 6738, 42903, 1330, 2581, 198, 6738, 42903, 62, 65, 11231, 2588, 1330, 651, 5239, 198, 198, 6738, 1628, 1330, 598, 11, 9289, 417, 628, 198, 31, 65, 9608, 13, 17946, 2040, 9509, 273, 628 ]
3.441176
34
# Generated by Django 3.0.4 on 2020-05-05 17:56 import django.contrib.auth.validators import django.core.validators from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 15, 13, 19, 319, 12131, 12, 2713, 12, 2713, 1596, 25, 3980, 198, 198, 11748, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 12102, 2024, 198, 11748, 42625, 14208, 13, 7295, 13, 12102, 2024, 198, 6738,...
3
53
#!/usr/bin/python # -*- coding: utf-8 -*- """ Examples of how to use scripts in this directory """ from db_api import accident accident1_id = 11 accident1 = accident.new( id=accident1_id, country='USA', timestamp='TIMESTAMP \'2014-05-16 15:36:38\'', day_of_week=7, latitude=23.3453451, longitude=56.23424234, persons_count=3, fatalities_count=2, vehicles_count=1, speed_limit=-1 ) accident.insert(accident1) accident.delete(accident1_id) accident.insert(accident1)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 27730, 286, 703, 284, 779, 14750, 287, 428, 8619, 198, 37811, 198, 198, 6738, 20613, 62, 15042, 1330, 5778, ...
2.345622
217
#!/usr/bin/env python # coding=utf8 PLUGIN_CLASS_GET_HANDLER = 'get_handler' PLUGIN_CLASS_KEY_REGISTER = '__register__'
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 28, 40477, 23, 198, 198, 6489, 7340, 1268, 62, 31631, 62, 18851, 62, 39, 6981, 39878, 796, 705, 1136, 62, 30281, 6, 198, 6489, 7340, 1268, 62, 31631, 62, 20373, 62, 31553, ...
2.372549
51
import torch from datetime import datetime
[ 11748, 28034, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198 ]
4.3
10
""" fanout模式下,传递到 exchange 的消息将会转发到所有与其绑定的 queue 上。 不需要指定 routing_key ,即使指定了也是无效。 需要提前将 exchange 和 queue 绑定,一个 exchange 可以绑定多个 queue,一个queue可以绑定多个exchange。 需要先启动 订阅者,此模式下的队列是 consumer 随机生成的,发布者 仅仅发布消息到 exchange ,由 exchange 转发消息至 queue。 """ import json import pika if __name__ == '__main__': credentials = pika.PlainCredentials('test', '123456') # mq用户名和密码 # 虚拟队列需要指定参数 virtual_host,如果是默认的可以不填。 connection = pika.BlockingConnection(pika.ConnectionParameters( host='api.mdavid.cn', port=5672, virtual_host='xiang_test', credentials=credentials)) channel = connection.channel() # 声明exchange,由exchange指定消息在哪个队列传递,如不存在,则创建。 # durable = True 代表exchange持久化存储,False 非持久化存储 channel.exchange_declare(exchange='python-test', durable=True, exchange_type='fanout') for i in range(10): message = json.dumps({'OrderId': "1000%s" % i}) # 向队列插入数值 routing_key是队列名。 # delivery_mode = 2 声明消息在队列中持久化, # delivery_mode = 1 消息非持久化。routing_key 不需要配置 channel.basic_publish(exchange='python-test', routing_key='queue_1', body=message, properties=pika.BasicProperties(delivery_mode=2)) print(message) connection.close()
[ 37811, 198, 24408, 448, 162, 101, 94, 28156, 237, 10310, 233, 171, 120, 234, 27670, 254, 34460, 240, 26344, 108, 5163, 13328, 248, 226, 162, 114, 230, 162, 223, 107, 49546, 27670, 248, 164, 121, 105, 20998, 239, 26344, 108, 33699, 222...
1.432591
853
import pytest from pydicom.dataset import FileDataset, FileMetaDataset @pytest.fixture(scope='function')
[ 11748, 12972, 9288, 198, 198, 6738, 279, 5173, 291, 296, 13, 19608, 292, 316, 1330, 9220, 27354, 292, 316, 11, 9220, 48526, 27354, 292, 316, 628, 198, 31, 9078, 9288, 13, 69, 9602, 7, 29982, 11639, 8818, 11537, 198 ]
2.769231
39
from CHECLabPy.plotting.camera import CameraImage import numpy as np from matplotlib import pyplot as plt ci = CameraImageClick.from_camera_version("1.1.0") plt.show() np.save("click_camera.npy", ci.image)
[ 6738, 5870, 2943, 17822, 20519, 13, 29487, 889, 13, 25695, 1330, 20432, 5159, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 83, 628, 198, 198, 979, 796, 20432, 5159, 8164, 13, 6738, 62, ...
2.786667
75
#!/usr/bin/env python3 """ Gaussian mixture fitting with Nested Sampling. This module was tested in the main `nestfit` repo on bare arrays and Gaussian components -- without a spectral axis, units, or other necessary complications. The `.wrapped` references a Cython implementation of the Gaussian model class. """ import ctypes import operator from pathlib import Path import h5py import numpy as np import pandas as pd from scipy import (special, stats) from matplotlib import ticker from matplotlib import pyplot as plt import corner import pymultinest from .wrapped import CGaussianModel plt.rc('font', size=10, family='serif') plt.rc('text', usetex=True) plt.rc('xtick', direction='out', top=True) plt.rc('ytick', direction='out', right=True) ROOT_DIR = Path('/lustre/aoc/users/bsvoboda/temp/nestfit') DATA_DIR = ROOT_DIR / Path('data') PLOT_DIR = ROOT_DIR / Path('plots')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 198, 35389, 31562, 11710, 15830, 351, 399, 7287, 3409, 11347, 13, 770, 8265, 373, 6789, 287, 262, 198, 12417, 4600, 77, 395, 11147, 63, 29924, 319, 6247, 26515, 290, 12822, ...
3.016667
300
# ROS packages required from eagerx import Object, Engine, Node, initialize, log, process initialize("eagerx_core", anonymous=True, log_level=log.INFO) # Environment from eagerx.core.env import EagerxEnv from eagerx.core.graph import Graph from eagerx.wrappers import Flatten # Implementation specific import eagerx.nodes # Registers butterworth_filter # noqa # pylint: disable=unused-import import eagerx_ode # Registers OdeEngine # noqa # pylint: disable=unused-import import eagerx_dcsc_setups # Registers Pendulum # noqa # pylint: disable=unused-import # Other import numpy as np import stable_baselines3 as sb if __name__ == "__main__": # Define rate (depends on rate of ode) rate = 30.0 # Initialize empty graph graph = Graph.create() # Create pendulum pendulum = Object.make( "Pendulum", "pendulum", render_shape=[480, 480], sensors=["x"], states=["model_state", "model_parameters"], ) # Visualize EngineGraph pendulum.gui(engine_id="OdeEngine") graph.add(pendulum) # Create Butterworth filter bf = Node.make( "ButterworthFilter", name="bf", rate=rate, N=2, Wn=13, process=process.NEW_PROCESS, ) graph.add(bf) # Connect the nodes graph.connect(action="action", target=bf.inputs.signal) graph.connect(source=bf.outputs.filtered, target=pendulum.actuators.u) graph.connect(source=pendulum.sensors.x, observation="observation", window=1) # Add rendering graph.add_component(pendulum.sensors.image) graph.render(source=pendulum.sensors.image, rate=10, display=True) # Visualize Graph graph.gui() # Define engines engine = Engine.make("OdeEngine", rate=rate, sync=True, real_time_factor=0, process=process.NEW_PROCESS) # Define step function # Initialize Environment env = Flatten(EagerxEnv(name="ode_env", rate=rate, graph=graph, engine=engine, step_fn=step_fn)) # Initialize learner (kudos to Antonin) model = sb.SAC("MlpPolicy", env, verbose=1) # First train in simulation for 5 minutes and save env.render("human") model.learn(total_timesteps=int(300 * rate))
[ 2, 48263, 10392, 2672, 198, 6738, 11069, 87, 1330, 9515, 11, 7117, 11, 19081, 11, 41216, 11, 2604, 11, 1429, 198, 198, 36733, 1096, 7203, 68, 3536, 87, 62, 7295, 1600, 11614, 28, 17821, 11, 2604, 62, 5715, 28, 6404, 13, 10778, 8, ...
2.602594
848
from .dense import DenseNet
[ 6738, 764, 67, 1072, 1330, 360, 1072, 7934 ]
3.375
8
from networkx.utils.misc import * from networkx.utils.decorators import * from networkx.utils.random_sequence import * from networkx.utils.union_find import * from networkx.utils.rcm import * from networkx.utils.heaps import *
[ 6738, 3127, 87, 13, 26791, 13, 44374, 1330, 1635, 198, 6738, 3127, 87, 13, 26791, 13, 12501, 273, 2024, 1330, 1635, 198, 6738, 3127, 87, 13, 26791, 13, 25120, 62, 43167, 1330, 1635, 198, 6738, 3127, 87, 13, 26791, 13, 24592, 62, 197...
3.338235
68
# Preprocess an input text: # - delete punctuation symbols (commas, periods, # exclamation and question marks ,.!?), # - convert all symbols to lowercase. # Then print your text. # Punctuation marks appear not only at the end of the input # string, so you have to figure out how to get rid of all of them. print(input().replace('?', '').replace('!', '').replace(',', '').replace('.', '').lower())
[ 2, 3771, 14681, 281, 5128, 2420, 25, 198, 198, 2, 220, 532, 12233, 21025, 2288, 14354, 357, 785, 5356, 11, 9574, 11, 198, 2, 220, 220, 220, 409, 20931, 290, 1808, 8849, 837, 13, 22857, 828, 198, 2, 220, 532, 10385, 477, 14354, 284...
3.290323
124
import re from typing import Optional from flask import redirect, render_template, request, url_for from koro.dataset import JsonLoader from koro.manipulation import first_true
[ 11748, 302, 198, 6738, 19720, 1330, 32233, 198, 198, 6738, 42903, 1330, 18941, 11, 8543, 62, 28243, 11, 2581, 11, 19016, 62, 1640, 198, 198, 6738, 479, 16522, 13, 19608, 292, 316, 1330, 449, 1559, 17401, 198, 6738, 479, 16522, 13, 805...
3.64
50
import mimeparse from django.contrib.auth.models import AnonymousUser from hyperadmin.states import State class APIRequest(object): """ An API Request """ @property @property def get_response_type(self): """ Returns the active response type to be used :rtype: string """ val = self.META.get('HTTP_ACCEPT', self.META.get('CONTENT_TYPE', '')) media_types = self.media_types.keys() if not media_types: return val return mimeparse.best_match(media_types, val) or val def get_request_type(self): """ Returns the active request type to be used :rtype: string """ val = self.META.get('CONTENT_TYPE', self.META.get('HTTP_ACCEPT', '')) media_types = self.media_types.keys() if not media_types: return val return mimeparse.best_match(media_types, val) or val def get_request_media_type(self): """ Returns the request media type to be used or raises an error :raises ValueError: when the requested content type is unrecognized :rtype: string """ content_type = self.get_request_type() media_type_cls = self.media_types.get(content_type, None) if media_type_cls is None: raise ValueError('Unrecognized request content type "%s". Choices are: %s' % (content_type, self.media_types.keys())) return media_type_cls(self) def get_response_media_type(self): """ Returns the response media type to be used or raises an error :raises ValueError: when the requested content type is unrecognized :rtype: string """ content_type = self.get_response_type() media_type_cls = self.media_types.get(content_type, None) if media_type_cls is None: raise ValueError('Unrecognized request content type "%s". Choices are: %s' % (content_type, self.media_types.keys())) return media_type_cls(self) def get_endpoint(self, urlname): """ Returns a bound endpoint matching the urlname :param urlname: The urlname to find :type urlname: string :raises KeyError: when the urlname does not match any endpoints :rtype: Endpoint """ if urlname not in self.endpoint_state['endpoints']: endpoint = self.site.get_endpoint_from_urlname(urlname) bound_endpoint = endpoint.fork(api_request=self) if bound_endpoint != self.endpoint_state['endpoints'][urlname]: pass return self.endpoint_state['endpoints'][urlname] def record_endpoint(self, endpoint): """ Record the endpoint in our urlname cache :param resource: Endpoint """ assert endpoint.api_request == self urlname = endpoint.get_url_name() if urlname not in self.endpoint_state['endpoints']: self.endpoint_state['endpoints'][urlname] = endpoint #else: # original = self.endpoint_state['endpoints'][urlname] # self.site.get_logger().debug('Double registration at api request level on %s by %s, original: %s' % (urlname, endpoint, original)) def get_link_prototypes(self, endpoint): """ Returns the link prototypes to be used by the endpint :param endpoint: endpoint object :rtype: list of link prototypes """ urlname = endpoint.get_url_name() if urlname not in self.endpoint_state['link_prototypes']: link_prototypes = endpoint.create_link_prototypes() self.endpoint_state['link_prototypes'][urlname] = link_prototypes return self.endpoint_state['link_prototypes'][urlname] def get_site(self): """ Returns the bound site :rtype: SiteResource """ if 'site' not in self.endpoint_state: bound_site = self.site.fork(api_request=self) self.endpoint_state['site'] = bound_site return self.endpoint_state['site'] def generate_response(self, link, state): """ Returns a response generated from the response media type :param link: The active link representing the endpoint's response :param state: The endpoint's state :rtype: [Http]Response """ media_type = self.get_response_media_type() response_type = self.get_response_type() return media_type.serialize(content_type=response_type, link=link, state=state) def generate_options_response(self, links, state): """ Returns an OPTIONS response generated from the response media type :param links: dictionary mapping available HTTP methods to a link :param state: The endpoint's state :rtype: [Http]Response """ media_type = self.get_response_media_type() response_type = self.get_response_type() return media_type.options_serialize(content_type=response_type, links=links, state=state) class InternalAPIRequest(APIRequest): """ An Internal API Request """ class HTTPAPIRequest(APIRequest): """ Represents an API Request spawned from a Django HTTP Request """ get_to_meta_map = { '_HTTP_ACCEPT':'HTTP_ACCEPT', '_CONTENT_TYPE':'CONTENT_TYPE', } @property @property @property @property class Namespace(object): """ Represents alternative data associated with the current api request Namespaced data is provided by another resource through an internal api request """ @property @property
[ 11748, 285, 524, 29572, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 19200, 12982, 198, 198, 6738, 8718, 28482, 13, 27219, 1330, 1812, 628, 198, 4871, 7824, 18453, 7, 15252, 2599, 198, 220, 220, 220, 37227, ...
2.482472
2,282
from grafo_adj_nao_dir import * g8 = Grafo([], {}) for i in ['a', 'b', 'c', 'd', 'e', 'f', 'g']: g8.adicionaVertice(i) g8.adicionaAresta("a-b", 5) g8.adicionaAresta("a-e", 12) g8.adicionaAresta("b-g", 4) g8.adicionaAresta("b-f", 9) g8.adicionaAresta("c-d", 10) g8.adicionaAresta("c-f", 7) g8.adicionaAresta("d-f", 8) g8.adicionaAresta("c-e", 10) g8.adicionaAresta("e-g", 2) g8.adicionaAresta("f-g", 6) print(g8.Kruskal())
[ 6738, 7933, 6513, 62, 41255, 62, 2616, 78, 62, 15908, 1330, 1635, 198, 70, 23, 796, 7037, 6513, 26933, 4357, 23884, 8, 198, 1640, 1312, 287, 37250, 64, 3256, 705, 65, 3256, 705, 66, 3256, 705, 67, 3256, 705, 68, 3256, 705, 69, 325...
1.827004
237
#!/usr/bin/python import socket def tcpping(host, port, timeout = 5): """ Does a TCP 'ping' Simply attempts a socket connection on the specified port 22 = SSH 23 = Telnet Timeout is 5 seconds Code "borrowed" from yantisj """ try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(timeout) s.connect((host, int(port))) s.shutdown(socket.SHUT_RD) return True except: pass return False
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 17802, 198, 198, 4299, 37096, 2105, 7, 4774, 11, 2493, 11, 26827, 796, 642, 2599, 198, 220, 220, 220, 37227, 8314, 257, 23633, 705, 13886, 6, 198, 220, 220, 220, 220, 220, 220, ...
2.182979
235
# Adapted for numpy/ma/cdms2 by convertcdms.py import adamsregrid import numpy import EzTemplate import vcs.test.support bg = vcs.test.support.bg ts=[] M = EzTemplate.Multi(1,5) for i in range(5): ts.append(M.get()) ## Prepare axes lon1 = numpy.arange(0,360,.25,'f')/180.*numpy.pi #.25 deg lat1 = numpy.arange(0,180,2,'f')/180.*numpy.pi #2 deg lev1 = numpy.arange(0,17,1,'f')+1. # 17 levs tim1 = numpy.arange(0,24,3,'f')+1. # 3hourly data lon2 = numpy.arange(0,360,5,'f')/180.*numpy.pi #5 deg lat2 = numpy.arange(0,180,4,'f')/180.*numpy.pi #4 deg lev2 = numpy.arange(0,17,4,'f')+1. # less levs tim2 = numpy.arange(0,24,6,'f')+1. # 6hourly data p1 = numpy.cos(lon1) p2 = p1[numpy.newaxis,:]*numpy.sin(lat1)[:,numpy.newaxis] p3 = p2[numpy.newaxis,:,:]*lev1[:,numpy.newaxis,numpy.newaxis] p4 = p3[numpy.newaxis,:,:,:]*tim1[:,numpy.newaxis,numpy.newaxis,numpy.newaxis] print 'Testing for 1D array/grid' interps = ['linear','linearLog','cubic','cubicLog'] M.x.clear() M.x.plot(p1,ts[0],bg=bg) for i in range(4): interp = interps[i] R = adamsregrid.Regrid(lon1,lon2,interp,0) po1 = R.rgrd(p1) M.x.plot(po1,ts[i+1],bg=bg) vcs.test.support.check_plot(M.x) print 'Testing for 2D array/grid' interps = ['linear','linearLog','cubic','cubicLog'] M.x.clear() M.x.plot(p2,ts[0],bg=bg) for i in range(4): interp = interps[i] R = adamsregrid.Regrid(lon1,lon2,interp,1, lat1,lat2,interp,0) po2 = R.rgrd(p2) M.x.plot(po2,ts[i+1],bg=bg) vcs.test.support.check_plot(M.x) print 'Testing for 3D array/grid' interps = ['linear','linearLog','cubic','cubicLog'] M.x.clear() M.x.plot(p3,ts[0],bg=bg) for i in range(4): interp = interps[i] R = adamsregrid.Regrid(lon1,lon2,interp,2, lat1,lat2,interp,1, lev1,lev2,interp,0, ) po3 = R.rgrd(p3) M.x.plot(po3,ts[i+1],bg=bg) vcs.test.support.check_plot(M.x) print 'Testing for 4D array/grid' interps = ['linear','linearLog','cubic','cubicLog'] M.x.clear() M.x.plot(p4,ts[0],bg=bg) for i in range(4): interp = interps[i] R = adamsregrid.Regrid(lon1,lon2,interp,3, lat1,lat2,interp,2, lev1,lev2,interp,1, tim1,tim2,interp,0, ) po4 = R.rgrd(p4) M.x.plot(po4,ts[i+1],bg=bg) vcs.test.support.check_plot(M.x) print 'Testing for 1D array/grid passing 2D' interps = ['linear','linearLog','cubic','cubicLog'] M.x.clear() M.x.plot(p2,ts[0],bg=bg) for i in range(4): interp = interps[i] R = adamsregrid.Regrid(lon1,lon2,interp,1) po2 = R.rgrd(p2) M.x.plot(po2,ts[i+1],bg=bg) vcs.test.support.check_plot(M.x)
[ 2, 30019, 276, 329, 299, 32152, 14, 2611, 14, 10210, 907, 17, 416, 10385, 10210, 907, 13, 9078, 198, 11748, 512, 4105, 260, 25928, 198, 11748, 299, 32152, 198, 11748, 21034, 30800, 198, 11748, 410, 6359, 13, 9288, 13, 11284, 198, 3590...
1.82777
1,498
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** from ... import _utilities import typing # Export this package's modules as members: from ._enums import * from .application import * from .application_package import * from .batch_account import * from .get_application import * from .get_application_package import * from .get_batch_account import * from .list_batch_account_keys import * from ._inputs import * from . import outputs
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 26144, 35986, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760, 644, 345, 389, 1804, 0, 17202, ...
3.794521
146
import ftplib from ftplib import FTP from sys import argv import warnings import functions as F from tqdm import tqdm import os warnings.filterwarnings('ignore') not_to_download = [ "LIDC-IDRI-0001", "LIDC-IDRI-0004", "LIDC-IDRI-0007", "LIDC-IDRI-0010", "LIDC-IDRI-0013", "LIDC-IDRI-0016", "LIDC-IDRI-0002", "LIDC-IDRI-0005", "LIDC-IDRI-0008", "LIDC-IDRI-0011", "LIDC-IDRI-0014", "LIDC-IDRI-0017", "LIDC-IDRI-0003", "LIDC-IDRI-0006", "LIDC-IDRI-0009", "LIDC-IDRI-0012", "LIDC-IDRI-0015" ] def _is_ftp_dir(ftp, name, guess_by_extension=True): """ simply determines if an item listed on the ftp server is a valid directory or not """ # if the name has a "." in the fourth to last position, its probably a file extension # this is MUCH faster than trying to set every file to a working directory, and will work 99% of time. if guess_by_extension is True: if len(name) >= 4: if name[-4] == '.': return False original_cwd = ftp.pwd() # remember the current working directory try: ftp.cwd(name) # try to set directory to new name ftp.cwd(original_cwd) # set it back to what it was return True except ftplib.error_perm as e: print(e) return False except Exception as e: print(e) return False if __name__ == "__main__": if len(argv) is not 7: print("Usage: python download_ftp.py ftp_server ftp_path ssh_server ssh_username ssh_password ssh_path") else: ftp_server = argv[1] ftp_path = argv[2] ssh_server = argv[3] ssh_username = argv[4] ssh_password = argv[5] ssh_path = argv[6] ftp = FTP(ftp_server) ftp.login("", "") sftp = F.sftp_connect(ssh_server, ssh_username, ssh_password) download_ftp_tree(ftp, ftp_path, sftp, ssh_path)
[ 11748, 10117, 489, 571, 198, 6738, 10117, 489, 571, 1330, 45854, 198, 6738, 25064, 1330, 1822, 85, 198, 11748, 14601, 198, 11748, 5499, 355, 376, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 11748, 28686, 198, 198, 40539, 654, ...
2.106011
915
from django.shortcuts import render from django.http import HttpResponseRedirect from .models import Action from .models import Sport from .forms import ActionForm
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 7738, 1060, 198, 6738, 764, 27530, 1330, 7561, 198, 6738, 764, 27530, 1330, 12771, 198, 6738, 764, 23914, 1330, 7561, 8479, 628 ...
4.125
40
import os from django.conf import settings from django.shortcuts import render def render_special_markdown_template(request, template_name, relative_path): """ :param request: :param template_name: :param relative_path: markdown relative path from BASE_DIR like 'docs/demos.md' :return: """ path = os.path.join(settings.BASE_DIR, relative_path) content = markdown_from_file(path) return render(request, template_name, { 'content': content }) def render_markdown_template(request, title, heading, relative_path, leads=None): """ :param request: :param title: :param heading: :param leads: :param relative_path: markdown relative path from BASE_DIR like 'docs/demos.md' :return: """ if leads is None: leads = () path = os.path.join(settings.BASE_DIR, relative_path) content = markdown_from_file(path) return render(request, 'home/markdown.html', { 'title': title, 'heading': heading, 'leads': leads, 'content': content, }) def render_plain_text_file(request, title, heading, relative_path): """ :param request: :param title: :param heading: :param relative_path: file relative path from BASE_DIR like 'LICENSE' :return: """ path = os.path.join(settings.BASE_DIR, relative_path) content = read_file(path) return render_plain_text_content(request, title, heading, content)
[ 11748, 28686, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 628, 628, 198, 4299, 8543, 62, 20887, 62, 4102, 2902, 62, 28243, 7, 25927, 11, 11055, 62, 3672, 11, 3585, 62, 69...
2.647913
551
#!/usr/bin/env python # # Runs a Tornado web server with a django project # Make sure to edit the DJANGO_SETTINGS_MODULE to point to your settings.py # # http://localhost:8080/hello-tornado # http://localhost:8080 from __future__ import absolute_import, division, print_function, unicode_literals import sys import os import asyncio import tornado.httpserver import tornado.ioloop import tornado.web import tornado.wsgi from tornado.options import options, define, parse_command_line from tornado.platform.asyncio import AsyncIOMainLoop from django.core.wsgi import get_wsgi_application define('port', type=int, default=8001) if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 44743, 257, 48970, 3992, 4382, 351, 257, 42625, 14208, 1628, 198, 2, 6889, 1654, 284, 4370, 262, 13004, 1565, 11230, 62, 28480, 51, 20754, 62, 33365, 24212, 284, 966, 284, ...
3.220096
209
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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. """Utilities for `gcloud app firewall-rules`.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.calliope import exceptions from googlecloudsdk.core import resources import six # The default rule is placed at MaxInt32 - 1 and is always evaluated last DEFAULT_RULE_PRIORITY = 2**31 - 1 LIST_FORMAT = """ table( priority:sort=1, action, source_range, description ) """ registry = resources.REGISTRY def ParseFirewallRule(client, priority): """Creates a resource path given a firewall rule priority. Args: client: AppengineFirewallApiClient, the API client for this release track. priority: str, the priority of the rule. Returns: The resource for the rule. """ res = GetRegistry(client.ApiVersion()).Parse( six.text_type(ParsePriority(priority)), params={'appsId': client.project}, collection='appengine.apps.firewall.ingressRules') return res def ParsePriority(priority): """Converts a priority to an integer.""" if priority == 'default': priority = DEFAULT_RULE_PRIORITY try: priority_int = int(priority) if priority_int <= 0 or priority_int > DEFAULT_RULE_PRIORITY: raise exceptions.InvalidArgumentException( 'priority', 'Priority must be between 1 and {0} inclusive.'.format( DEFAULT_RULE_PRIORITY)) return priority_int except ValueError: raise exceptions.InvalidArgumentException( 'priority', 'Priority should be an integer value or `default`.') def ParseAction(messages, action): """Converts an action string to the corresponding enum value. Options are: 'allow' or 'deny', otherwise None will be returned. Args: messages: apitools.base.protorpclite.messages, the proto messages class for this API version for firewall. action: str, the action as a string Returns: ActionValueValuesEnum type """ if not action: return None return messages.FirewallRule.ActionValueValuesEnum(action.upper())
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 1303, 198, 2, 15069, 2177, 3012, 11419, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198,...
3.182681
843
import unittest import pprint import sys import os import json import datetime # The test object sys.path.append('../') from template import TemplateRex fspec_template = 't-detail_base.html' fspec_tsections = "./test_data/tsections_base.py" fspec_render = "./test_data/trender_base.html" fspec_data_flwr = "./test_data/data_flwr.json" # set as true to make new set to test data #tdata_make = False #if tdata_make: print("\nWarning test data be generated!\n\n") global display_flg, tdata_make_flg display_flg = 0 tdata_make_flg = 0 # ---------------------- # ---------------------- if __name__ == '__main__': if len(sys.argv) > 1: arg1 = sys.argv.pop() if arg1 == '-d': display_flg = 1 if arg1 == '-m': tdata_make_flg = 1 unittest.main()
[ 11748, 555, 715, 395, 198, 11748, 279, 4798, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 4818, 8079, 198, 198, 2, 383, 1332, 2134, 198, 17597, 13, 6978, 13, 33295, 10786, 40720, 11537, 198, 6738, 11055, 1330, 37...
2.383481
339
import abc import numpy as np from optuna.study import Study class BaseCrossover(object, metaclass=abc.ABCMeta): """Base class for crossovers. A crossover operation is used by :class:`~optuna.samplers.NSGAIISampler` to create new parameter combination from parameters of ``n`` parent individuals. .. note:: Concrete implementations of this class are expected to only accept parameters from numerical distributions. At the moment, only crossover operation for categorical parameters (uniform crossover) is built-in into :class:`~optuna.samplers.NSGAIISampler`. """ @property @abc.abstractmethod def n_parents(self) -> int: """Number of parent individuals required to perform crossover.""" raise NotImplementedError @abc.abstractmethod def crossover( self, parents_params: np.ndarray, rng: np.random.RandomState, study: Study, search_space_bounds: np.ndarray, ) -> np.ndarray: """Perform crossover of selected parent individuals. This method is called in :func:`~optuna.samplers.NSGAIISampler.sample_relative`. Args: parents_params: A ``numpy.ndarray`` with dimensions ``num_parents x num_parameters``. Represents a parameter space for each parent individual. This space is continuous for numerical parameters. rng: An instance of ``numpy.random.RandomState``. study: Target study object. search_space_bounds: A ``numpy.ndarray`` with dimensions ``len_search_space x 2`` representing numerical distribution bounds constructed from transformed search space. Returns: A 1-dimensional ``numpy.ndarray`` containing new parameter combination. """ raise NotImplementedError
[ 11748, 450, 66, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 2172, 9613, 13, 44517, 1330, 12481, 628, 198, 4871, 7308, 34, 23954, 7, 15252, 11, 1138, 330, 31172, 28, 39305, 13, 24694, 48526, 2599, 198, 220, 220, 220, 37227...
2.588156
743
import os import numpy as np from pandas import DataFrame, read_csv from os.path import dirname, join ROOT_DIR = dirname(dirname(os.path.realpath(__file__))) DATA_DIR = os.path.join(ROOT_DIR, 'data') STAN_DIR = os.path.join(ROOT_DIR, 'stan_results') #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# ### Load and prepare data. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# ## Load metadata and restrict participants. metadata = read_csv(os.path.join('data','metadata.csv')) metadata = metadata.loc[metadata['prev_complete']=="No",['platform','subject']].copy() ## Load task data and restrict participants. data = read_csv(os.path.join('data','data.csv')) data = data.loc[data.subject.isin(metadata.subject)] ## Initialize correlates DataFrame. corr = metadata[['platform','subject']].copy() #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# ### 1.1 Accuracy. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# print('1.1 Computing accuracy.') ## Compute accuracy. gb = data.groupby(['platform','subject']).accuracy.mean().reset_index() ## Merge with correlates. corr = corr.merge(gb) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# ### 1.2 Total Points. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# print('1.2 Computing points total.') ## Compute points. gb = data.groupby(['platform','subject']).outcome.sum().reset_index() gb = gb.rename(columns={'outcome':'points'}) ## Merge with correlates. corr = corr.merge(gb) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# ### 1.3 Win-Stay Rates. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# print('1.3 Computing win-stay rates.') ## Determine previous win trials. f = lambda x: np.roll(x, 1) data['prev_win'] = data.groupby(['platform','subject']).outcome.transform(f) data.loc[data.trial==1, 'prev_win'] = np.nan ## Determine stay trials. f = lambda x: (x == np.roll(x,1)).astype(int) data['stay'] = data.groupby(['platform','subject']).choice.transform(f) data.loc[data.trial==1, 'stay'] = np.nan ## Compute win-stay rate. gb = data.query('prev_win==1').groupby(['platform','subject']).stay.mean().reset_index() gb = gb.rename(columns={'stay':'ws'}) ## Merge with correlates. corr = corr.merge(gb) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# ### 1.4 Lose-Shift Rates. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# print('1.4 Computing lose-shift rates.') ## Compute lose-shift rate. gb = data.query('prev_win==0').groupby(['platform','subject']).stay.mean().reset_index() gb = gb.rename(columns={'stay':'ls'}) gb['ls'] = 1 - gb['ls'] ## Merge with correlates. corr = corr.merge(gb) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# ### 1.5 Perseveration Errors. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# print('1.5 Computing perseveration errors.') ## Define trial number within each block. data['exposure'] = data.groupby(['subject','block']).trial.transform(lambda x: np.arange(x.size)+1) ## Define perseveration errors. data['perseveration'] = data.groupby('subject').correct.transform(lambda x: np.roll(x, 15)) data['perseveration'] = (data['perseveration'] == data['choice']).astype(int) data.loc[data.block==1,'perseveration'] = np.nan ## Compute perseveration errors within participants. gb = data.groupby(['platform','subject']).perseveration.mean().reset_index() ## Merge with correlates. corr = corr.merge(gb) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# ### 1.6 Model-based correlates. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# print('1.6 Extracting Stan parameters.') ## Load StanFit. df = read_csv('stan_results/rstd.tsv.gz', sep='\t', compression='gzip') ## Extract parameters of interest. beta = df.filter(regex='beta').median().values eta_p = df.filter(regex='^eta_p').median().values eta_n = df.filter(regex='^eta_n').median().values kappa = (eta_p - eta_n) / (eta_p + eta_n) ## Convert to DataFrame. params = DataFrame(np.column_stack([beta,eta_p,eta_n,kappa]), columns=['beta','eta_p','eta_n','kappa']) ## Append metadata. params['platform'] = corr.sort_values('subject').platform.values params['subject'] = corr.sort_values('subject').subject.values ## Merge with correlates. corr = corr.merge(params) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# ### Save data. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# print('Saving data.') corr.to_csv(os.path.join(DATA_DIR, 'correlates.csv'), index=False)
[ 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 19798, 292, 1330, 6060, 19778, 11, 1100, 62, 40664, 198, 6738, 28686, 13, 6978, 1330, 26672, 3672, 11, 4654, 198, 13252, 2394, 62, 34720, 796, 26672, 3672, 7, 15908, 3672, 7, ...
3.096681
1,386
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.constant.ParamConstants import *
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 2829, 17752, 355, 33918, 198, 198, 6738, 435, 541, 323, 13, 64, 404, 13, 15042, 13, 9979, 415, 13, 22973, 3418...
2.58
50
import typing from graphql import GraphQLUnionType from strawberry.exceptions import UnallowedReturnTypeForUnion, WrongReturnTypeForUnion from strawberry.type import TypeDefinition from strawberry.union import UnionDefinition from strawberry.utils.typing import ( get_list_annotation, is_generic, is_list, is_type_var, ) from .types import TypeMap
[ 11748, 19720, 198, 198, 6738, 4823, 13976, 1330, 29681, 9711, 38176, 6030, 198, 6738, 41236, 13, 1069, 11755, 1330, 791, 40845, 13615, 6030, 1890, 38176, 11, 28843, 13615, 6030, 1890, 38176, 198, 6738, 41236, 13, 4906, 1330, 5994, 36621, ...
3.481132
106
#!/usr/bin/env python """ Copyright 2019 Pystol (pystol.org). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of 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. """ import kubernetes from kubernetes.client.rest import ApiException from pystol import __version__ from pystol.operator import load_kubernetes_config pystol_version = __version__ def purge_pystol(): """ Purge Pystol from the cluster. This is a main component of the input for the controller """ load_kubernetes_config() v1 = kubernetes.client.CoreV1Api() name = 'pystol' pretty = 'true' orphan_dependents = True # propagation_policy = 'Foreground' propagation_policy = 'Background' body = kubernetes.client.V1DeleteOptions() try: v1.delete_namespace(name, pretty=pretty, orphan_dependents=orphan_dependents, propagation_policy=propagation_policy, body=body) print(" " + u"\U0001F9F9" + " Namespace removed.") except ApiException: print(" " + u"\u2757" + " Namespace removing warning.") print(" Can't remove it, maybe it's gone...") name = 'pystol-config' namespace = 'pystol' pretty = 'true' orphan_dependents = True propagation_policy = 'Background' body = kubernetes.client.V1DeleteOptions() try: v1.delete_namespaced_config_map(name, namespace=namespace, pretty=pretty, orphan_dependents=orphan_dependents, propagation_policy=propagation_policy, body=body) print(" " + u"\U0001F9F9" + " Config map removed.") except ApiException: print(" " + u"\u2757" + " Config map removing warning.") print(" Can't remove it, maybe it's gone...") name = 'pystol' namespace = 'pystol' pretty = 'true' orphans = True propagation = 'Background' body = kubernetes.client.V1DeleteOptions() try: v1.delete_namespaced_service_account(name, namespace=namespace, pretty=pretty, orphan_dependents=orphans, propagation_policy=propagation, body=body) print(" " + u"\U0001F9F9" + " Service account removed.") except ApiException: print(" " + u"\u2757" + " Service account removing warning.") print(" Can't remove it, maybe it's gone...") rbac = kubernetes.client.RbacAuthorizationV1Api() name = 'pystol' pretty = 'true' orphan_dependents = True propagation_policy = 'Background' body = kubernetes.client.V1DeleteOptions() try: rbac.delete_cluster_role(name, pretty=pretty, orphan_dependents=orphan_dependents, propagation_policy=propagation_policy, body=body) print(" " + u"\U0001F9F9" + " Cluster role removed.") except ApiException: print(" " + u"\u2757" + " Cluster role removing warning.") print(" Can't remove it, maybe it's gone...") rbac = kubernetes.client.RbacAuthorizationV1Api() name = 'pystol' pretty = 'true' orphan_dependents = True propagation_policy = 'Background' body = kubernetes.client.V1DeleteOptions() try: rbac.delete_cluster_role_binding(name, pretty=pretty, orphan_dependents=orphan_dependents, propagation_policy=propagation_policy, body=body) print(" " + u"\U0001F9F9" + " Cluster role binding removed.") except ApiException: print(" " + u"\u2757" + " Cluster role binding removing warning.") print(" Can't remove it, maybe it's gone...") ext = kubernetes.client.ApiextensionsV1beta1Api() name = 'pystolactions.pystol.org' pretty = 'true' orphans = True propagation = 'Background' body = kubernetes.client.V1DeleteOptions() try: ext.delete_custom_resource_definition(name, pretty=pretty, orphan_dependents=orphans, propagation_policy=propagation, body=body) print(" " + u"\U0001F9F9" + " CRD removed.") except ApiException: print(" " + u"\u2757" + " CRD removing warning.") print(" Can't remove it, maybe it's gone...")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 198, 15269, 13130, 9485, 301, 349, 357, 9078, 301, 349, 13, 2398, 737, 198, 198, 26656, 15385, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341,...
2.015997
2,688
from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin from .models import Task from .mixins import UserTaskMixin
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 7343, 7680, 11, 42585, 7680, 11, 13610, 7680, 11, 10133, 7680, 11, 23520, 7680, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 62...
3.594937
79
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the Apple Spotlight store database parser.""" from __future__ import unicode_literals import unittest from plaso.lib import definitions from plaso.parsers import spotlight_storedb from tests.parsers import test_lib class SpotlightStoreDatabaseParserTest(test_lib.ParserTestCase): """Tests for the Apple Spotlight store database parser.""" def testParse(self): """Tests the Parse function.""" parser = spotlight_storedb.SpotlightStoreDatabaseParser() storage_writer = self._ParseFile(['store.db'], parser) self.assertEqual(storage_writer.number_of_warnings, 0) self.assertEqual(storage_writer.number_of_events, 1159238) events = list(storage_writer.GetEvents()) expected_event_values = { 'file_name': 'CIJCanoScan9000F.icns', 'file_system_identifier': 41322, 'kind': 'Apple icon image', 'parent_file_system_identifier': 41320, 'timestamp': '2013-06-04 20:53:10.000000', 'timestamp_desc': definitions.TIME_DESCRIPTION_MODIFICATION} self.CheckEventValues(storage_writer, events[12], expected_event_values) expected_message = 'CIJCanoScan9000F.icns com.apple.icns' expected_short_message = 'CIJCanoScan9000F.icns' event_data = self._GetEventDataOfEvent(storage_writer, events[12]) self._TestGetMessageStrings( event_data, expected_message, expected_short_message) if __name__ == '__main__': unittest.main()
[ 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, 51, 3558, 329, 262, 4196, 49014, 3650, 6831, 30751, 526, 15931, 198, 198, 6738, 11593, 37443, 834, 1330, 280...
2.740331
543
from pathlib import Path import chess.pgn import pandas as pd from datetime import date csv_datasets_folder = Path('../../data/interim') raw_data_folder = Path('../../data/raw') pgn_files = sorted(raw_data_folder.glob('*.pgn')) datasets = [] for path in pgn_files: print(f'parsing {path}') games = [] with open(path) as pgn_file: while pgn_file: try: headers = chess.pgn.read_headers(pgn_file) except UnicodeDecodeError: print( f'UnicodeDecodeError occurs while parsing {path} after the game {headers}. Going to the next game...') continue if headers is None: break games.append(pd.Series(headers)) df = pd.DataFrame(games) datasets.append(df) final_df = pd.concat(datasets) today_str = date.today().strftime('%d_%m_%Y') csv_file_name = csv_datasets_folder / f"{today_str}.csv" final_df.to_csv(csv_file_name) print(f'csv file {csv_file_name} was saved.')
[ 6738, 3108, 8019, 1330, 10644, 198, 11748, 19780, 13, 79, 4593, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 4818, 8079, 1330, 3128, 198, 198, 40664, 62, 19608, 292, 1039, 62, 43551, 796, 10644, 10786, 40720, 40720, 7890, 14, 3849, ...
2.145833
480
#!/usr/bin/python3 import time ''' ####### ''' date = 5 dev = 0 # extra prints part = 3 # 1,2, or 3 for both samp = 0 # 0 or 1 ''' ####### ''' ''' ####### ''' time0 = time.time() if samp == 1: filename = "/sample.txt" else: filename = "/input.txt" try: with open(str(date) + filename,"r") as f: t = f.readlines() except FileNotFoundError: with open("." + filename,"r") as f: t = f.readlines() t = [(x.strip().replace(' ',' ')) for x in t] if part == 1: print("Part 1: ", day(t)) elif part == 2: print("Part 2: ", day2(t)) elif part == 3: #run both print("Part 1: ", day(t)) print("Part 2: ", day2(t)) tdif = time.time() - time0 print("Elapsed time: {:.4f} s".format(tdif))
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 11748, 640, 198, 198, 7061, 6, 220, 220, 220, 220, 46424, 2235, 220, 220, 220, 220, 705, 7061, 198, 198, 4475, 796, 642, 198, 7959, 796, 657, 1303, 3131, 20842, 198, 3911, 796, 5...
2.168091
351
"""Tests for version.py.""" import os import sys import pytest try: # Python 2 from cStringIO import StringIO except: # Python 3 from io import StringIO import hera_pspec from .. import version import json
[ 37811, 51, 3558, 329, 2196, 13, 9078, 526, 15931, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 12972, 9288, 198, 198, 28311, 25, 198, 220, 220, 220, 1303, 11361, 362, 198, 220, 220, 220, 422, 269, 10100, 9399, 1330, 10903, 9399, ...
2.922078
77
# Copyright (c) 2016 Mirantis, 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 tempest.lib import decorators from murano_tempest_tests.tests.api.application_catalog import base from murano_tempest_tests import utils
[ 2, 220, 220, 220, 15069, 357, 66, 8, 1584, 7381, 20836, 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,...
3.324561
228
#!/usr/bin/env python3 ################################################################################ ## ___ _ ____ ____ ## / _ \ _ _ ___ ___| |_| _ \| __ ) ## | | | | | | |/ _ \/ __| __| | | | _ \ ## | |_| | |_| | __/\__ \ |_| |_| | |_) | ## \__\_\\__,_|\___||___/\__|____/|____/ ## ## Copyright (c) 2014-2019 Appsicle ## Copyright (c) 2019-2022 QuestDB ## ## 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. ## ################################################################################ import sys sys.dont_write_bytecode = True import datetime import argparse import unittest import questdb_line_sender as qls import uuid from fixture import ( Project, QuestDbFixture, install_questdb, list_questdb_releases, retry) import urllib.request import urllib.parse import json import subprocess from collections import namedtuple QDB_FIXTURE: QuestDbFixture = None if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 29113, 29113, 14468, 198, 2235, 220, 220, 220, 220, 46444, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 4808, 220, 220, 220, 1427, ...
3.016129
496
from __future__ import print_function, division import codecs from emoji import UNICODE_EMOJI
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 11, 7297, 198, 11748, 40481, 82, 198, 6738, 44805, 1330, 4725, 2149, 16820, 62, 3620, 46, 41, 40, 198 ]
3.481481
27
""" This python script builds the XML files for case5a of the FHR benchmark materials.xml, geometry.xml, settings.xml, and tallies.xml """ ############################################################################### # Python Package Import ############################################################################### import openmc import numpy as np from numpy import sin, cos, tan, pi import sys sys.path.insert(1, '../../scripts/') from phase1a_constants import * from tallies import * ############################################################################### # Simulation Input File Parameters ############################################################################### # OpenMC simulation parameters batches = 500 inactive = 100 particles = 2000000 tallies_on = True ############################################################################### # Exporting to OpenMC materials.xml file ############################################################################### uoc_9 = openmc.Material() uoc_9.set_density('g/cc', 11) uoc_9.add_nuclide('U235', 2.27325e-3) uoc_9.add_nuclide('U238', 2.269476e-2) uoc_9.add_nuclide('O16', 3.561871e-2) uoc_9.add_nuclide('C0', 9.79714e-3) uoc_9.temperature = 1110 uoc_9.volume = 4 / 3 * pi * (T_r1 ** 3) * 101 * 210 * 4 * 36 por_c = openmc.Material() por_c.set_density('g/cc', 1) por_c.add_nuclide('C0', 5.013980e-2) por_c.temperature = 948 si_c = openmc.Material() si_c.set_density('g/cc', 3.2) si_c.add_nuclide('Si28', 4.431240e-2) si_c.add_nuclide('Si29', 2.25887e-3) si_c.add_nuclide('Si30', 1.48990e-3) si_c.add_nuclide('C0', 4.806117e-2) si_c.temperature = 948 graphite = openmc.Material() graphite.set_density('g/cc', 1.8) graphite.add_nuclide('C0', 9.025164e-2) graphite.temperature = 948 p_graphite = openmc.Material() p_graphite.set_density('g/cc', 1.8) p_graphite.add_nuclide('C0', 9.025164e-2) p_graphite.add_nuclide('Eu151', 1.533453e-6) p_graphite.add_nuclide('Eu153', 1.674607e-6) p_graphite.add_nuclide('O16', 4.812090e-6) p_graphite.temperature = 948 s_graphite = openmc.Material() s_graphite.set_density('g/cc', 1.8) s_graphite.add_nuclide('C0', 9.025164e-2) s_graphite.temperature = 948 lm_graphite = openmc.Material() lm_graphite.set_density('g/cc', 1.8) lm_graphite.add_nuclide('C0', 9.025164e-2) lm_graphite.temperature = 948 flibe = openmc.Material() flibe.set_density('g/cc', 1.95) flibe.add_nuclide('Li6', 1.383014e-6) flibe.add_nuclide('Li7', 2.37132e-2) flibe.add_nuclide('Be9', 1.18573e-2) flibe.add_nuclide('F19', 4.74291e-2) flibe.temperature = 948 mhc = openmc.Material() mhc.set_density('g/cc', 10.28) mhc.add_nuclide('Mo92', 9.328884e-3) mhc.add_nuclide('Mo94', 5.850533e-3) mhc.add_nuclide('Mo95', 1.010836e-2) mhc.add_nuclide('Mo96', 1.061782e-2) mhc.add_nuclide('Mo97', 6.102080e-3) mhc.add_nuclide('Mo98', 1.546981e-2) mhc.add_nuclide('Mo100', 6.205246e-3) mhc.add_nuclide('Hf174', 6.659530e-7) mhc.add_nuclide('Hf176', 2.189321e-5) mhc.add_nuclide('Hf177', 7.741704e-5) mhc.add_nuclide('Hf178', 1.135450e-4) mhc.add_nuclide('Hf179', 5.668925e-5) mhc.add_nuclide('Hf180', 1.460102e-4) mhc.add_nuclide('C0', 5.154371e-4) mhc.temperature = 948 mats = openmc.Materials( (uoc_9, por_c, si_c, graphite, p_graphite, lm_graphite, flibe, mhc, s_graphite)) mats.export_to_xml() ############################################################################### # Exporting to OpenMC geometry.xml file ############################################################################### # top and bottom surfaces (dz) top_surface = openmc.ZPlane( z0=T_pitch / 2 + (z_thickness - 1) / 2 * T_pitch, boundary_type='reflective') bot_surface = openmc.ZPlane( z0=-(T_pitch / 2 + (z_thickness - 1) / 2 * T_pitch), boundary_type='reflective') # Outermost Hexagon H_m = 1 / tan(pi / 6) H_1 = openmc.YPlane(0.5 * H_side / tan(pi / 6), 'periodic') H_2 = plane(-H_m, 0.5 * H_side, 0.5 * H_side / tan(pi / 6), 'periodic') H_3 = plane(H_m, 0.5 * H_side, -0.5 * H_side / tan(pi / 6), 'periodic') H_4 = openmc.YPlane(-0.5 * H_side / tan(pi / 6), 'periodic') H_5 = plane(-H_m, -0.5 * H_side, -0.5 * H_side / tan(pi / 6), 'periodic') H_6 = plane(H_m, -0.5 * H_side, 0.5 * H_side / tan(pi / 6), 'periodic') H_1.periodic_surface = H_4 H_2.periodic_surface = H_5 H_3.periodic_surface = H_6 H_region = -H_1 & +H_4 & -H_2 & +H_3 & +H_5 & -H_6 H_cell = openmc.Cell(fill=graphite) H_cell.region = H_region & -top_surface & + bot_surface # Diamond Plank Area A1_D_cell = openmc.Cell(fill=flibe) A1_D_cell.region = region_maker('A1', 'D') & -top_surface & + bot_surface A2_D_cell = openmc.Cell(fill=flibe) A2_D_cell.region = region_maker('A2', 'D') & -top_surface & + bot_surface A3_D_cell = openmc.Cell(fill=flibe) A3_D_cell.region = region_maker('A3', 'D') & -top_surface & + bot_surface D_regions = A1_D_cell.region | A2_D_cell.region | A3_D_cell.region D_universe = openmc.Universe(cells=(A1_D_cell, A2_D_cell, A3_D_cell,)) D_areas = openmc.Cell(fill=D_universe, region=D_regions) H_cell.region &= ~D_regions # Graphite Planks all_P_univ = openmc.Universe() all_P_regions = region_maker('A1', 'P') # initialize for area in range(3): area_str = 'A{}'.format(area + 1) P_region = region_maker(area_str, 'P') P_cell = openmc.Cell(fill=p_graphite, region=P_region) P_univ = openmc.Universe(cells=(P_cell,)) for trans in range(6): P_region_new = P_region.translate( (trans * T[area_str]['P']['x'], trans * T[area_str]['P']['y'], 0)) P_cell_new = openmc.Cell(fill=P_univ, region=P_region_new) P_cell_new.translation = ( trans * T[area_str]['P']['x'], trans * T[area_str]['P']['y'], 0) all_P_univ.add_cell(P_cell_new) all_P_regions |= P_region_new D_areas.region &= ~P_region_new H_cell.region &= ~P_region_new P_areas = openmc.Cell( fill=all_P_univ, region=all_P_regions & - top_surface & + bot_surface) # Triso Particles spheres = [openmc.Sphere(r=r) for r in [T_r1, T_r2, T_r3, T_r4, T_r5]] triso_cells = [openmc.Cell(fill=uoc_9, region=-spheres[0]), openmc.Cell(fill=por_c, region=+spheres[0] & -spheres[1]), openmc.Cell(fill=graphite, region=+spheres[1] & -spheres[2]), openmc.Cell(fill=si_c, region=+spheres[2] & -spheres[3]), openmc.Cell(fill=graphite, region=+spheres[3] & -spheres[4]), openmc.Cell(fill=lm_graphite, region=+spheres[4])] triso_univ = openmc.Universe(cells=triso_cells) lm_graphite_cell = openmc.Cell(fill=lm_graphite) lm_graphite_univ = openmc.Universe(cells=(lm_graphite_cell,)) u = triso_univ lattice = openmc.RectLattice() lattice.lower_left = (V['A1']['F']['L']['x'], V['A1']['F']['B'] ['y'], -(T_pitch / 2 + (z_thickness - 1) / 2 * T_pitch)) lattice.pitch = (T_pitch, T_pitch, T_pitch) lattice.outer = lm_graphite_univ lattice_list = [] for z in range(z_thickness): lattice_z_list = [] for row in range(4): lattice_y_list = [] for col in range(210): lattice_y_list.append(u) lattice_z_list.append(lattice_y_list) lattice_list.append(lattice_z_list) lattice.universes = lattice_list # Fuel Plank all_F_univ = openmc.Universe() all_F_regions = region_maker('A1', 'F') # initialize for area in range(3): area_str = 'A{}'.format(area + 1) F_region = region_maker(area_str, 'F') F_cell = openmc.Cell(fill=lm_graphite,) F_cell.fill = lattice F_univ = openmc.Universe(cells=(F_cell,)) for t in range(6): for x in range(2): x_trans = t * T[area_str]['P']['x'] y_trans = t * T[area_str]['P']['y'] if x == 1: x_trans += T[area_str]['F']['x'] y_trans += T[area_str]['F']['y'] F_region_new = F_region.translate((x_trans, y_trans, 0)) F_cell_new = openmc.Cell(fill=F_univ, region=F_region_new) if area == 1: F_cell_new.rotation = (0, 0, -120) if area == 2: F_cell_new.rotation = (0, 0, 120) F_cell_new.translation = (x_trans, y_trans, 0) all_F_univ.add_cell(F_cell_new) all_F_regions |= F_region_new P_areas.region &= ~F_region_new D_areas.region &= ~F_region_new H_cell.region &= ~F_region_new F_areas = openmc.Cell( fill=all_F_univ, region=all_F_regions & - top_surface & + bot_surface) # Spacer all_S_univ = openmc.Universe() S_small_spacer_surf = openmc.ZCylinder( r=S_small_r, x0=-D_to_center_width - S_A1_D_gap, y0=-D_to_center - P_small_gap) # initialize all_S_regions = -S_small_spacer_surf & + \ plane(V['A1']['P']['T']['m'], V['A1']['P']['T']['x'], V['A1']['P']['T']['y']) # outer loop is for 3 types of spacers, small top, big middle, small bottom rad = [S_small_r, S_large_r, S_small_r] start = [0, 1, 5] end = [1, 6, 6] C = ['C', 'C', 'Cb'] for y in range(3): for area in range(3): area_str = 'A{}'.format(area + 1) S_cylinder = openmc.ZCylinder(r=rad[y], x0=V[area_str]['S'][C[y]]['x0'], y0=V[area_str]['S'][C[y]]['y0']) if area == 0: S_region = -S_cylinder & + \ plane(V[area_str]['P']['T']['m'], V[area_str]['P']['T']['x'], V[area_str]['P']['T']['y']) if y == 2: S_region = -S_cylinder & - \ plane(V[area_str]['P']['B']['m'], V[area_str]['P']['B']['x'], V[area_str]['P']['B']['y']) if area == 1: S_region = -S_cylinder & - \ plane(V[area_str]['P']['R']['m'], V[area_str]['P']['R']['x'], V[area_str]['P']['R']['y']) if y == 2: S_region = -S_cylinder & + \ plane(V[area_str]['P']['L']['m'], V[area_str]['P']['L']['x'], V[area_str]['P']['L']['y']) if area == 2: S_region = -S_cylinder & - \ plane(V[area_str]['P']['L']['m'], V[area_str]['P']['L']['x'], V[area_str]['P']['L']['y']) if y == 2: S_region = -S_cylinder & + \ plane(V[area_str]['P']['R']['m'], V[area_str]['P']['R']['x'], V[area_str]['P']['R']['y']) S_cell = openmc.Cell(fill=s_graphite, region=S_region) S_univ = openmc.Universe(cells=(S_cell,)) for trans in range(start[y], end[y]): for x in range(2): x_trans = trans * T[area_str]['P']['x'] y_trans = trans * T[area_str]['P']['y'] if x == 1: x_trans += T[area_str]['S']['x'] y_trans += T[area_str]['S']['y'] S_region_new = S_region.translate((x_trans, y_trans, 0)) S_cell_new = openmc.Cell(fill=S_univ, region=S_region_new) S_cell_new.translation = (x_trans, y_trans, 0) all_S_univ.add_cell(S_cell_new) all_S_regions |= S_region_new F_areas.region &= ~S_region_new P_areas.region &= ~S_region_new D_areas.region &= ~S_region_new H_cell.region &= ~S_region_new S_areas = openmc.Cell( fill=all_S_univ, region=all_S_regions & - top_surface & + bot_surface) # Control Rod Slot A1_CS_cell = openmc.Cell(fill=flibe) A1_CS_cell.region = region_maker('A1', 'CS') & -top_surface & + bot_surface A2_CS_cell = openmc.Cell(fill=flibe) A2_CS_cell.region = region_maker('A2', 'CS') & -top_surface & + bot_surface A3_CS_cell = openmc.Cell(fill=flibe) A3_CS_cell.region = region_maker('A3', 'CS') & -top_surface & + bot_surface CS_regions = A1_CS_cell.region | A2_CS_cell.region | A3_CS_cell.region CS_universe = openmc.Universe(cells=(A1_CS_cell, A2_CS_cell, A3_CS_cell,)) CS_areas = openmc.Cell(fill=CS_universe, region=CS_regions) S_areas.region &= ~CS_regions F_areas.region &= ~CS_regions P_areas.region &= ~CS_regions D_areas.region &= ~CS_regions H_cell.region &= ~CS_regions # Control Rod Arm A1_CA_cell = openmc.Cell(fill=flibe) A1_CA_cell.region = region_maker('A1', 'CA') & -top_surface & + bot_surface A2_CA_cell = openmc.Cell(fill=flibe) A2_CA_cell.region = region_maker('A2', 'CA') & -top_surface & + bot_surface A3_CA_cell = openmc.Cell(fill=flibe) A3_CA_cell.region = region_maker('A3', 'CA') & -top_surface & + bot_surface CA_regions = A1_CA_cell.region | A2_CA_cell.region | A3_CA_cell.region CA_universe = openmc.Universe(cells=(A1_CA_cell, A2_CA_cell, A3_CA_cell,)) CA_areas = openmc.Cell(fill=CA_universe, region=CA_regions) CS_areas.region &= ~CA_regions S_areas.region &= ~CA_regions F_areas.region &= ~CA_regions P_areas.region &= ~CA_regions D_areas.region &= ~CA_regions H_cell.region &= ~CA_regions # export to xml root = openmc.Universe( cells=[ H_cell, D_areas, P_areas, F_areas, S_areas, CS_areas, CA_areas]) geom = openmc.Geometry(root) geom.export_to_xml() ############################################################################### # Exporting to OpenMC settings.xml file ############################################################################## settings = openmc.Settings() settings.batches = batches settings.inactive = inactive settings.particles = particles settings.temperature = {'multipole': True, 'method': 'interpolation'} settings.export_to_xml() ############################################################################### # Exporting to OpenMC tallies.xml file ############################################################################### if tallies_on: tallies_generation(root) else: print('tallies off')
[ 37811, 198, 1212, 21015, 4226, 12188, 262, 23735, 3696, 329, 1339, 20, 64, 286, 262, 376, 17184, 18335, 198, 33665, 82, 13, 19875, 11, 22939, 13, 19875, 11, 6460, 13, 19875, 11, 290, 7331, 444, 13, 19875, 198, 198, 37811, 198, 198, ...
2.027221
6,833
from .general import TrussBar from .construction import TrussConstruction __all__ = ['TrussBar', 'TrussConstruction']
[ 6738, 764, 24622, 1330, 833, 1046, 10374, 198, 6738, 764, 9979, 2762, 1330, 833, 1046, 36687, 198, 198, 834, 439, 834, 796, 37250, 2898, 1046, 10374, 3256, 705, 2898, 1046, 36687, 20520, 198 ]
3.606061
33
import os import configparser import getpass from jinja2 import Environment, FileSystemLoader import socket import sys deploy_dir = os.path.dirname(os.path.abspath(__file__)) module_root = os.path.dirname(deploy_dir) properties_path = module_root + "/application.prod.cfg" config = configparser.ConfigParser() TEMPLATE_ENVIRONMENT = Environment( autoescape=False, loader=FileSystemLoader(os.path.join(deploy_dir, 'templates')), trim_blocks=False) if os.path.isfile(properties_path): with open(properties_path, 'r') as propertiesfile: config_string = '[default_section]\n' + propertiesfile.read() config.read_string(config_string) if sys.argv[1] == 'syncmanagerapi.service': systemd_service_file = sys.argv[1] install_dir = config['default_section'].get('INSTALL_DIR', '/opt/syncmanagerapi').strip('"\'') fs_root_dir = config['default_section'].get('FS_ROOT', '/var/syncmanager').strip('"\'') context = { 'unix_user': config['default_section'].get('UNIX_USER', 'syncman').strip('"\''), 'unix_group': config['default_section'].get('UNIX_USER', 'syncman').strip('"\''), 'install_dir': install_dir, 'server_port': config['default_section'].get('SERVER_PORT', '5010'), 'hostname': config['default_section'].get('HOSTNAME', socket.gethostname()).strip('"\'') } conf_file = TEMPLATE_ENVIRONMENT.get_template('{}.j2'.format(systemd_service_file)).render(context) f = open(os.path.join(deploy_dir, systemd_service_file), 'w') f.write(conf_file) f.close() # generate database init script if sys.argv[1] == 'init_db.sql': init_db_file = sys.argv[1] db_user_name = config['default_section'].get('DB_USER', 'syncmanager').strip('"\'') # password must be provided, in future this should be replaced by a retrieval from a password vault passw = getpass.getpass("Provide password for Mysql user {}:".format(db_user_name)) context = { 'db_schema_name': config['default_section'].get('DB_SCHEMA_NAME', 'syncmanerapi').strip('"\''), 'db_user': db_user_name, 'db_user_password': passw } conf_file = TEMPLATE_ENVIRONMENT.get_template('{}.j2'.format(init_db_file)).render(context) f = open(os.path.join(deploy_dir, init_db_file), 'w') f.write(conf_file) f.close() print(f"DB_PASSWORD=\"{passw}\"")
[ 11748, 28686, 198, 11748, 4566, 48610, 198, 11748, 651, 6603, 198, 6738, 474, 259, 6592, 17, 1330, 9344, 11, 9220, 11964, 17401, 198, 11748, 17802, 198, 11748, 25064, 198, 198, 2934, 1420, 62, 15908, 796, 28686, 13, 6978, 13, 15908, 367...
2.213254
1,177
__all__ = ["HashableDict"]
[ 834, 439, 834, 796, 14631, 26257, 540, 35, 713, 8973, 628 ]
2.545455
11
import math import warnings def is_pythagorean_triplet(a,b,c): """ Checks if a,b and c forms pythagorean triplet i.e., a^2 + b^2 = c^2 Parameters ---------- a : int denotes positive integer a in a^2 + b^2 = c^2 b : int denotes positive integer b in a^2 + b^2 = c^2 c : int denotes positive integer c in a^2 + b^2 = c^2 return : bool returns true if a, b and c forms pythagorean triplet otherwise false """ if(a<1 or a!=int(a) or b<1 or b!=int(b) or c<1 or c!=int(c)): raise ValueError( "a,b and c are positive integers" ) count = 0 if(a%2 == 0): count += 1 if(b%2 == 0): count += 1 if(count!=1): return False if(c%2 == 0): return False return (a**2) + (b**2) == (c**2) def generate_pythagorean_triplet(m , n): """ Generates pythagorean triplets from the given two integers Parameters ---------- m : int denotes positive integer n : int denotes positive integer return : 3 int returns three positive integers """ if(m<1 or m!=int(m) or n<1 or n!=int(n)): raise ValueError( "m and n must be positive integers" ) if(m<=n): raise ValueError( "m must be greater than n" ) a = 2*m*n b = (m**2) - (n**2) c = (m**2) + (n**2) return a,b,c
[ 11748, 10688, 198, 11748, 14601, 198, 198, 4299, 318, 62, 79, 5272, 363, 29456, 62, 28461, 37069, 7, 64, 11, 65, 11, 66, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 47719, 611, 257, 11, 65, 290, 269, 5107, 279, 5272, 363,...
2.035411
706
#!/usr/bin/python3 ''' Summary ------- This application simulates the cumulative PSF and compare with data (if available). The telescope zenith angle and the source distance can be set by command line arguments. The measured cumulative PSF should be provided by using the command line argument data. \ A file name is expected, in which the file should contains 3 columns: radial distance in mm, \ differential value of photon intensisity and its integral value. The MC model can be changed by providing a yaml file with the new parameter values using \ the argument pars (see example below). Examples of the plots generated by this applications are shown below. On the left, \ the cumulative PSF and on the right, the simulated PSF image. .. _compare_cumulative_psf_plot: .. image:: images/compare_cumulative_psf_North-LST-1_cumulativePSF.png :width: 49 % .. image:: images/compare_cumulative_psf_North-LST-1_image.png :width: 49 % Command line arguments ---------------------- site (str, required) North or South. telescope (str, required) Telescope model name (e.g. LST-1, SST-D, ...). model_version (str, optional) Model version (default=prod4). src_distance (float, optional) Source distance in km (default=10). zenith (float, optional) Zenith angle in deg (default=20). data (str, optional) Name of the data file with the measured cumulative PSF. pars (str, optional) Yaml file with the new model parameters to replace the default ones. test (activation mode, optional) If activated, application will be faster by simulating fewer photons. verbosity (str, optional) Log level to print (default=INFO). Example ------- LST-1 Prod5 Runtime < 1 min. First, create an yml file named lst_pars.yml with the following content: .. code-block:: yaml mirror_reflection_random_angle: '0.0075,0.15,0.035' mirror_align_random_horizontal: '0.0040,28.,0.0,0.0' mirror_align_random_vertical: '0.0040,28.,0.0,0.0' And the run: .. code-block:: console python applications/compare_cumulative_psf.py --site North --telescope LST-1 --model_version prod4 --pars lst_pars.yml --data PSFcurve_data_v2.txt .. todo:: * Change default model to default (after this feature is implemented in db_handler) ''' import logging import matplotlib.pyplot as plt import argparse import yaml from collections import OrderedDict import numpy as np import astropy.units as u import simtools.io_handler as io import simtools.util.general as gen import simtools.config as cfg from simtools.ray_tracing import RayTracing from simtools.model.telescope_model import TelescopeModel from simtools import visualize if __name__ == '__main__': parser = argparse.ArgumentParser( description=( 'Calculate and plot the PSF and eff. mirror area as a function of off-axis angle ' 'of the telescope requested.' ) ) parser.add_argument( '-s', '--site', help='North or South', type=str, required=True ) parser.add_argument( '-t', '--telescope', help='Telescope model name (e.g. MST-FlashCam-D, LST-1)', type=str, required=True ) parser.add_argument( '-m', '--model_version', help='Model version (default=prod4)', type=str, default='prod4' ) parser.add_argument( '--src_distance', help='Source distance in km (default=10)', type=float, default=10 ) parser.add_argument( '--zenith', help='Zenith angle in deg (default=20)', type=float, default=20 ) parser.add_argument( '--data', help='Data file name with the measured PSF vs radius [cm]', type=str ) parser.add_argument( '--pars', help='Yaml file with the model parameters to be replaced', type=str ) parser.add_argument( '--test', help='Test option will be faster by simulating fewer photons.', action='store_true' ) parser.add_argument( '-v', '--verbosity', dest='logLevel', action='store', default='info', help='Log level to print (default is INFO)' ) args = parser.parse_args() label = 'compare_cumulative_psf' logger = logging.getLogger() logger.setLevel(gen.getLogLevelFromUser(args.logLevel)) # Output directory to save files related directly to this app outputDir = io.getApplicationOutputDirectory(cfg.get('outputLocation'), label) telModel = TelescopeModel( site=args.site, telescopeModelName=args.telescope, modelVersion=args.model_version, label=label ) # New parameters if args.pars is not None: with open(args.pars) as file: newPars = yaml.load(file, Loader=yaml.FullLoader) telModel.changeParameters(**newPars) ray = RayTracing.fromKwargs( telescopeModel=telModel, sourceDistance=args.src_distance * u.km, zenithAngle=args.zenith * u.deg, offAxisAngle=[0. * u.deg] ) ray.simulate(test=args.test, force=False) ray.analyze(force=False) # Plotting cumulative PSF im = ray.images()[0] print('d80 in cm = {}'.format(im.getPSF())) # Plotting cumulative PSF dataToPlot = OrderedDict() dataToPlot[r'sim$\_$telarray'] = im.getCumulativeData() if args.data is not None: dataFile = cfg.findFile(args.data) dataToPlot['measured'] = loadData(dataFile) plt = visualize.plot1D(dataToPlot) plt.gca().set_ylim(0, 1.05) plotFileName = label + '_' + telModel.name + '_cumulativePSF' plotFile = outputDir.joinpath(plotFileName) for f in ['pdf', 'png']: plt.savefig(str(plotFile) + '.' + f, format=f, bbox_inches='tight') plt.clf() # Plotting image dataToPlot = im.getImageData() visualize.plotHist2D(dataToPlot, bins=80) circle = plt.Circle((0, 0), im.getPSF(0.8) / 2, color='k', fill=False, lw=2, ls='--') plt.gca().add_artist(circle) plotFileName = label + '_' + telModel.name + '_image' plotFile = outputDir.joinpath(plotFileName) for f in ['pdf', 'png']: plt.savefig(str(plotFile) + '.' + f, format=f, bbox_inches='tight') plt.clf()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 7061, 6, 198, 220, 220, 220, 21293, 198, 220, 220, 220, 35656, 198, 220, 220, 220, 770, 3586, 985, 15968, 262, 23818, 6599, 37, 290, 8996, 351, 1366, 357, 361, 1695, 737, 628, 22...
2.456841
2,653
import os import platform import subprocess import sys import click from pycparser import ( c_parser, ) from .declarations import ( BUILTIN_HEADERS_DIR, DARWIN_HEADERS_DIR, IGNORE_DECLARATIONS, ) from .writer import ( AutoPxd, ) __version__ = "2.0.4" def ensure_binary(s, encoding="utf-8", errors="strict"): """Coerce **s** to bytes. - `str` -> encoded to `bytes` - `bytes` -> `bytes` """ if isinstance(s, str): return s.encode(encoding, errors) if isinstance(s, bytes): return s raise TypeError("not expecting type '%s'" % type(s)) def translate(code, hdrname, extra_cpp_args=None, whitelist=None, debug=False): """ to generate pxd mappings for only certain files, populate the whitelist parameter with the filenames (including relative path): whitelist = ['/usr/include/baz.h', 'include/tux.h'] if the input file is a file that we want in the whitelist, i.e. `whitelist = [hdrname]`, the following extra step is required: extra_cpp_args += [hdrname] """ if extra_cpp_args is None: extra_cpp_args = [] extra_incdir = os.path.dirname(hdrname) if extra_incdir: extra_cpp_args += ["-I%s" % extra_incdir] p = AutoPxd(hdrname) p.visit(parse(code, extra_cpp_args=extra_cpp_args, whitelist=whitelist, debug=debug)) pxd_string = "" if p.stdint_declarations: pxd_string += "from libc.stdint cimport {:s}\n\n".format(", ".join(p.stdint_declarations)) pxd_string += str(p) return pxd_string WHITELIST = [] CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"]) @click.command( context_settings=CONTEXT_SETTINGS, help="Generate a Cython pxd file from a C header file.", ) @click.option("--version", "-v", is_flag=True, help="Print program version and exit.") @click.option( "--include-dir", "-I", multiple=True, metavar="<dir>", help="Allow the C preprocessor to search for files in <dir>.", ) @click.option( "--compiler-directive", "-D", multiple=True, help="Additional directives for the C compiler.", metavar="<directive>", ) @click.option( "--debug/--no-debug", default=False, help="Dump preprocessor output to stderr.", ) @click.argument( "infile", type=click.File("r"), default=sys.stdin, ) @click.argument( "outfile", type=click.File("w"), default=sys.stdout, )
[ 11748, 28686, 198, 11748, 3859, 198, 11748, 850, 14681, 198, 11748, 25064, 198, 198, 11748, 3904, 198, 6738, 12972, 13155, 28198, 1330, 357, 198, 220, 220, 220, 269, 62, 48610, 11, 198, 8, 198, 198, 6738, 764, 32446, 24355, 1330, 357, ...
2.458333
984
"""Tools for getting spectra for lya fitting. Includes choosing a data file for each star, reading the files, and processing the spectral data (from either IUE, STIS, ...) into a format that can be used directly for the fitting. The variable target_use_which_spectrum indicates which data to use for each star. It can be customized by editing this file. Running this module directly will print out the default value for this dictionary. """ from astropy.table import Table from astropy.io import fits import numpy as np from pathlib import Path from warnings import warn from scipy.interpolate import interp1d import collections # \(swp[0-9]\{5\}\) # can be manually tweaked. If the value is a list or contains *, the # spectra will be coadded target_use_which_spectrum = { "HD097471": "data/HD097471/mastDownload/IUE/swp19375/swp19375mxlo_vo.fits", "HD037525": "data/HD037525/mastDownload/IUE/swp27579/swp27579.mxhi.gz", "HD093827": "data/HD093827/mastDownload/IUE/swp50536/swp50536.mxhi.gz", # "HD093827": "data/HD093827/*mxlo_vo.fits", "HD051013": "data/HD051013/mastDownload/IUE/swp22860/swp22860.mxhi.gz", "HD096675": "data/HD096675/mastDownload/IUE/swp41717/swp41717.mxhi.gz", "HD023060": "data/HD023060/mastDownload/IUE/swp11151/swp11151mxlo_vo.fits", "HD099872": "data/HD099872/mastDownload/HST/**/*_x1d.fits", # "HD152248": "data/HD152248/mastDownload/IUE/swp54576/swp54576.mxhi.gz", "HD152248": "data/HD152248/**/*.mxhi.gz", "HD209339": "data/HD209339/mastDownload/HST/**/*_x1d.fits", # "HD197770": "data/HD197770/mastDownload/HST/oedl04010/oedl04010_x1d.fits", "HD197770": "data/HD197770/**/*.mxhi.gz", "HD037332": "data/HD037332/mastDownload/IUE/swp32289/swp32289.mxhi.gz", "HD093028": "data/HD093028/mastDownload/IUE/swp05521/swp05521.mxhi.gz", # "HD062542": "data/HD062542/mastDownload/HST/obik01020/obik01020_x1d.fits", # wavelength range # "HD062542": "data/HD062542/*.mxhi.gz", # way too noisy "HD062542": "data/HD062542/**/*mxlo_vo.fits", # "HD190603": "data/HD190603/*.mxhi.gz", "HD190603": "data/HD190603/**/*mxlo_vo.fits", # "HD046202": "data/HD046202/mastDownload/IUE/swp08845/swp08845.mxhi.gz", # "HD046202": "data/HD046202/mastDownload/HST/ocb6e0030/ocb6e0030_x1d.fits", # "HD046202": "data/HD046202/mastDownload/HST/ocb6e1030/ocb6e1030_x1d.fits", "HD046202": "data/HD046202/mastDownload/HST/**/*_x1d.fits", # "HD047129": "data/HD047129/mastDownload/IUE/swp07077/swp07077.mxhi.gz", "HD047129": "data/HD047129/**/*.mxhi.gz", "HD235874": "data/HD235874/mastDownload/IUE/swp34158/swp34158mxlo_vo.fits", "HD216898": "data/HD216898/swp43934.mxhi.gz", # "HD216898": "data/HD216898/mastDownload/IUE/swp17175/swp17175mxlo_vo.fits", "HD326329": "data/HD326329/mastDownload/IUE/swp48698/swp48698.mxhi.gz", "HD179406": [ "data/HD179406/mastDownload/IUE/swp08974/swp08974.mxhi.gz", "data/HD179406/mastDownload/IUE/swp08976/swp08976.mxhi.gz", "data/HD179406/mastDownload/IUE/swp13865/swp13865.mxhi.gz", "data/HD179406/mastDownload/IUE/swp36939/swp36939.mxhi.gz", "data/HD179406/mastDownload/IUE/swp36940/swp36940.mxhi.gz", ], "BD+52d3210": "data/BD+52d3210/mastDownload/IUE/swp34153/swp34153mxlo_vo.fits", "BD+56d524": "data/BD+56d524/mastDownload/IUE/swp20330/swp20330mxlo_vo.fits", # data for comparison to existing HI results "HD094493": "data/HD094493/mastDownload/HST/o54306010/o54306010_x1d.fits", "HD045314": "data/HD045314/mastDownload/IUE/**/*mxhi.gz" } # namedtuple defines a simple class Spectrum = collections.namedtuple( "Spectrum", ["wavs", "flux", "errs", "net", "exptime"] ) def processed(target, wmin=0, wmax=1400, disp=0.25): """Get spectrum data ready for fitting Lya for the given target. Tweak the variable get_spectrum.target_use_which_spectrum to choose the right data. Depending on whether a IUE or STIS spectrum was chosen, different steps will be taken. The end result is the spectral data in a common format, processed with different steps depending on the source of the data. Returns ------- wav, flux: ndarray of wavelengths (angstrom) and fluxes (erg s-1 cm-2 angstrom-1) """ # choose data filename = target_use_which_spectrum[target] print("Getting data from ", filename) spectrum, rebin = auto_wavs_flux_errs(filename) if rebin: binnedwavs, binnedflux = rebin_spectrum_around_lya(spectrum, wmin, wmax, disp) else: wavs, flux = spectrum.wavs, spectrum.flux use = np.logical_and(wmin < wavs, wavs < wmax) binnedwavs, binnedflux = wavs[use], flux[use] # remove nans (these are very annoying when they propagate, e.g. # max([array with nan]) = nan). safe = np.isfinite(binnedflux) safewavs = binnedwavs[safe] safeflux = binnedflux[safe] return safewavs, safeflux, filename def auto_wavs_flux_errs(filename): """Load spectrum or multiple spectra based on file name.""" # determine if multiple files were provided. If a glob pattern was provided, this counts as if isinstance(filename, list): to_be_coadded = filename elif isinstance(filename, str): if "*" in filename: to_be_coadded = [str(p) for p in Path(".").glob(filename)] elif "x1d" in filename: # a single x1d file can contain multiple extensions, which # need to be coadded to_be_coadded = [filename] else: to_be_coadded = None else: warn("filename should be str or list!") raise if to_be_coadded is None: if "x1d" in filename: spectrum = merged_stis_data(filename) rebin = True elif "mxhi" in filename: spectrum = merged_iue_h_data(filename) rebin = True elif "mxlo" in filename: spectrum = iue_l_data(filename) rebin = False else: warn("File {} not supported yet, exiting".format(filename)) exit() else: if "x1d" in to_be_coadded[0]: spectrum = coadd_hst_stis(to_be_coadded) rebin = True elif "mxhi" in to_be_coadded[0]: spectrum = coadd_iue_h(to_be_coadded) rebin = True elif "mxlo" in to_be_coadded[0]: spectrum = coadd_iue_l(to_be_coadded) rebin = False return spectrum, rebin def merged_stis_data(filename, extension=1): """Get spectrum data from all STIS spectral orders. If only filename is given, use SCI extension. Returns ------- wavs: numpy array, all wavelengths, sorted flux: all fluxes at these wavelengths errs: all errors at these wavelengths """ with fits.open(filename) as f: t = f[extension].data exptime = get_exptime(f[extension].header) output_columns = ["WAVELENGTH", "FLUX", "ERROR", "NET"] fields = [np.concatenate(t[c]) for c in output_columns] # clean up by dq dq = np.concatenate(t["DQ"]) good = dq == 0 print(f"STIS: {good.sum()} out of {len(good)} wavelength points are good") fields = [c[good] for c in fields] # sort by wavelength idxs = np.argsort(fields[0]) fields = [c[idxs] for c in fields] # add exptime and create Spectrum (namedtuple) object (* unpacks, # should be in right order) fields.append(exptime) return Spectrum(*fields) def merged_iue_h_data(filename): """ Get Spectrumn info over all orders of high res IUE data. Returns ------- Spectrum """ t = Table.read(filename) allwavs = np.concatenate([iue_wavs(i) for i in range(len(t))]) colnames = ["WAVELENGTH", "ABS_CAL", "NOISE", "NET"] column_values = [allwavs] for colname in colnames[1:]: column_values.append(all_of_column(colname)) # clean up using DQ dq = all_of_column("QUALITY") good = dq == 0 print(f"IUE: {good.sum()} out of {len(good)} wavelength points are good") for array in column_values: array = array[good] # sort by wavelength idxs = np.argsort(column_values[0]) column_values = [c[idxs] for c in column_values] # add exptime and create Spectrum exptime = get_exptime(fits.getheader(filename, ext=0)) fields = column_values + [exptime] return Spectrum(*fields) def coadd_general(spectrums): """General function for coadding spectra. spectrums : list of Spectrum objects Returns ------- spectrum : Spectrum object representing the coadded data """ # get all the per-wavelength data all_wavs = [s.wavs for s in spectrums] # determine new wavelength grid, using max of median of wavelength # increment as step size maxwav = np.amax(np.concatenate(all_wavs)) minwav = np.amin(np.concatenate(all_wavs)) disp = np.amax([np.median(np.diff(w)) for w in all_wavs]) newwavs = np.arange(minwav, maxwav, disp) # instead of binning, we're just going to do nearest neighbour on a # slightly coarser wavelength grid. It worked for Julia, so... flux_sum = np.zeros(len(newwavs)) weight_sum = np.zeros(len(newwavs)) variance_sum = np.zeros(len(newwavs)) net_sum = np.zeros(len(newwavs)) total_exptime = np.zeros(len(newwavs)) for s in spectrums: # nearest neighbour interpolation of all relevant quantities fi = do_interp1d(s.flux) ei = do_interp1d(s.errs) ni = do_interp1d(s.net) exptime = s.exptime # weights scale with ni / fi = sensitivity good_fi_ni = (fi != 0) & np.isfinite(fi) & (ni != 0) & np.isfinite(ni) wi = np.where(good_fi_ni, ni / fi, 0) * exptime good_wi = wi > 0 # total_counts = flux * sensitivity * exptime # --> flux = total_counts / (sensitivity * exptime) # # V(flux) = V(total_counts) / (sensitivity * exptime)**2 # = total_counts / (sensitivity * exptime)**2 (poisson) # = flux * sensitivity * exptime / (sensitivity * exptime)**2 # = flux / (sensitivity * exptime) # sens = counts per flux unit weight_sum[good_wi] += wi[good_wi] flux_sum[good_wi] += wi[good_wi] * fi[good_wi] variance_sum[good_wi] += np.square(ei[good_wi] * wi[good_wi]) net_sum[good_wi] += ni[good_wi] * exptime total_exptime[good_wi] += exptime flux_result = flux_sum / weight_sum errs_result = np.sqrt(variance_sum) / weight_sum net_result = net_sum / total_exptime return Spectrum(newwavs, flux_result, errs_result, net_result, total_exptime) def rebin_spectrum_around_lya(spectrum, wmin=0, wmax=1400, disp=0.25): """Rebin spectrum to for lya fitting, and reject certain points. A rebinning of the spectrum to make it more useful for lya fitting. Every new point is the weighted average of all data within the range of a bin. The weights are flux / net * exptime if those are available. If not 1 / errs**2 is used. The bins can be specified by choosing a minimum, maximum wavelength and a resolution (in Angstrom). Additionally, only the points that satisfy some basic data rejection criteria are used. Returns ------- newwavs: average wavelength in each bin newflux: average flux in each bin """ wavs = spectrum.wavs flux = spectrum.flux wavmin = max(wmin, np.amin(wavs)) wavmax = min(wmax, np.amax(wavs)) wavbins = np.arange(wavmin, wavmax, disp) if spectrum.net is not None and spectrum.exptime is not None: weights = spectrum.net / flux * spectrum.exptime else: weights = 1 / spectrum.errs ** 2 # np.digitize returns list of indices. b = 1 means that the data point # is between wav[0] (first) and wav[1]. b = n-1 means between wav[n-2] # and wav[n-1] (last). b = 0 or n mean out of range. bs = np.digitize(wavs, wavbins) newwavs = np.zeros(len(wavbins) - 1) newflux = np.zeros(len(wavbins) - 1) for i in range(0, len(wavbins) - 1): in_bin = bs == i + 1 # b runs from 1 to n-1 use = np.logical_and.reduce( [in_bin, np.isfinite(flux), weights > 0, np.isfinite(weights)] ) # if a bin is empty or something else is wrong, the nans will be # filtered out later if not use.any(): newwavs[i] = 0 newflux[i] = np.nan continue newwavs[i] = np.average(wavs[use], weights=weights[use]) newflux[i] = np.average(flux[use], weights=weights[use]) return newwavs, newflux def get_exptime(header): """Tries a couple of keywords to find the exposure time in a FITS header""" for exptime_key in ("EXPTIME", "LEXPTIME", "SEXPTIME"): if exptime_key in header: exptime = float(header[exptime_key]) return exptime # Some code to generate the above dict from scratch. Manual tweaking can # occur after. if __name__ == "__main__": gen_dict = {} here = Path(".") for d in list(here.glob("./data/HD*")) + list(here.glob("./data/BD*")): has_iue_h = False has_iue_l = False has_hst_stis = False # has_hst_cos = False # lower in this list of ifs is higher priority target = Path(d).name # def set_if_exists(glob_pattern): # files = d.glob(glob_pattern) # if len(files) > 0: # spectrum_file = files[0] iue_l_files = list(d.glob("*mxlo_vo.fits")) if len(iue_l_files) > 0: spectrum_file = str(iue_l_files[0]) iue_h_files = list(d.glob("*mxhi.gz")) if len(iue_h_files) > 0: spectrum_file = str(iue_h_files[0]) hst_stis_files = list(d.glob("**/*x1d.fits")) if len(hst_stis_files) > 0: spectrum_file = str(hst_stis_files[0]) gen_dict[target] = spectrum_file print(gen_dict)
[ 37811, 33637, 329, 1972, 5444, 430, 329, 300, 3972, 15830, 13, 198, 198, 42986, 11236, 257, 1366, 2393, 329, 1123, 3491, 11, 3555, 262, 3696, 11, 290, 198, 36948, 262, 37410, 1366, 357, 6738, 2035, 314, 8924, 11, 3563, 1797, 11, 2644,...
2.29093
6,108
""" String algorithms """ assert balanced_parens('') assert balanced_parens('()') assert balanced_parens('((()))') assert balanced_parens('((()()()))') assert balanced_parens('((()()()))()(())(()())') assert not balanced_parens('(()') assert not balanced_parens('((())))') assert not balanced_parens('((()())') assert not balanced_parens('())(()') def longest_valid_parens(s: str) -> int: """ return the length of the longest run of valid nested parens. Given a string containing just the characters '(' and ')', find the length of the longest well-formed substring. """ seeds = [(i,i+1) for i in range(len(s)-1) if s[i:i+2]=='()'] grew = True while grew or merged: grew = 0 merged = 0 # grow for i in range(len(seeds)): a,b = seeds[i] if a>0 and b+1<len(s) and s[a-1]=='(' and s[b+1]==')': grew += 1 seeds[i] = (a-1, b+1) # merge new_seeds = [] s0 = seeds[0] for s1 in seeds[1:]: if s0[1]+1==s1[0]: merged += 1 s0 = (s0[0], s1[1]) else: new_seeds.append(s0) s0 = s1 new_seeds.append(s0) seeds = new_seeds return max(b-a+1 for a,b in seeds)
[ 37811, 198, 10100, 16113, 198, 37811, 628, 198, 30493, 12974, 62, 11730, 82, 7, 7061, 8, 198, 30493, 12974, 62, 11730, 82, 10786, 3419, 11537, 198, 30493, 12974, 62, 11730, 82, 10786, 19510, 3419, 4008, 11537, 198, 30493, 12974, 62, 117...
2.003053
655
print("Hello World") type(3) #How many votes did you get? #my_votes = int(input("How many votes did you get in the election?")) #Total votes in the election #total_votes = int(input("What is the total votes in the election?")) #Calculate the percentage of votes you receive #percentage_votes = (my_votes / total_votes)*100 #print("I received " + str(percentage_votes)+"% of the total votes") #IF-ELSE STATEMENT counties = ["Arapahoe","Denver","Jefferson"] if counties[1] == 'Denver': print(counties[1]) #IndexError: list index out of range #if counties[3] != 'Jefferson': # print(counties[2]) #temperature = int(input("What is the temperature outside? ")) #if temperature > 80: # print("Turn on the AC.") #else: # print("Open the windows.") """ #What is the score? score = int(input("What is your test score? ")) # Determine the grade. if score >= 90: print('Your grade is an A.') else: if score >= 80: print('Your grade is a B.') else: if score >= 70: print('Your grade is a C.') else: if score >= 60: print('Your grade is a D.') else: print('Your grade is an F.') # What is the score? score = int(input("What is your test score? ")) # Determine the grade. if score >= 90: print('Your grade is an A.') elif score >= 80: print('Your grade is a B.') elif score >= 70: print('Your grade is a C.') elif score >= 60: print('Your grade is a D.') else: print('Your grade is an F.') """ """ if "Arapahoe" in counties: print("True") else: print("False") if "El Paso" not in counties: print("True") else: print("False") counties = ["Arapahoe","Denver","Jefferson"] if "El Paso" in counties: print("El Paso is in the list of counties.") else: print("El Paso is not the list of counties.") x = 5 y = 5 if x == 5 and y == 5: print("True") else: print("False") if x == 3 or y == 5: print("True") else: print("False") if not(x > y): print("True") else: print("False") if "Arapahoe" in counties and "El Paso" in counties: print("Arapahoe and El Paso are in the list of counties.") else: print("Arapahoe or El Paso is not in the list of counties.") if "Arapahoe" in counties or "El Paso" in counties: print("Arapahoe or El Paso is in the list of counties.") else: print("Arapahoe and El Paso are not in the list of counties.") if "Arapahoe" in counties and "El Paso" not in counties: print("Only Arapahoe is in the list of counties.") else: print("Arapahoe is in the list of counties and El Paso is not in the list of counties.") """ #REPETITION STATEMENT """ #while loop x = 0 while x <= 5: print(x) x = x + 1 #infinite loop: If you forget to write code inside the loop that makes the test condition false, the while loop will continue to run #for loop #the county variable is declared and set equal to the first item in the list of counties, "Arapahoe." for county in counties: print(county) numbers = [0, 1, 2, 3, 4] for num in numbers: print(num) #range for num in range(5): print(num) #Indexing can also be used to iterate through a list for i in range(len(counties)): print(counties[i]) #Iterate through a dictionary counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438} #key for county in counties_dict: print(county) #key for county in counties_dict.keys(): print(county) #values for voters in counties_dict.values(): print(voters) #values for county in counties_dict: print(counties_dict[county]) #values for county in counties_dict: print(counties_dict.get(county)) #Get the Key-Value Pairs of a Dictionary #for key, value in dictionary_name.items(): # print(key, value) for county, voters in counties_dict.items(): print(county, voters) #When iterating over a dictionary: #The first variable declared in the for loop is assigned to the keys. #The second variable is assigned to the values. for county, voters in counties_dict.items(): print(str(county) + "county has " + str(voters) + " registered") voting_data = [{"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters": 463353}, {"county":"Jefferson", "registered_voters": 432438}] #Get Each Dictionary in a List of Dictionaries for county_dict in voting_data: print(county_dict) for i in range(len(voting_data)): print(voting_data[i]['county']) #Get the Values from a List of Dictionaries for county_dict in voting_data: for value in county_dict.values(): print(value) #How would you retrieve the number of registered voters from each dictionary? for county_dict in voting_data: print(county_dict['registered_voters']) #If we only want to print the county name from each dictionary, we can use county_dict['county'] for county_dict in voting_data: print(county_dict['county']) """ #Printing Formats """ #my_votes = int(input("How many votes did you get in the election? ")) #total_votes = int(input("What is the total votes in the election? ")) #percentage_votes = (my_votes / total_votes) * 100 #print("I received " + str(percentage_votes)+"% of the total votes.") #print(f"I received {my_votes / total_votes * 100}% of the total votes.") counties_dict = {"Arapahoe": 369237, "Denver":413229, "Jefferson": 390222} for county, voters in counties_dict.items(): print(county + " county has " + str(voters) + " registered voters.") for county, voters in counties_dict.items(): print(f"{county} county has {voters} registered voters.") candidate_votes = int(input("How many votes did the candidate get in the election? ")) total_votes = int(input("What is the total number of votes in the election? ")) message_to_candidate = ( f"You received {candidate_votes} number of votes. " f"The total number of votes in the election was {total_votes}. " f"You received {candidate_votes / total_votes * 100}% of the total votes.") print(message_to_candidate) message_to_candidate = ( f"You received {candidate_votes:,} number of votes. " f"The total number of votes in the election was {total_votes:,}. " f"You received {candidate_votes / total_votes * 100:.2f}% of the total votes.") print(message_to_candidate) """
[ 4798, 7203, 15496, 2159, 4943, 198, 4906, 7, 18, 8, 198, 198, 2, 2437, 867, 5690, 750, 345, 651, 30, 198, 2, 1820, 62, 29307, 796, 493, 7, 15414, 7203, 2437, 867, 5690, 750, 345, 651, 287, 262, 3071, 1701, 4008, 198, 2, 14957, 5...
2.797609
2,258
import numpy as np import pandas as pd import torch as th import tqdm import os if __name__ == '__main__': parser = argparse.ArgumentParser(description='.') parser.add_argument('--include_val', help='whether include val') parser.add_argument('--head_upsample_epochs', help='upample rate') parser.add_argument('--t_threshold', help='train score threshold') parser.add_argument('--v_threshold', help='val score threshold') generator_val_hrt() generator_new_train(args.include_val,args.head_upsample_epochs,args.t_threshold,args.v_threshold) generator_new_val(args.include_val,args.head_upsample_epochs,args.t_threshold,args.v_threshold) generator_for_finefune(args.include_val,args.head_upsample_epochs,args.t_threshold,args.v_threshold)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 28034, 355, 294, 198, 11748, 256, 80, 36020, 198, 11748, 28686, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 197, 48610, 796, ...
2.722807
285
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2020 PANGAEA (https://www.pangaea.de/) # # 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 fuji_server.helper.metadata_collector import MetaDataCollector import feedparser class MetaDataCollectorOreAtom(MetaDataCollector): """ A class to collect the Object Reuse and Exchange (ORE) Atom metadata from the data. This class is child class of MetadataCollector. ... Attributes ---------- source_name : str Source name of metadata target_url : str Target URL of the metadata Methods -------- parse_metadata() Method to parse the ORE Atom metadata from the data. """ source_name = None def __init__(self, loggerinst, target_url): """ Parameters ---------- loggerinst : logging.Logger Logger instance target_url : str Target URL """ #self.is_pid = ispid self.target_url = target_url super().__init__(logger=loggerinst) def parse_metadata(self): """Parse the ORE Atom metadata from the data Returns ------ str a string of source name dict a dictionary of ORE Atom metadata """ ore_metadata = {} if self.target_url: self.source_name = self.getEnumSourceNames().OAI_ORE.value try: feed = feedparser.parse(self.target_url) if feed: if feed.get('entries'): if len(feed.get('entries')) == 1: ore_metadata['title'] = feed.get('entries')[0].get('title') ore_metadata['creator'] = feed.get('entries')[0].get('author') ore_metadata['publisher'] = feed.get('entries')[0].get('source') ore_metadata['publication_date'] = feed.get('entries')[0].get('published') if feed.get('entries')[0].get('source'): ore_metadata['publisher'] = feed.get('entries')[0].get('source').get('author') ore_metadata['object_identifier'] = [feed.get('entries')[0].get('id')] if feed.get('entries')[0].get('link'): ore_metadata['object_identifier'].append(feed.get('entries')[0].get('link')) if feed.get('entries')[0].get('link'): pid = feed.get('entries')[0].get('link') if pid != self.target_url: ore_metadata['object_identifier'] = feed.get('entries')[0].get('link') if feed.get('entries')[0].get('links'): ore_metadata['object_content_identifier'] = [] for link in feed.get('entries')[0].get('links'): if 'ore/terms/aggregates' in str(link.get('rel')): ore_metadata['object_content_identifier'].append({ 'url': str(link.get('href')), 'type': str(link.get('type')), 'size': str(link.get('length')) }) except Exception as err: #print(err.with_traceback()) self.logger.info('FsF-F2-01M : Failed to parse OAI ORE XML -: {}'.format(err)) else: self.logger.info('FsF-F2-01M : Could not identify OAI ORE metadata') return self.source_name, ore_metadata
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 17168, 13789, 198, 2, 198, 2, 15069, 357, 66, 8, 12131, 40468, 9273, 16412, 357, 5450, 1378, 2503, 13, 79, 648, 44705, 13, 2934, 34729, 198, 2, 198, 2, 2448,...
2.123435
2,236
############################################################################### # The MIT License (MIT) # # Copyright (c) 2014 Justin Lovinger # # 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. ############################################################################### import pytest from optimal import problems, optimize, GenAlg from optimal.algorithms import crossentropy @pytest.mark.parametrize('solution,pdf,expected', [ ([1, 1], [0.5, 0.5], 0.25), ([0, 0], [0.5, 0.5], 0.25), ([0, 0], [0.0, 0.0], 1.0), ([1, 1], [1.0, 1.0], 1.0), ([1, 1, 1], [1.0, 1.0, 1.0], 1.0), ([1, 1, 1], [0.0, 0.0, 0.0], 0.0), ([0, 0, 0], [1.0, 1.0, 1.0], 0.0), ([0, 0, 0], [0.5, 0.5, 0.5], 0.125), ([1, 1, 1], [0.5, 0.5, 0.5], 0.125), ]) @pytest.mark.parametrize('values,q,expected', [ ([0.0, 0.5, 1.0], 1, 0.5), ([0.0, 0.5, 1.0], 0, 1.0), ([0.0, 0.5, 1.0], 2, 0.0), ([1.0, 0.5, 0.0], 0, 1.0), ]) @pytest.mark.parametrize('num_values,q,expected', [(10, 1.0, 0), (10, 0.0, 9), (10, 0.5, 4)]) @pytest.mark.slowtest() @pytest.mark.slowtest()
[ 29113, 29113, 7804, 4242, 21017, 198, 2, 383, 17168, 13789, 357, 36393, 8, 198, 2, 198, 2, 15069, 357, 66, 8, 1946, 10799, 39911, 3889, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, ...
2.618293
820
import unittest from ..sequence.aligner import Aligner if __name__ == "__main__": unittest.main()
[ 11748, 555, 715, 395, 198, 198, 6738, 11485, 43167, 13, 31494, 263, 1330, 978, 570, 263, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 198 ]
2.65
40
import threading import wsgiref.util from wsgiref.simple_server import make_server import http.server import socketserver import socket import tweepy import urllib.parse def server_bind(self): """Override server_bind to fix UnicodeDecodeError when computer name has non-ascii characters.""" socketserver.TCPServer.server_bind(self) host, port = self.server_address[:2] try: self.server_name = socket.getfqdn(host) except UnicodeDecodeError: self.server_name = "localhost" self.server_port = port http.server.HTTPServer.server_bind = server_bind class _RedirectWSGIApp(object): """ WSGI app to handle the authorization redirect. Stores the request URI and displays the given success message. """ def __init__(self, port, hook,failedHook): """ Args: port (int): The port number That receive request hook (callable): The function when got token failedHook (callable): The function when authorization failed (ex: disagreed authorize) """ self.successMessage="Authorization successful. Close this window and go back to your application." self.failedMessage="Authorization failed. Please try again." self.transferMessage="If the screen does not change after a while, open this page in another browser." self.lang = "ja" self.port = port self.hook = hook self.failedHook = failedHook def setMessage(self,lang,success,failed,transfer): """ Set Message that viewd in browser Args: lang (string): The message language code (ex:ja,en,...) success (string): The success message failed (string): The failed message transfer (string): The transfer error message that appear in old or Javascript disabled browser """ self.lang=lang self.successMessage=success self.failedMessage=failed self.transferMessage=transfer def __call__(self, environ, start_response): """ Args: environ (Mapping[str, Any]): The WSGI environment. start_response (Callable[str, list]): The WSGI start_response callable. Returns: Iterable[bytes]: The response body. """ try: uri = wsgiref.util.request_uri(environ) query = urllib.parse.urlparse(uri).query queryDic = urllib.parse.parse_qs(query) #例外発生しなければ正当なリクエスト #サーバ側で処理 if query != "": self.hook(queryDic) start_response('200 OK', [('Content-type', 'text/html; charset=utf-8')]) response=[("<html lang='"+self.lang+"'><head><title>Authorization result</title><meta charset='utf-8'></head><body>"+self.successMessage+"<script><!--\n").encode('utf-8')] response.append("window.close()\n".encode("utf-8")) response.append("--></script></body></html>".encode("utf-8")) return response except Exception as e: if query != "": #favicon.icoなどの不要なリクエストへの対策 self.failedHook() start_response('400 Bad Request', [('Content-type', 'text/html; charset=utf-8')]) return [("<html lang='"+self.lang+"'><head><title>Authorization result</title><meta charset='utf-8'></head><body>"+self.failedMessage+"</body></html>").encode('utf-8')]
[ 11748, 4704, 278, 198, 11748, 266, 45213, 557, 69, 13, 22602, 198, 6738, 266, 45213, 557, 69, 13, 36439, 62, 15388, 1330, 787, 62, 15388, 198, 11748, 2638, 13, 15388, 198, 11748, 37037, 18497, 198, 11748, 17802, 198, 11748, 4184, 538, ...
2.761468
1,090
# Copyright 2019 Filipe Assuncao # 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. import random import keras from keras import backend from time import time import tensorflow as tf import numpy as np from keras.callbacks import Callback, ModelCheckpoint import os from fast_denser.utilities.data import load_dataset from multiprocessing import Pool import contextlib #TODO: future -- impose memory constraints # tf.config.experimental.set_virtual_device_configuration(gpus[0], [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=50)]) DEBUG = False class TimedStopping(keras.callbacks.Callback): """ Stop training when maximum time has passed. Code from: https://github.com/keras-team/keras-contrib/issues/87 Attributes ---------- start_time : float time when the training started seconds : float maximum time before stopping. verbose : bool verbosity mode. Methods ------- on_train_begin(logs) method called upon training beginning on_epoch_end(epoch, logs={}) method called after the end of each training epoch """ def __init__(self, seconds=None, verbose=0): """ Parameters ---------- seconds : float maximum time before stopping. vebose : bool verbosity mode """ super(keras.callbacks.Callback, self).__init__() self.start_time = 0 self.seconds = seconds self.verbose = verbose def on_train_begin(self, logs={}): """ Method called upon training beginning Parameters ---------- logs : dict training logs """ self.start_time = time() def on_epoch_end(self, epoch, logs={}): """ Method called after the end of each training epoch. Checks if the maximum time has passed Parameters ---------- epoch : int current epoch logs : dict training logs """ if time() - self.start_time > self.seconds: self.model.stop_training = True if self.verbose: print('Stopping after %s seconds.' % self.seconds) class Evaluator: """ Stores the dataset, maps the phenotype into a trainable model, and evaluates it Attributes ---------- dataset : dict dataset instances and partitions fitness_metric : function fitness_metric (y_true, y_pred) y_pred are the confidences Methods ------- get_layers(phenotype) parses the phenotype corresponding to the layers auxiliary function of the assemble_network function get_learning(learning) parses the phenotype corresponding to the learning auxiliary function of the assemble_optimiser function assemble_network(keras_layers, input_size) maps the layers phenotype into a keras model assemble_optimiser(learning) maps the learning into a keras optimiser evaluate(phenotype, load_prev_weights, weights_save_path, parent_weights_path, train_time, num_epochs, datagen=None, input_size=(32, 32, 3)) evaluates the keras model using the keras optimiser testing_performance(self, model_path) compute testing performance of the model """ def __init__(self, dataset, fitness_metric): """ Creates the Evaluator instance and loads the dataset. Parameters ---------- dataset : str dataset to be loaded """ self.dataset = load_dataset(dataset) self.fitness_metric = fitness_metric def get_layers(self, phenotype): """ Parses the phenotype corresponding to the layers. Auxiliary function of the assemble_network function. Parameters ---------- phenotye : str individual layers phenotype Returns ------- layers : list list of tuples (layer_type : str, node properties : dict) """ raw_phenotype = phenotype.split(' ') idx = 0 first = True node_type, node_val = raw_phenotype[idx].split(':') layers = [] while idx < len(raw_phenotype): if node_type == 'layer': if not first: layers.append((layer_type, node_properties)) else: first = False layer_type = node_val node_properties = {} else: node_properties[node_type] = node_val.split(',') idx += 1 if idx < len(raw_phenotype): node_type, node_val = raw_phenotype[idx].split(':') layers.append((layer_type, node_properties)) return layers def get_learning(self, learning): """ Parses the phenotype corresponding to the learning Auxiliary function of the assemble_optimiser function Parameters ---------- learning : str learning phenotype of the individual Returns ------- learning_params : dict learning parameters """ raw_learning = learning.split(' ') idx = 0 learning_params = {} while idx < len(raw_learning): param_name, param_value = raw_learning[idx].split(':') learning_params[param_name] = param_value.split(',') idx += 1 for _key_ in sorted(list(learning_params.keys())): if len(learning_params[_key_]) == 1: try: learning_params[_key_] = eval(learning_params[_key_][0]) except NameError: learning_params[_key_] = learning_params[_key_][0] return learning_params def assemble_network(self, keras_layers, input_size): """ Maps the layers phenotype into a keras model Parameters ---------- keras_layers : list output from get_layers input_size : tuple network input shape Returns ------- model : keras.models.Model keras trainable model """ #input layer inputs = keras.layers.Input(shape=input_size) #Create layers -- ADD NEW LAYERS HERE layers = [] for layer_type, layer_params in keras_layers: #convolutional layer if layer_type == 'conv': conv_layer = keras.layers.Conv2D(filters=int(layer_params['num-filters'][0]), kernel_size=(int(layer_params['filter-shape'][0]), int(layer_params['filter-shape'][0])), strides=(int(layer_params['stride'][0]), int(layer_params['stride'][0])), padding=layer_params['padding'][0], activation=layer_params['act'][0], use_bias=eval(layer_params['bias'][0]), kernel_initializer='he_normal', kernel_regularizer=keras.regularizers.l2(0.0005)) layers.append(conv_layer) #batch-normalisation elif layer_type == 'batch-norm': #TODO - check because channels are not first batch_norm = keras.layers.BatchNormalization() layers.append(batch_norm) #average pooling layer elif layer_type == 'pool-avg': pool_avg = keras.layers.AveragePooling2D(pool_size=(int(layer_params['kernel-size'][0]), int(layer_params['kernel-size'][0])), strides=int(layer_params['stride'][0]), padding=layer_params['padding'][0]) layers.append(pool_avg) #max pooling layer elif layer_type == 'pool-max': pool_max = keras.layers.MaxPooling2D(pool_size=(int(layer_params['kernel-size'][0]), int(layer_params['kernel-size'][0])), strides=int(layer_params['stride'][0]), padding=layer_params['padding'][0]) layers.append(pool_max) #fully-connected layer elif layer_type == 'fc': fc = keras.layers.Dense(int(layer_params['num-units'][0]), activation=layer_params['act'][0], use_bias=eval(layer_params['bias'][0]), kernel_initializer='he_normal', kernel_regularizer=keras.regularizers.l2(0.0005)) layers.append(fc) #dropout layer elif layer_type == 'dropout': dropout = keras.layers.Dropout(rate=min(0.5, float(layer_params['rate'][0]))) layers.append(dropout) #gru layer #TODO: initializers, recurrent dropout, dropout, unroll, reset_after elif layer_type == 'gru': gru = keras.layers.GRU(units=int(layer_params['units'][0]), activation=layer_params['act'][0], recurrent_activation=layer_params['rec_act'][0], use_bias=eval(layer_params['bias'][0])) layers.append(gru) #lstm layer #TODO: initializers, recurrent dropout, dropout, unroll, reset_after elif layer_type == 'lstm': lstm = keras.layers.LSTM(units=int(layer_params['units'][0]), activation=layer_params['act'][0], recurrent_activation=layer_params['rec_act'][0], use_bias=eval(layer_params['bias'][0])) layers.append(lstm) #rnn #TODO: initializers, recurrent dropout, dropout, unroll, reset_after elif layer_type == 'rnn': rnn = keras.layers.SimpleRNN(units=int(layer_params['units'][0]), activation=layer_params['act'][0], use_bias=eval(layer_params['bias'][0])) layers.append(rnn) elif layer_type == 'conv1d': #todo initializer conv1d = keras.layers.Conv1D(filters=int(layer_params['num-filters'][0]), kernel_size=int(layer_params['kernel-size'][0]), strides=int(layer_params['strides'][0]), padding=layer_params['padding'][0], activation=layer_params['activation'][0], use_bias=eval(layer_params['bias'][0])) layers.add(conv1d) #END ADD NEW LAYERS #Connection between layers for layer in keras_layers: layer[1]['input'] = list(map(int, layer[1]['input'])) first_fc = True data_layers = [] invalid_layers = [] for layer_idx, layer in enumerate(layers): try: if len(keras_layers[layer_idx][1]['input']) == 1: if keras_layers[layer_idx][1]['input'][0] == -1: data_layers.append(layer(inputs)) else: if keras_layers[layer_idx][0] == 'fc' and first_fc: first_fc = False flatten = keras.layers.Flatten()(data_layers[keras_layers[layer_idx][1]['input'][0]]) data_layers.append(layer(flatten)) continue data_layers.append(layer(data_layers[keras_layers[layer_idx][1]['input'][0]])) else: #Get minimum shape: when merging layers all the signals are converted to the minimum shape minimum_shape = input_size[0] for input_idx in keras_layers[layer_idx][1]['input']: if input_idx != -1 and input_idx not in invalid_layers: if data_layers[input_idx].shape[-3:][0] < minimum_shape: minimum_shape = int(data_layers[input_idx].shape[-3:][0]) #Reshape signals to the same shape merge_signals = [] for input_idx in keras_layers[layer_idx][1]['input']: if input_idx == -1: if inputs.shape[-3:][0] > minimum_shape: actual_shape = int(inputs.shape[-3:][0]) merge_signals.append(keras.layers.MaxPooling2D(pool_size=(actual_shape-(minimum_shape-1), actual_shape-(minimum_shape-1)), strides=1)(inputs)) else: merge_signals.append(inputs) elif input_idx not in invalid_layers: if data_layers[input_idx].shape[-3:][0] > minimum_shape: actual_shape = int(data_layers[input_idx].shape[-3:][0]) merge_signals.append(keras.layers.MaxPooling2D(pool_size=(actual_shape-(minimum_shape-1), actual_shape-(minimum_shape-1)), strides=1)(data_layers[input_idx])) else: merge_signals.append(data_layers[input_idx]) if len(merge_signals) == 1: merged_signal = merge_signals[0] elif len(merge_signals) > 1: merged_signal = keras.layers.concatenate(merge_signals) else: merged_signal = data_layers[-1] data_layers.append(layer(merged_signal)) except ValueError as e: data_layers.append(data_layers[-1]) invalid_layers.append(layer_idx) if DEBUG: print(keras_layers[layer_idx][0]) print(e) model = keras.models.Model(inputs=inputs, outputs=data_layers[-1]) if DEBUG: model.summary() return model def assemble_optimiser(self, learning): """ Maps the learning into a keras optimiser Parameters ---------- learning : dict output of get_learning Returns ------- optimiser : keras.optimizers.Optimizer keras optimiser that will be later used to train the model """ if learning['learning'] == 'rmsprop': return keras.optimizers.RMSprop(learning_rate = float(learning['lr']), rho = float(learning['rho']), decay = float(learning['decay'])) elif learning['learning'] == 'gradient-descent': return keras.optimizers.SGD(learning_rate = float(learning['lr']), momentum = float(learning['momentum']), decay = float(learning['decay']), nesterov = bool(learning['nesterov'])) elif learning['learning'] == 'adam': return keras.optimizers.Adam(learning_rate = float(learning['lr']), beta_1 = float(learning['beta1']), beta_2 = float(learning['beta2']), decay = float(learning['decay'])) def evaluate(self, phenotype, load_prev_weights, weights_save_path, parent_weights_path,\ train_time, num_epochs, datagen=None, datagen_test = None, input_size=(32, 32, 3)): #pragma: no cover """ Evaluates the keras model using the keras optimiser Parameters ---------- phenotype : str individual phenotype load_prev_weights : bool resume training from a previous train or not weights_save_path : str path where to save the model weights after training parent_weights_path : str path to the weights of the previous training train_time : float maximum training time num_epochs : int maximum number of epochs datagen : keras.preprocessing.image.ImageDataGenerator Data augmentation method image data generator input_size : tuple dataset input shape Returns ------- score_history : dict training data: loss and accuracy """ model_phenotype, learning_phenotype = phenotype.split('learning:') learning_phenotype = 'learning:'+learning_phenotype.rstrip().lstrip() model_phenotype = model_phenotype.rstrip().lstrip().replace(' ', ' ') keras_layers = self.get_layers(model_phenotype) keras_learning = self.get_learning(learning_phenotype) batch_size = int(keras_learning['batch_size']) if load_prev_weights and os.path.exists(parent_weights_path.replace('.hdf5', '.h5')): model = keras.models.load_model(parent_weights_path.replace('.hdf5', '.h5')) else: if load_prev_weights: num_epochs = 0 model = self.assemble_network(keras_layers, input_size) opt = self.assemble_optimiser(keras_learning) model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy']) #early stopping early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=int(keras_learning['early_stop']), restore_best_weights=True) #time based stopping time_stop = TimedStopping(seconds=train_time, verbose=DEBUG) #save individual with the lowest validation loss #useful for when traaining is halted because of time monitor = ModelCheckpoint(weights_save_path, monitor='val_loss', verbose=DEBUG, save_best_only=True) trainable_count = model.count_params() if datagen is not None: score = model.fit_generator(datagen.flow(self.dataset['evo_x_train'], self.dataset['evo_y_train'], batch_size=batch_size), steps_per_epoch=(self.dataset['evo_x_train'].shape[0]//batch_size), epochs=int(keras_learning['epochs']), validation_data=(datagen_test.flow(self.dataset['evo_x_val'], self.dataset['evo_y_val'], batch_size=batch_size)), validation_steps = (self.dataset['evo_x_val'].shape[0]//batch_size), callbacks = [early_stop, time_stop, monitor], initial_epoch = num_epochs, verbose= DEBUG) else: score = model.fit(x = self.dataset['evo_x_train'], y = self.dataset['evo_y_train'], batch_size = batch_size, epochs = int(keras_learning['epochs']), steps_per_epoch=(self.dataset['evo_x_train'].shape[0]//batch_size), validation_data=(self.dataset['evo_x_val'], self.dataset['evo_y_val']), callbacks = [early_stop, time_stop, monitor], initial_epoch = num_epochs, verbose = DEBUG) #save final moodel to file model.save(weights_save_path.replace('.hdf5', '.h5')) #measure test performance if datagen_test is None: y_pred_test = model.predict(self.dataset['evo_x_test'], batch_size=batch_size, verbose=0) else: y_pred_test = model.predict_generator(datagen_test.flow(self.dataset['evo_x_test'], batch_size=100, shuffle=False), steps=self.dataset['evo_x_test'].shape[0]//100, verbose=DEBUG) accuracy_test = self.fitness_metric(self.dataset['evo_y_test'], y_pred_test) if DEBUG: print(phenotype, accuracy_test) score.history['trainable_parameters'] = trainable_count score.history['accuracy_test'] = accuracy_test keras.backend.clear_session() return score.history def testing_performance(self, model_path, datagen_test): #pragma: no cover """ Compute testing performance of the model Parameters ---------- model_path : str Path to the model .h5 file Returns ------- accuracy : float Model accuracy """ model = keras.models.load_model(model_path) if datagen_test is None: y_pred = model.predict(self.dataset['x_test']) else: y_pred = model.predict_generator(datagen_test.flow(self.dataset['x_test'], shuffle=False, batch_size=1)) accuracy = self.fitness_metric(self.dataset['y_test'], y_pred) return accuracy def evaluate(args): #pragma: no cover """ Function used to deploy a new process to train a candidate solution. Each candidate solution is trained in a separe process to avoid memory problems. Parameters ---------- args : tuple cnn_eval : Evaluator network evaluator phenotype : str individual phenotype load_prev_weights : bool resume training from a previous train or not weights_save_path : str path where to save the model weights after training parent_weights_path : str path to the weights of the previous training train_time : float maximum training time num_epochs : int maximum number of epochs Returns ------- score_history : dict training data: loss and accuracy """ import tensorflow as tf gpus = tf.config.experimental.list_physical_devices('GPU') tf.config.experimental.set_memory_growth(gpus[0], True) cnn_eval, phenotype, load_prev_weights, weights_save_path, parent_weights_path, train_time, num_epochs, datagen, datagen_test = args try: return cnn_eval.evaluate(phenotype, load_prev_weights, weights_save_path, parent_weights_path, train_time, num_epochs, datagen, datagen_test) except tf.errors.ResourceExhaustedError as e: keras.backend.clear_session() return None except TypeError as e2: keras.backend.clear_session() return None class Module: """ Each of the units of the outer-level genotype Attributes ---------- module : str non-terminal symbol min_expansions : int minimum expansions of the block max_expansions : int maximum expansions of the block levels_back : dict number of previous layers a given layer can receive as input layers : list list of layers of the module connections : dict list of connetions of each layer Methods ------- initialise(grammar, reuse) Randomly creates a module """ def __init__(self, module, min_expansions, max_expansions, levels_back, min_expansins): """ Parameters ---------- module : str non-terminal symbol min_expansions : int minimum expansions of the block max_expansions : int maximum expansions of the block levels_back : dict number of previous layers a given layer can receive as input """ self.module = module self.min_expansions = min_expansins self.max_expansions = max_expansions self.levels_back = levels_back self.layers = [] self.connections = {} def initialise(self, grammar, reuse, init_max): """ Randomly creates a module Parameters ---------- grammar : Grammar grammar instace that stores the expansion rules reuse : float likelihood of reusing an existing layer Returns ------- score_history : dict training data: loss and accuracy """ num_expansions = random.choice(init_max[self.module]) #Initialise layers for idx in range(num_expansions): if idx>0 and random.random() <= reuse: r_idx = random.randint(0, idx-1) self.layers.append(self.layers[r_idx]) else: self.layers.append(grammar.initialise(self.module)) #Initialise connections: feed-forward and allowing skip-connections self.connections = {} for layer_idx in range(num_expansions): if layer_idx == 0: #the -1 layer is the input self.connections[layer_idx] = [-1,] else: connection_possibilities = list(range(max(0, layer_idx-self.levels_back), layer_idx-1)) if len(connection_possibilities) < self.levels_back-1: connection_possibilities.append(-1) sample_size = random.randint(0, len(connection_possibilities)) self.connections[layer_idx] = [layer_idx-1] if sample_size > 0: self.connections[layer_idx] += random.sample(connection_possibilities, sample_size) class Individual: """ Candidate solution. Attributes ---------- network_structure : list ordered list of tuples formated as follows [(non-terminal, min_expansions, max_expansions), ...] output_rule : str output non-terminal symbol macro_rules : list list of non-terminals (str) with the marco rules (e.g., learning) modules : list list of Modules (genotype) of the layers output : dict output rule genotype macro : list list of Modules (genotype) for the macro rules phenotype : str phenotype of the candidate solution fitness : float fitness value of the candidate solution metrics : dict training metrics num_epochs : int number of performed epochs during training trainable_parameters : int number of trainable parameters of the network time : float network training time current_time : float performed network training time train_time : float maximum training time id : int individual unique identifier Methods ------- initialise(grammar, levels_back, reuse) Randomly creates a candidate solution decode(grammar) Maps the genotype to the phenotype evaluate(grammar, cnn_eval, weights_save_path, parent_weights_path='') Performs the evaluation of a candidate solution """ def __init__(self, network_structure, macro_rules, output_rule, ind_id): """ Parameters ---------- network_structure : list ordered list of tuples formated as follows [(non-terminal, min_expansions, max_expansions), ...] macro_rules : list list of non-terminals (str) with the marco rules (e.g., learning) output_rule : str output non-terminal symbol ind_id : int individual unique identifier """ self.network_structure = network_structure self.output_rule = output_rule self.macro_rules = macro_rules self.modules = [] self.output = None self.macro = [] self.phenotype = None self.fitness = None self.metrics = None self.num_epochs = 0 self.trainable_parameters = None self.time = None self.current_time = 0 self.train_time = 0 self.id = ind_id def initialise(self, grammar, levels_back, reuse, init_max): """ Randomly creates a candidate solution Parameters ---------- grammar : Grammar grammar instaces that stores the expansion rules levels_back : dict number of previous layers a given layer can receive as input reuse : float likelihood of reusing an existing layer Returns ------- candidate_solution : Individual randomly created candidate solution """ for non_terminal, min_expansions, max_expansions in self.network_structure: new_module = Module(non_terminal, min_expansions, max_expansions, levels_back[non_terminal], min_expansions) new_module.initialise(grammar, reuse, init_max) self.modules.append(new_module) #Initialise output self.output = grammar.initialise(self.output_rule) # Initialise the macro structure: learning, data augmentation, etc. for rule in self.macro_rules: self.macro.append(grammar.initialise(rule)) return self def decode(self, grammar): """ Maps the genotype to the phenotype Parameters ---------- grammar : Grammar grammar instaces that stores the expansion rules Returns ------- phenotype : str phenotype of the individual to be used in the mapping to the keras model. """ phenotype = '' offset = 0 layer_counter = 0 for module in self.modules: offset = layer_counter for layer_idx, layer_genotype in enumerate(module.layers): layer_counter += 1 phenotype += ' ' + grammar.decode(module.module, layer_genotype)+ ' input:'+",".join(map(str, np.array(module.connections[layer_idx])+offset)) phenotype += ' '+grammar.decode(self.output_rule, self.output)+' input:'+str(layer_counter-1) for rule_idx, macro_rule in enumerate(self.macro_rules): phenotype += ' '+grammar.decode(macro_rule, self.macro[rule_idx]) self.phenotype = phenotype.rstrip().lstrip() return self.phenotype def evaluate(self, grammar, cnn_eval, datagen, datagen_test, weights_save_path, parent_weights_path=''): #pragma: no cover """ Performs the evaluation of a candidate solution Parameters ---------- grammar : Grammar grammar instaces that stores the expansion rules cnn_eval : Evaluator Evaluator instance used to train the networks datagen : keras.preprocessing.image.ImageDataGenerator Data augmentation method image data generator weights_save_path : str path where to save the model weights after training parent_weights_path : str path to the weights of the previous training Returns ------- fitness : float quality of the candidate solutions """ phenotype = self.decode(grammar) start = time() load_prev_weights = True if self.current_time == 0: load_prev_weights = False train_time = self.train_time - self.current_time num_pool_workers=1 with contextlib.closing(Pool(num_pool_workers)) as po: pool_results = po.map_async(evaluate, [(cnn_eval, phenotype, load_prev_weights,\ weights_save_path, parent_weights_path,\ train_time, self.num_epochs, datagen, datagen_test)]) metrics = pool_results.get()[0] if metrics is not None: metrics['val_accuracy'] = [i.item() for i in metrics['val_accuracy']] metrics['loss'] = [i.item() for i in metrics['loss']] metrics['accuracy'] = [i.item() for i in metrics['accuracy']] self.metrics = metrics self.fitness = self.metrics['accuracy_test'].item() self.num_epochs += len(self.metrics['val_accuracy']) self.trainable_parameters = self.metrics['trainable_parameters'] self.current_time += (self.train_time-self.current_time) else: self.metrics = None self.fitness = -1 self.num_epochs = 0 self.trainable_parameters = -1 self.current_time = 0 self.time = time() - start return self.fitness
[ 2, 15069, 13130, 376, 2403, 431, 2195, 19524, 5488, 198, 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,...
1.987805
17,630
from topomc.common.coordinates import Coordinates from topomc.processes.topomap import Depression, Hill, TopoMap from topomc.symbol import PointSymbol from topomc import app
[ 6738, 1353, 296, 66, 13, 11321, 13, 37652, 17540, 1330, 22819, 17540, 198, 6738, 1353, 296, 66, 13, 14681, 274, 13, 4852, 296, 499, 1330, 22483, 11, 3327, 11, 5849, 78, 13912, 198, 6738, 1353, 296, 66, 13, 1837, 23650, 1330, 6252, 1...
3.346154
52
# Created by Egor Kostan. # GitHub: https://github.com/ikostan # LinkedIn: https://www.linkedin.com/in/egor-kostan/ def first_non_consecutive(arr: list): """ Find the first element of an array that is not consecutive. E.g. If we have an array [1,2,3,4,6,7,8] then 1 then 2 then 3 then 4 are all consecutive but 6 is not, so that's the first non-consecutive number. If the whole array is consecutive then return null or Nothing. :param arr: :return: """ for index, n in enumerate(arr): if index + 1 < len(arr) and n + 1 != arr[index + 1]: return arr[index + 1]
[ 2, 220, 15622, 416, 412, 7053, 509, 455, 272, 13, 198, 2, 220, 21722, 25, 3740, 1378, 12567, 13, 785, 14, 1134, 455, 272, 198, 2, 220, 27133, 25, 3740, 1378, 2503, 13, 25614, 259, 13, 785, 14, 259, 14, 1533, 273, 12, 74, 455, ...
2.563265
245
OVERTIME_LIMIT = 40.0 hours = input("Enter Hours:") hours_f = float(hours) rate = input("Enter Rate:") rate_f = float(rate) pay = computepay(hours_f, rate_f) print("Pay", pay)
[ 46, 15858, 12789, 62, 43, 3955, 2043, 796, 2319, 13, 15, 198, 198, 24425, 796, 5128, 7203, 17469, 19347, 25, 4943, 198, 24425, 62, 69, 796, 12178, 7, 24425, 8, 198, 198, 4873, 796, 5128, 7203, 17469, 14806, 25, 4943, 198, 4873, 62, ...
2.445946
74
from django.urls import path from modules.users.index import ( user_info, user_tweets, user_medias, user_replies, user_likes, ) urlpatterns = [ path("", user_info, name="info"), path("tweets", user_tweets, name="tweets"), path("medias", user_medias, name="medias"), path("likes", user_likes, name="likes"), path("comments", user_replies, name="comments"), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 198, 6738, 13103, 13, 18417, 13, 9630, 1330, 357, 198, 220, 220, 220, 2836, 62, 10951, 11, 198, 220, 220, 220, 2836, 62, 83, 732, 1039, 11, 198, 220, 220, 220, 2836, 62, 2379, 292...
2.39521
167
#!/usr/bin/env python import datetime import json import logging import os from typing import Optional, List, Dict from raft_peer import Peer LOG = logging.getLogger(__name__) LOG.setLevel(logging.DEBUG) class LeaderVolatileState(object): """ Volatile state on leaders: (Reinitialized after election) nextIndex[]: for each server, index of the next log entry to send to that server (initialized to leader last log index + 1) matchIndex[]: for each server, index of highest log entry known to be replicated on server (initialized to 0, increases monotonically) """ class NodeVolatileState(object): """ Volatile state on all servers: commitIndex: index of highest log entry known to be committed (initialized to 0, increases monotonically) lastApplied: index of highest log entry applied to state machine (initialized to 0, increases monotonically) """ class NodePersistentState(object): """ Persistent state on all servers: (Updated on stable storage before responding to RPCs) currentTerm: latest term server has seen (initialized to 0 on first boot, increases monotonically) votedFor: candidateId that received vote in current term (or null if none) log[]: log entries; each entry contains command for state machine, and term when entry was received by leader (first index is 1) """ @classmethod def load(cls, fpath): """ load persistent state from a file :param fpath: path of state. Created if it does not already exist. """ if not os.path.exists(fpath): open(fpath, 'a').close() with open(fpath, 'r') as f: json_str = f.read() json_obj = json.loads(json_str or '{}') current_term = json_obj.get('current_term', 0) voted_for = json_obj.get('voted_for', None) logs = [] for l in json_obj.get('logs', []): entry = Entry.from_bytes(bytes(l, encoding='utf-8')) logs.append(entry) return NodePersistentState(fpath, current_term, voted_for, logs) class BookingData(object): """ BookingData represents a room booking to be stored in the Raft log. """ @classmethod class Entry(object): """ Entry represents a single log entry. """ @classmethod
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 4818, 8079, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, 28686, 198, 6738, 19720, 1330, 32233, 11, 7343, 11, 360, 713, 198, 198, 6738, 31812, 62, 33350, 1330, 41139, 198, 198...
2.76285
856
import sys import skdd.core as core if __name__ == "__main__": if len(sys.argv) > 1: filename = sys.argv[1] else: filename = 'test.xlsx' core.analysis(filename)
[ 11748, 25064, 198, 198, 11748, 1341, 1860, 13, 7295, 355, 4755, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 611, 18896, 7, 17597, 13, 853, 85, 8, 1875, 352, 25, 198, 220, 220, 220, 220, 2...
2.157303
89
import os import Errors as err import Settings as props import FileHandler as fl import JSONHandler as js from ProjectClass import Project
[ 11748, 28686, 198, 11748, 44225, 355, 11454, 198, 11748, 16163, 355, 25744, 198, 11748, 9220, 25060, 355, 781, 198, 11748, 19449, 25060, 355, 44804, 198, 6738, 4935, 9487, 1330, 4935 ]
4.6
30
import csv import os import re from concurrent import futures from concurrent.futures import ThreadPoolExecutor from html.parser import HTMLParser from operator import itemgetter from urllib import request from urllib.error import HTTPError def csv_to_list(filename: str) -> list: """Receive an csv filename and returns rows of file with an list""" with open(filename) as csv_file: reader = csv.DictReader(csv_file) csv_data = [line for line in reader] return csv_data def get_files_in_directory(directory: str) -> list: """Receive an directory and returns an list of filenames in directory""" full_filenames = [] for root, dirs, files in os.walk(directory): for file in files: filename = os.path.join(root, file) full_filenames.append(filename) return full_filenames def evaluate_job_file(filename: str, metrics: list) -> tuple: """ Receive an filename and metrics (list of dicts containing metrics) and return an poor level and words with match """ poor_level = 0 words = [] with open(filename) as file: content = file.read() for metric in metrics: lower_term = metric['Terms'].lower() pattern = r'\b{}\b'.format(lower_term) lower_content = content.lower() if re.search(pattern, lower_content): poor_level += int(metric['Poor level']) words.append(metric['Terms']) return poor_level, words def order_by_key(results_list: list, order_key: str) -> list: """Receive an list of dicts and return ordered list by order_key""" reordered_results = sorted(results_list, key=itemgetter(order_key)) return reordered_results def get_pyjob_codes(url='http://www.pyjobs.com.br/', page=1) -> list: """Receive and url and page of pyjobs and return list of codes of jobs""" job_codes = [] full_url = '{}?page={}'.format(url, page) try: response = request.urlopen(full_url) except HTTPError as exc: print('Error "{}" when get "{}"'.format(exc.msg, full_url)) return job_codes pattern = r'href="/job/([0-9]+)/"' for line in response: decoded_line = line.decode('utf-8') match = re.search(pattern, decoded_line) if match: job_code = match.group(1) job_codes.append(job_code) return job_codes def get_pyjob_content(pyjob_code: str) -> str: """Get an pyjob_code and return your description""" job_url = 'http://www.pyjobs.com.br/job/{}/' url = job_url.format(pyjob_code) try: response = request.urlopen(url) except HTTPError as exc: print('Error "{}" when get "{}"'.format(exc.msg, url)) return (pyjob_code, None) response_content = response.read().decode('utf-8') parser = ParsePyjobsHTML() parser.feed(response_content) return (pyjob_code, parser.parsed_content) def async_get_pyjob_codes(initial_page: int, final_page: int, max_workers=10) -> list: """Get initial_page and final_page of pyjobs and return a list pyjob_codes from pages""" print('Running async_get_pyjob_codes...') pyjob_codes = [] pages = range(initial_page, final_page + 1) with ThreadPoolExecutor(max_workers=max_workers) as executor: to_do_map = {} for page in pages: future = executor.submit(get_pyjob_codes, page=page) to_do_map[future] = page done_iter = futures.as_completed(to_do_map) for future in done_iter: pyjob_codes += future.result() return pyjob_codes def async_get_pyjob_content(pyjob_codes: list, max_workers=10) -> list: """Get pyjob_codes, get content of pyjob and return a list of contents""" print('Running async_get_pyjob_content...') contets = [] with ThreadPoolExecutor(max_workers=max_workers) as executor: to_do_map = {} for pyjob_code in pyjob_codes: future = executor.submit(get_pyjob_content, pyjob_code=pyjob_code) to_do_map[future] = pyjob_code done_iter = futures.as_completed(to_do_map) for future in done_iter: pyjob_code, content = future.result() contets.append((pyjob_code, content)) return contets
[ 11748, 269, 21370, 198, 11748, 28686, 198, 11748, 302, 198, 6738, 24580, 1330, 25650, 198, 6738, 24580, 13, 69, 315, 942, 1330, 14122, 27201, 23002, 38409, 198, 6738, 27711, 13, 48610, 1330, 11532, 46677, 198, 6738, 10088, 1330, 2378, 113...
2.508824
1,700
#!/usr/bin/env python import os from lib import Udger def is_crawler(client_ip): """ :return: crawler or not """ data_dir = os.path.join(os.path.dirname(__file__), 'data') udger = Udger(data_dir) return True if udger.parse_ip(client_ip)['ip_classification_code'] == 'crawler' else False def get_ua(client_ua): """ :return: dict {ua_family_code, ua_version, ua_class_code, device_class_code, os_family_code, os_code} """ data_dir = os.path.join(os.path.dirname(__file__), 'data') udger = Udger(data_dir) result = {} ua_obj = udger.parse_ua(client_ua) result['ua_family_code'] = ua_obj['ua_family_code'] result['ua_version'] = ua_obj['ua_version'] result['ua_class_code'] = ua_obj['ua_class_code'] result['device_class_code'] = ua_obj['device_class_code'] result['os_family_code'] = ua_obj['os_family_code'] result['os_code'] = ua_obj['os_code'] return result
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 28686, 198, 198, 6738, 9195, 1330, 35774, 1362, 628, 198, 4299, 318, 62, 66, 39464, 7, 16366, 62, 541, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 1058, 7783, 25...
2.276995
426
import unittest from pylti1p3.utils import add_param_to_url
[ 11748, 555, 715, 395, 198, 6738, 12972, 2528, 72, 16, 79, 18, 13, 26791, 1330, 751, 62, 17143, 62, 1462, 62, 6371, 628 ]
2.652174
23
import platform import importlib import itertools _init() __all__ = [ name for name, func in globals().items() if callable(func) and not name.startswith('_') ]
[ 11748, 3859, 198, 11748, 1330, 8019, 198, 11748, 340, 861, 10141, 628, 628, 198, 62, 15003, 3419, 628, 198, 834, 439, 834, 796, 685, 198, 220, 220, 220, 1438, 198, 220, 220, 220, 329, 1438, 11, 25439, 287, 15095, 874, 22446, 23814, ...
2.69697
66
# coding=utf-8 from PyQt4.QtGui import * from PyQt4.QtCore import * from v.ui_acerca_de import Ui_Acerca_de
[ 2, 19617, 28, 40477, 12, 23, 198, 6738, 9485, 48, 83, 19, 13, 48, 83, 8205, 72, 1330, 1635, 198, 6738, 9485, 48, 83, 19, 13, 48, 83, 14055, 1330, 1635, 198, 198, 6738, 410, 13, 9019, 62, 330, 2798, 64, 62, 2934, 1330, 471, 72,...
2.056604
53
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) # Package meta-data. NAME = "neuromodels" DESCRIPTION = "Computational neuroscience models and model tools." URL = "https://github.com/nicolossus/neuromodels" EMAIL = "prof.haug@gmail.com" AUTHOR = "Nicolai Haug" REQUIRES_PYTHON = '>=3.8.0' REQUIRES_INSTALL = [ "numpy", "matplotlib", "scipy", "pandas", "seaborn", "neo", "quantities", "elephant", "viziphant" ] REQUIRES_EXTRAS = { "dev": [ "pytest", "pytest-cov", "flake8>=3.9.2", "isort", "twine", ], } with open("README.md", "r") as fh: LONG_DESCRIPTION = fh.read() about = {} with open(os.path.join(here, NAME, "__version__.py")) as f: exec(f.read(), about) VERSION = about['__version__'] setup( name=NAME, version=VERSION, description=DESCRIPTION, long_description_content_type="text/markdown", long_description=LONG_DESCRIPTION, author=AUTHOR, author_email=EMAIL, url=URL, packages=find_packages(exclude=["tests", ]), python_requires=REQUIRES_PYTHON, install_requires=REQUIRES_INSTALL, extras_require=REQUIRES_EXTRAS, classifiers=[ "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 198, 198, 6738, 900, 37623, 10141, 1330, 1064, 62, 43789, 11, 9058, 198, 198, 1456, 796, 28686, 13, ...
2.231214
692
""" Contains classes which serve to provide functionalities that handle calculations involving coordinate systems. """ import sys from math import atan, pi from coordinatesystem.component import Point2D from coordinatesystem.component import Line2D from coordinatesystem.exceptions import ZeroDistanceError class EquivalentCoordinate: """ A class handling conversion from a cartesian coordinate system to another scaled or rotated equivalent cartesian coordinate system. Two reference points must be provided for each coordinate system in order to plot a point from the original coordinate to the equivalent coordinate. :param origpointref1: First reference point from the original coordinate system. :param origpointref2: Second reference point from the original coordinate system. :param equipointref1: First reference point from the equivalent coordinate system. :param equipointref2: Second reference point from the equivalent coordinate system. """ def get_equivalent_point(self, origpoint): """ Gets the point in the equivalent coordinate system correponding to a point the the original coordinate system. :param origpoint: Point in the original coordinate system. :returns: Point in the equivalent coordinate system. """ origdistance = self.origpointref1.get_distance(origpoint) origline = Line2D.from_two_points(self.origpointref1, origpoint) # Get the equivalent distance. equidistance = self.__distancescale * origdistance # Get the equivalent angle. Add 180 degrees if the point is # located below the line which is perpendicular to the original line reference. anglebetween = origline.get_angle_between(self.__origlineref) origperpenline = Line2D.from_point_slope(self.__origperpensloperef, self.origpointref1) if(origperpenline.is_above_point(origpoint) != origperpenline.is_above_point(self.origpointref2)): anglebetween += pi equipointrelative = Point2D.from_polar_coordinate(equidistance, anglebetween) equipointrelative.rotate(atan(-self.__origlineref.slope)) # Reflect if references are reflected. if(self.__is_reflected_horizontally): equipointrelative.x *= -1 if(self.__is_reflected_vertically): equipointrelative.y *= -1 # Offset the first equivalent point reference. equipoint = self.equipointref1 equipoint.offset(equipointrelative.x, equipointrelative.y) return equipoint
[ 37811, 198, 4264, 1299, 6097, 543, 4691, 284, 2148, 10345, 871, 326, 5412, 16765, 198, 259, 10396, 1075, 20435, 3341, 13, 198, 37811, 198, 198, 11748, 25064, 198, 6738, 10688, 1330, 379, 272, 11, 31028, 198, 198, 6738, 22715, 6781, 13, ...
3.077289
841
# Generated by Django 2.2.7 on 2020-01-23 06:35 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 22, 319, 12131, 12, 486, 12, 1954, 9130, 25, 2327, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.818182
44