content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import unittest from flask_monitoringdashboard.core.profiler.util.stringHash import StringHash
[ 11748, 555, 715, 395, 198, 198, 6738, 42903, 62, 41143, 278, 42460, 3526, 13, 7295, 13, 5577, 5329, 13, 22602, 13, 8841, 26257, 1330, 10903, 26257, 628 ]
3.592593
27
from django.shortcuts import render, get_object_or_404 from .models import News # Create your views here.
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 651, 62, 15252, 62, 273, 62, 26429, 198, 6738, 764, 27530, 1330, 3000, 198, 2, 13610, 534, 5009, 994, 13, 628, 628 ]
3.516129
31
#!/usr/bin/python import os.path import cppcodebase import random
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 28686, 13, 6978, 198, 11748, 269, 381, 8189, 8692, 198, 11748, 4738, 628, 628, 198 ]
2.84
25
""" FOTA update tool which is called from the dispatcher during installation Copyright (C) 2017-2022 Intel Corporation SPDX-License-Identifier: Apache-2.0 """ import logging import os import platform from threading import Timer from typing import Any, Optional, Mapping from future.moves.urllib.parse import urlparse from inbm_common_lib.exceptions import UrlSecurityException from inbm_common_lib.utility import canonicalize_uri from inbm_common_lib.constants import REMOTE_SOURCE from .constants import * from .fota_error import FotaError from .manifest import parse_tool_options, parse_guid, parse_hold_reboot_flag from .os_factory import OsFactory, OsType from ..common import dispatcher_state from ..common.result_constants import * from ..constants import UMASK_OTA from ..dispatcher_callbacks import DispatcherCallbacks from ..dispatcher_exception import DispatcherException from ..downloader import download from ..packagemanager.local_repo import DirectoryRepo logger = logging.getLogger(__name__)
[ 37811, 198, 220, 220, 220, 376, 29009, 4296, 2891, 543, 318, 1444, 422, 262, 49952, 1141, 9988, 628, 220, 220, 220, 15069, 357, 34, 8, 2177, 12, 1238, 1828, 8180, 10501, 198, 220, 220, 220, 30628, 55, 12, 34156, 12, 33234, 7483, 25,...
3.462838
296
import copy import datetime import sys import os import time import argparse import traceback import pytz import syncthing from influxdb import InfluxDBClient import yaml from yaml2dataclass import Schema, SchemaPath from typing import Optional, Dict, Type, List from dataclasses import dataclass, asdict, field def load_app_config(stream) -> AppConfiguration: """Load application configuration from a stream.""" obj = yaml.safe_load(stream) return AppConfiguration.scm_load_from_dict(obj) def error(message: str): sys.stderr.write("\nerror: " + message + "\n") sys.stderr.flush() raise SystemExit(-1) def info(*values): if not args.silent: print(*values) parser = argparse.ArgumentParser(description='Monitor your Syncthing instances with influxdb.') parser.add_argument('-c', "--config", dest="config", default=None, help="Configuration file for application. Default is syncflux.yml. " "See syncflux_example.yml for an example.") parser.add_argument("--config-dir", dest="config_dir", default=None, help="Configuration directory. All config files with .yml extension will be processed one by one.") parser.add_argument('-n', "--count", dest="count", default=1, type=int, help="Number of test runs. Default is one. Use -1 to run indefinitely.") parser.add_argument('-w', "--wait", dest="wait", default=60, type=float, help="Number of seconds between test runs.") parser.add_argument("-s", "--silent", dest='silent', action="store_true", default=False, help="Supress all messages except errors.") parser.add_argument("-v", "--verbose", dest='verbose', action="store_true", default=False, help="Be verbose." ) parser.add_argument("--halt-on-send-error", dest="halt_on_send_error", default=False, action="store_true", help="Halt when cannot send data to influxdb. The default is to ignore the error.") args = parser.parse_args() if args.silent and args.verbose: parser.error("Cannot use --silent and --verbose at the same time.") if args.config is None: args.config = "syncflux.yml" if (args.config is not None) and (args.config_dir is not None): parser.error("You must give either --config or --config-dir (exactly one of them)") if args.count == 0: parser.error("Test run count cannot be zero.") if args.wait <= 0: parser.error("Wait time must be positive.") if args.config: config_files = [args.config] else: config_files = [] for file_name in sorted(os.listdir(args.config_dir)): ext = os.path.splitext(file_name)[1] if ext.lower() == ".yml": fpath = os.path.join(args.config_dir, file_name) config_files.append(fpath) index = 0 while args.count < 0 or index < args.count: if args.count != 1: info("Pass #%d started" % (index + 1)) started = time.time() for config_file in config_files: if not os.path.isfile(config_file): parser.error("Cannot open %s" % config_file) config = load_app_config(open(config_file, "r")) main() elapsed = time.time() - started index += 1 last_one = (args.count > 0) and (index == args.count) if not last_one: remaining = args.wait - elapsed if remaining > 0: if not args.silent: info("Pass #%d elapsed %.2f sec, waiting %.2f sec for next." % (index, elapsed, remaining)) time.sleep(args.wait) else: info("Pass #%d elapsed %.2f sec" % (index, elapsed)) info("")
[ 11748, 4866, 198, 11748, 4818, 8079, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 640, 198, 11748, 1822, 29572, 198, 11748, 12854, 1891, 198, 198, 11748, 12972, 22877, 198, 11748, 6171, 310, 722, 198, 6738, 25065, 9945, 1330, 4806, 2...
2.552374
1,432
# -*- coding: utf-8 -*- import os import re import shutil import typing from PIL import Image from PyPDF2 import PdfFileReader import PyPDF2.utils import pytest from preview_generator.exception import UnavailablePreviewType from preview_generator.manager import PreviewManager from tests import test_utils CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) CACHE_DIR = "/tmp/preview-generator-tests/cache" PDF_FILE_PATH = os.path.join(CURRENT_DIR, "the_pdf.pdf") PDF_FILE_PATH__ENCRYPTED = os.path.join(CURRENT_DIR, "the_pdf.encrypted.pdf") PDF_FILE_PATH__A4 = os.path.join(CURRENT_DIR, "qpdfconvert.pdf")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 4423, 346, 198, 11748, 19720, 198, 198, 6738, 350, 4146, 1330, 7412, 198, 6738, 9485, 20456, 17, 1330, 350, 7568, 8979, 3...
2.757709
227
from ipso_phen.ipapi.base.ipt_abstract import IptBase from ipso_phen.ipapi.tools import regions import numpy as np import cv2 import logging logger = logging.getLogger(__name__) from ipso_phen.ipapi.base import ip_common as ipc
[ 6738, 20966, 568, 62, 31024, 13, 541, 15042, 13, 8692, 13, 10257, 62, 397, 8709, 1330, 314, 457, 14881, 201, 198, 6738, 20966, 568, 62, 31024, 13, 541, 15042, 13, 31391, 1330, 7652, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, ...
2.585106
94
from wrapper_tests.upsert_test import * from wrapper_tests.upsertvaluedict_test import * import os import logging import sys import argparse import signal logging.getLogger().setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) formatter = logging.Formatter('[%(asctime)s - %(name)s] %(message)s') ch.setFormatter(formatter) logging.getLogger().addHandler(ch) parser = argparse.ArgumentParser( description='Unit testing for fiery snap.') parser.add_argument('-config', type=str, default=None, help='toml config for keys and such, see key.toml') if __name__ == '__main__': unittest.main() os.kill(os.getpid(), signal.SIGKILL)
[ 6738, 29908, 62, 41989, 13, 4739, 861, 62, 9288, 1330, 1635, 198, 6738, 29908, 62, 41989, 13, 4739, 861, 39728, 713, 62, 9288, 1330, 1635, 198, 11748, 28686, 198, 11748, 18931, 198, 11748, 25064, 198, 11748, 1822, 29572, 198, 11748, 673...
2.610909
275
import smtplib gmail_user = 'your email' gmail_password = 'your password' sent_from = gmail_user to = ['reciever email'] #Create a list for all the recievers subject = 'OMG Super Important Message' body = 'Hey, what\'s up?\n- You' email_text = """\ From: %s To: %s Subject: %s %s """ % (sent_from, ", ".join(to), subject, body) try: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(gmail_user, gmail_password) server.sendmail(sent_from, to, email_text) server.close() print('Email sent!') except Exception as e: print(e)
[ 11748, 895, 83, 489, 571, 198, 198, 14816, 62, 7220, 796, 705, 14108, 3053, 6, 220, 220, 198, 14816, 62, 28712, 796, 705, 14108, 9206, 6, 198, 198, 34086, 62, 6738, 796, 308, 4529, 62, 7220, 220, 220, 198, 1462, 796, 37250, 8344, ...
2.430894
246
''' Created on 11 Sep 2015 @author: si ''' import json import random import time from threading import Thread # import urllib import urllib2 from Queue import Queue import logging logger = logging.getLogger(__name__) API_URL = "http://127.0.0.1:5000/" if __name__ == '__main__': l = LoadTest(10,30) l.go()
[ 7061, 6, 198, 41972, 319, 1367, 8621, 1853, 198, 198, 31, 9800, 25, 33721, 198, 7061, 6, 198, 11748, 33918, 198, 11748, 4738, 198, 11748, 640, 198, 6738, 4704, 278, 1330, 14122, 198, 2, 1330, 2956, 297, 571, 198, 11748, 2956, 297, 5...
2.563492
126
from django.contrib import admin from django.conf.urls import include,url from .import views urlpatterns = [ url(r'^$', views.IndexView.as_view(),name='index'), #homeapp_detail_view_url url(r'^(?P<pk>[0-9]+)/$',views.LocationView.as_view(),name='property'), #homeapp/detailview/moredetailview url(r'^([0-9]+)/(?P<pk>[0-9]+)/$',views.PropertyView.as_view(),name='propertyview'), ]
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 2291, 11, 6371, 198, 6738, 764, 11748, 5009, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 19016, 7, 81, 6, 61, 3, ...
2.352601
173
from utils import * from model import Model2 if __name__ == '__main__': train_data = DataLoader('../data/trainX.txt', '../data/trainY.txt') test_data = DataLoader('../data/testX.txt', '../data/testY.txt') train_data.set_batch(100) test_data.set_batch(100) char_dic = CharDic([train_data]) model = Model2(train_data=train_data, test_data=test_data, char_dic=char_dic, model_name='bilstm_crf_n3_e300_h2002') model.train() model.test()
[ 6738, 3384, 4487, 1330, 1635, 201, 198, 6738, 2746, 1330, 9104, 17, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 201, 198, 220, 220, 220, 4512, 62, 7890, 796, 6060, 17401, 10786, 40720, 7890, 14, 27432...
1.99631
271
#!/usr/bin/env python ############################################################################## ## # This file is part of Sardana ## # http://www.sardana-controls.org/ ## # Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain ## # Sardana is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. ## # Sardana is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. ## # You should have received a copy of the GNU Lesser General Public License # along with Sardana. If not, see <http://www.gnu.org/licenses/>. ## ############################################################################## """ macrodescriptionviewer.py: """ import taurus.core from taurus.external.qt import Qt from taurus.qt.qtgui.base import TaurusBaseWidget if __name__ == "__main__": test()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 29113, 29113, 7804, 4242, 2235, 198, 2235, 198, 2, 770, 2393, 318, 636, 286, 46997, 2271, 198, 2235, 198, 2, 2638, 1378, 2503, 13, 82, 446, 2271, 12, 13716, 82, 13, 2398, 14, ...
3.711974
309
import numpy as np
[ 11748, 299, 32152, 355, 45941, 628 ]
3.333333
6
from asaas.typing import SyncAsync from typing import Any, Optional, Dict
[ 6738, 355, 64, 292, 13, 774, 13886, 1330, 35908, 42367, 198, 6738, 19720, 1330, 4377, 11, 32233, 11, 360, 713, 628 ]
3.571429
21
from functools import partial from uuid import UUID from dateutil.parser import parse as dateutil_parse from django.apps import apps from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from rest_framework import serializers from rest_framework.exceptions import ValidationError from rest_framework.fields import ReadOnlyField, UUIDField from datahub.core.constants import Country as CountryEnum from datahub.core.validate_utils import DataCombiner from datahub.core.validators import InRule, OperatorRule, RulesBasedValidator, ValidationRule from datahub.metadata.models import AdministrativeArea, Country MAX_LENGTH = settings.CHAR_FIELD_MAX_LENGTH RelaxedDateField = partial(serializers.DateField, input_formats=('iso-8601', '%Y/%m/%d'))
[ 6738, 1257, 310, 10141, 1330, 13027, 198, 6738, 334, 27112, 1330, 471, 27586, 198, 198, 6738, 3128, 22602, 13, 48610, 1330, 21136, 355, 3128, 22602, 62, 29572, 198, 6738, 42625, 14208, 13, 18211, 1330, 6725, 198, 6738, 42625, 14208, 13, ...
3.497778
225
import math import random from ark import dear_imgui, ApplicationFacade, Arena, Event, Integer, Collider, RenderObject, Size, Camera, Vec3, Numeric if __name__ == '__main__': main(Application(_application))
[ 11748, 10688, 198, 11748, 4738, 198, 198, 6738, 610, 74, 1330, 13674, 62, 320, 48317, 11, 15678, 47522, 671, 11, 10937, 11, 8558, 11, 34142, 11, 50253, 11, 46722, 10267, 11, 12849, 11, 20432, 11, 38692, 18, 11, 399, 39223, 628, 628, ...
3.375
64
# coding: utf-8 """ Jamf Pro API ## Overview This is a sample Jamf Pro server which allows for usage without any authentication. The Jamf Pro environment which supports the Try it Out functionality does not run the current beta version of Jamf Pro, thus any newly added endpoints will result in an error and should be used soley for documentation purposes. # noqa: E501 The version of the OpenAPI document: 10.25.0 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from jamf.configuration import Configuration def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ComputerExtensionAttribute): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, ComputerExtensionAttribute): return True return self.to_dict() != other.to_dict()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 220, 220, 220, 9986, 69, 1041, 7824, 628, 220, 220, 220, 22492, 28578, 770, 318, 257, 6291, 9986, 69, 1041, 4382, 543, 3578, 329, 8748, 1231, 597, 18239, 13, 383, 9986, 69, 104...
2.920561
428
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ssokeygendialog.ui' # # Created: Sun Feb 1 12:33:36 2015 # by: PyQt5 UI code generator 5.4 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 5178, 7822, 7560, 422, 3555, 334, 72, 2393, 705, 82, 568, 2539, 70, 437, 498, 519, 13, 9019, 6, 198, 2, 198, 2, 15622, 25, 3825, 3158, 220, 352, 1105, 25, ...
2.622642
106
import urllib.request import os from typing import List from util.n_util import NUser from util.n_util import get_n_entry import time import threading from util.array_util import slice_array delay: float = 2.5 def save_files_to_dir(file_url_list: List[str], path: str, update=None, thread_count: int = 1) -> None: """Saves all files represented by a list of url resources to the folder specified. The files are being named after the last part of the url. The number of threads can be increased to use more threads for the downloading of the images.""" # pretend to be normal user # opener=urllib.request.build_opener() # opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')] # urllib.request.install_opener(opener) progress = ProgressWrapper(0, len(file_url_list), update) progress.update() if thread_count < 1 or thread_count > 16: print(f'invalid thread count: {thread_count} not in [1, 16]') return else: lock = threading.Lock() threads = [] for i in range(thread_count): slices = slice_array(file_url_list, thread_count) t = threading.Thread(target=download_images, kwargs=dict(lock=lock, file_url_list=slices[i], path=path, progress=progress), daemon=True) threads.append(t) t.start() for t in threads: t.join() def download_all_favorites(n_user: NUser, base_dir: str, update_entry=None, update_page=None, thread_count=1) -> None: """Downloads all entries favorited by `n_user` using the number of `thread_count` threads.""" print('downloading {}\'s {} favorites...'.format(n_user.username, n_user.fav_count)) current_entry = 1 total_entries = n_user.fav_count for min_entry in n_user.favorite_list: if update_entry is not None: update_entry(current_entry=min_entry, current=current_entry, total=total_entries) # get entry data print('downloading entry with id {}'.format(min_entry.n_id)) entry = get_n_entry(min_entry.n_id) if entry is None: print('no connection possible, skipping...') current_entry += 1 continue # check directory is valid if not os.path.exists(base_dir): print('base directory does not exist, aborting...') break save_dir = os.path.join(base_dir, entry.digits) if os.path.exists(save_dir): print('entry already exists, skipping...') current_entry += 1 continue else: os.mkdir(save_dir) # download images save_files_to_dir(entry.image_url_list, save_dir, update=update_page, thread_count=thread_count) print('waiting for {} seconds...'.format(delay)) time.sleep(delay) current_entry += 1 if update_entry is not None: update_entry(current_entry=None, current=current_entry, total=total_entries) print('download finished')
[ 11748, 2956, 297, 571, 13, 25927, 198, 11748, 28686, 198, 6738, 19720, 1330, 7343, 198, 6738, 7736, 13, 77, 62, 22602, 1330, 399, 12982, 198, 6738, 7736, 13, 77, 62, 22602, 1330, 651, 62, 77, 62, 13000, 198, 11748, 640, 198, 11748, ...
2.359792
1,348
import pytest from stable_baselines import A2C, ACER, ACKTR, DeepQ, DDPG, PPO1, PPO2, TRPO from stable_baselines.ddpg import AdaptiveParamNoiseSpec from stable_baselines.common.identity_env import IdentityEnv, IdentityEnvBox from stable_baselines.common.vec_env import DummyVecEnv PARAM_NOISE_DDPG = AdaptiveParamNoiseSpec(initial_stddev=float(0.2), desired_action_stddev=float(0.2)) # Hyperparameters for learning identity for each RL model LEARN_FUNC_DICT = { 'a2c': lambda e: A2C(policy="MlpPolicy", env=e).learn(total_timesteps=1000), 'acer': lambda e: ACER(policy="MlpPolicy", env=e).learn(total_timesteps=1000), 'acktr': lambda e: ACKTR(policy="MlpPolicy", env=e).learn(total_timesteps=1000), 'deepq': lambda e: DeepQ(policy="MlpPolicy", env=e).learn(total_timesteps=1000), 'ddpg': lambda e: DDPG(policy="MlpPolicy", env=e, param_noise=PARAM_NOISE_DDPG).learn(total_timesteps=1000), 'ppo1': lambda e: PPO1(policy="MlpPolicy", env=e).learn(total_timesteps=1000), 'ppo2': lambda e: PPO2(policy="MlpPolicy", env=e).learn(total_timesteps=1000), 'trpo': lambda e: TRPO(policy="MlpPolicy", env=e).learn(total_timesteps=1000), }
[ 11748, 12972, 9288, 198, 198, 6738, 8245, 62, 12093, 20655, 1330, 317, 17, 34, 11, 7125, 1137, 11, 7125, 42, 5446, 11, 10766, 48, 11, 360, 6322, 38, 11, 350, 16402, 16, 11, 350, 16402, 17, 11, 7579, 16402, 198, 6738, 8245, 62, 120...
2.521645
462
import tensorflow as tf from tensorflow.python.saved_model import signature_constants from tensorflow.python.saved_model import tag_constants export_dir = './reference/00000002' graph_pb = './creditcardfraud.pb' builder = tf.saved_model.builder.SavedModelBuilder(export_dir) with tf.gfile.GFile(graph_pb, "rb") as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) sigs = {} with tf.Session(graph=tf.Graph()) as sess: # name="" is important to ensure we don't get spurious prefixing tf.import_graph_def(graph_def, name="") g = tf.get_default_graph() inp1 = g.get_tensor_by_name("transaction:0") inp2 = g.get_tensor_by_name("reference:0") out = g.get_tensor_by_name("output:0") sigs[signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY] = \ tf.saved_model.signature_def_utils.predict_signature_def( {"transaction": inp1, "reference": inp2}, {"output": out}) builder.add_meta_graph_and_variables(sess, [tag_constants.SERVING], signature_def_map=sigs) builder.save()
[ 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11192, 273, 11125, 13, 29412, 13, 82, 9586, 62, 19849, 1330, 9877, 62, 9979, 1187, 198, 6738, 11192, 273, 11125, 13, 29412, 13, 82, 9586, 62, 19849, 1330, 7621, 62, 9979, 1187, 198, 198...
2.253493
501
from __future__ import division from __future__ import absolute_import from pycuda.tools import context_dependent_memoize import numpy as np
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 6738, 12972, 66, 15339, 13, 31391, 1330, 4732, 62, 21186, 62, 11883, 78, 1096, 198, 11748, 299, 32152, 355, 45941, 628, 628, 198 ]
3.65
40
import torch from scipy.stats import median_absolute_deviation
[ 11748, 28034, 201, 198, 6738, 629, 541, 88, 13, 34242, 1330, 14288, 62, 48546, 62, 7959, 3920, 201, 198, 201, 198, 201, 198, 201, 198 ]
2.84
25
# eliminate duplicate service periods from a GTFS database from graphserver.ext.gtfs.gtfsdb import GTFSDatabase import sys from optparse import OptionParser if __name__=='__main__':
[ 2, 11005, 23418, 2139, 9574, 422, 257, 7963, 10652, 6831, 198, 198, 6738, 4823, 15388, 13, 2302, 13, 13655, 9501, 13, 13655, 9501, 9945, 1330, 7963, 37, 10305, 265, 5754, 198, 198, 11748, 25064, 198, 6738, 2172, 29572, 1330, 16018, 4667...
2.871429
70
print(MyClass().__repr__())
[ 4798, 7, 3666, 9487, 22446, 834, 260, 1050, 834, 28955, 198 ]
2.545455
11
import pytest from prefect.core import Edge, Flow, Parameter, Task from prefect.tasks.core import collections from prefect.tasks.core.constants import Constant from prefect.tasks.core.function import FunctionTask
[ 11748, 12972, 9288, 198, 198, 6738, 662, 2309, 13, 7295, 1330, 13113, 11, 27782, 11, 25139, 2357, 11, 15941, 198, 6738, 662, 2309, 13, 83, 6791, 13, 7295, 1330, 17268, 198, 6738, 662, 2309, 13, 83, 6791, 13, 7295, 13, 9979, 1187, 13...
3.57377
61
"""Node class module for Binary Tree."""
[ 37811, 19667, 1398, 8265, 329, 45755, 12200, 526, 15931, 628 ]
4.2
10
# This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the QuTiP: Quantum Toolbox in Python 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 # HOLDER 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. ############################################################################### """ This module contains functions for generating Qobj representation of a variety of commonly occuring quantum operators. """ __all__ = ['jmat', 'spin_Jx', 'spin_Jy', 'spin_Jz', 'spin_Jm', 'spin_Jp', 'spin_J_set', 'sigmap', 'sigmam', 'sigmax', 'sigmay', 'sigmaz', 'destroy', 'create', 'qeye', 'identity', 'position', 'momentum', 'num', 'squeeze', 'squeezing', 'displace', 'commutator', 'qutrit_ops', 'qdiags', 'phase', 'qzero', 'enr_destroy', 'enr_identity', 'charge', 'tunneling'] import numbers import numpy as np import scipy import scipy.sparse as sp from qutip.qobj import Qobj from qutip.fastsparse import fast_csr_matrix, fast_identity from qutip.dimensions import flatten # # Spin operators # def jmat(j, *args): """Higher-order spin operators: Parameters ---------- j : float Spin of operator args : str Which operator to return 'x','y','z','+','-'. If no args given, then output is ['x','y','z'] Returns ------- jmat : qobj / ndarray ``qobj`` for requested spin operator(s). Examples -------- >>> jmat(1) # doctest: +SKIP [ Quantum object: dims = [[3], [3]], \ shape = [3, 3], type = oper, isHerm = True Qobj data = [[ 0. 0.70710678 0. ] [ 0.70710678 0. 0.70710678] [ 0. 0.70710678 0. ]] Quantum object: dims = [[3], [3]], \ shape = [3, 3], type = oper, isHerm = True Qobj data = [[ 0.+0.j 0.-0.70710678j 0.+0.j ] [ 0.+0.70710678j 0.+0.j 0.-0.70710678j] [ 0.+0.j 0.+0.70710678j 0.+0.j ]] Quantum object: dims = [[3], [3]], \ shape = [3, 3], type = oper, isHerm = True Qobj data = [[ 1. 0. 0.] [ 0. 0. 0.] [ 0. 0. -1.]]] Notes ----- If no 'args' input, then returns array of ['x','y','z'] operators. """ if (np.fix(2 * j) != 2 * j) or (j < 0): raise TypeError('j must be a non-negative integer or half-integer') if not args: return jmat(j, 'x'), jmat(j, 'y'), jmat(j, 'z') if args[0] == '+': A = _jplus(j) elif args[0] == '-': A = _jplus(j).getH() elif args[0] == 'x': A = 0.5 * (_jplus(j) + _jplus(j).getH()) elif args[0] == 'y': A = -0.5 * 1j * (_jplus(j) - _jplus(j).getH()) elif args[0] == 'z': A = _jz(j) else: raise TypeError('Invalid type') return Qobj(A) def _jplus(j): """ Internal functions for generating the data representing the J-plus operator. """ m = np.arange(j, -j - 1, -1, dtype=complex) data = (np.sqrt(j * (j + 1.0) - (m + 1.0) * m))[1:] N = m.shape[0] ind = np.arange(1, N, dtype=np.int32) ptr = np.array(list(range(N-1))+[N-1]*2, dtype=np.int32) ptr[-1] = N-1 return fast_csr_matrix((data,ind,ptr), shape=(N,N)) def _jz(j): """ Internal functions for generating the data representing the J-z operator. """ N = int(2*j+1) data = np.array([j-k for k in range(N) if (j-k)!=0], dtype=complex) # Even shaped matrix if (N % 2 == 0): ind = np.arange(N, dtype=np.int32) ptr = np.arange(N+1,dtype=np.int32) ptr[-1] = N # Odd shaped matrix else: j = int(j) ind = np.array(list(range(j))+list(range(j+1,N)), dtype=np.int32) ptr = np.array(list(range(j+1))+list(range(j,N)), dtype=np.int32) ptr[-1] = N-1 return fast_csr_matrix((data,ind,ptr), shape=(N,N)) # # Spin j operators: # def spin_Jx(j): """Spin-j x operator Parameters ---------- j : float Spin of operator Returns ------- op : Qobj ``qobj`` representation of the operator. """ return jmat(j, 'x') def spin_Jy(j): """Spin-j y operator Parameters ---------- j : float Spin of operator Returns ------- op : Qobj ``qobj`` representation of the operator. """ return jmat(j, 'y') def spin_Jz(j): """Spin-j z operator Parameters ---------- j : float Spin of operator Returns ------- op : Qobj ``qobj`` representation of the operator. """ return jmat(j, 'z') def spin_Jm(j): """Spin-j annihilation operator Parameters ---------- j : float Spin of operator Returns ------- op : Qobj ``qobj`` representation of the operator. """ return jmat(j, '-') def spin_Jp(j): """Spin-j creation operator Parameters ---------- j : float Spin of operator Returns ------- op : Qobj ``qobj`` representation of the operator. """ return jmat(j, '+') def spin_J_set(j): """Set of spin-j operators (x, y, z) Parameters ---------- j : float Spin of operators Returns ------- list : list of Qobj list of ``qobj`` representating of the spin operator. """ return jmat(j) # # Pauli spin 1/2 operators: # def sigmap(): """Creation operator for Pauli spins. Examples -------- >>> sigmap() # doctest: +SKIP Quantum object: dims = [[2], [2]], \ shape = [2, 2], type = oper, isHerm = False Qobj data = [[ 0. 1.] [ 0. 0.]] """ return jmat(1 / 2., '+') def sigmam(): """Annihilation operator for Pauli spins. Examples -------- >>> sigmam() # doctest: +SKIP Quantum object: dims = [[2], [2]], \ shape = [2, 2], type = oper, isHerm = False Qobj data = [[ 0. 0.] [ 1. 0.]] """ return jmat(1 / 2., '-') def sigmax(): """Pauli spin 1/2 sigma-x operator Examples -------- >>> sigmax() # doctest: +SKIP Quantum object: dims = [[2], [2]], \ shape = [2, 2], type = oper, isHerm = False Qobj data = [[ 0. 1.] [ 1. 0.]] """ return 2.0 * jmat(1.0 / 2, 'x') def sigmay(): """Pauli spin 1/2 sigma-y operator. Examples -------- >>> sigmay() # doctest: +SKIP Quantum object: dims = [[2], [2]], \ shape = [2, 2], type = oper, isHerm = True Qobj data = [[ 0.+0.j 0.-1.j] [ 0.+1.j 0.+0.j]] """ return 2.0 * jmat(1.0 / 2, 'y') def sigmaz(): """Pauli spin 1/2 sigma-z operator. Examples -------- >>> sigmaz() # doctest: +SKIP Quantum object: dims = [[2], [2]], \ shape = [2, 2], type = oper, isHerm = True Qobj data = [[ 1. 0.] [ 0. -1.]] """ return 2.0 * jmat(1.0 / 2, 'z') # # DESTROY returns annihilation operator for N dimensional Hilbert space # out = destroy(N), N is integer value & N>0 # def destroy(N, offset=0): '''Destruction (lowering) operator. Parameters ---------- N : int Dimension of Hilbert space. offset : int (default 0) The lowest number state that is included in the finite number state representation of the operator. Returns ------- oper : qobj Qobj for lowering operator. Examples -------- >>> destroy(4) # doctest: +SKIP Quantum object: dims = [[4], [4]], \ shape = [4, 4], type = oper, isHerm = False Qobj data = [[ 0.00000000+0.j 1.00000000+0.j 0.00000000+0.j 0.00000000+0.j] [ 0.00000000+0.j 0.00000000+0.j 1.41421356+0.j 0.00000000+0.j] [ 0.00000000+0.j 0.00000000+0.j 0.00000000+0.j 1.73205081+0.j] [ 0.00000000+0.j 0.00000000+0.j 0.00000000+0.j 0.00000000+0.j]] ''' if not isinstance(N, (int, np.integer)): # raise error if N not integer raise ValueError("Hilbert space dimension must be integer value") data = np.sqrt(np.arange(offset+1, N+offset, dtype=complex)) ind = np.arange(1,N, dtype=np.int32) ptr = np.arange(N+1, dtype=np.int32) ptr[-1] = N-1 return Qobj(fast_csr_matrix((data,ind,ptr),shape=(N,N)), isherm=False) # # create returns creation operator for N dimensional Hilbert space # out = create(N), N is integer value & N>0 # def create(N, offset=0): '''Creation (raising) operator. Parameters ---------- N : int Dimension of Hilbert space. Returns ------- oper : qobj Qobj for raising operator. offset : int (default 0) The lowest number state that is included in the finite number state representation of the operator. Examples -------- >>> create(4) # doctest: +SKIP Quantum object: dims = [[4], [4]], \ shape = [4, 4], type = oper, isHerm = False Qobj data = [[ 0.00000000+0.j 0.00000000+0.j 0.00000000+0.j 0.00000000+0.j] [ 1.00000000+0.j 0.00000000+0.j 0.00000000+0.j 0.00000000+0.j] [ 0.00000000+0.j 1.41421356+0.j 0.00000000+0.j 0.00000000+0.j] [ 0.00000000+0.j 0.00000000+0.j 1.73205081+0.j 0.00000000+0.j]] ''' if not isinstance(N, (int, np.integer)): # raise error if N not integer raise ValueError("Hilbert space dimension must be integer value") qo = destroy(N, offset=offset) # create operator using destroy function return qo.dag() def _implicit_tensor_dimensions(dimensions): """ Total flattened size and operator dimensions for operator creation routines that automatically perform tensor products. Parameters ---------- dimensions : (int) or (list of int) or (list of list of int) First dimension of an operator which can create an implicit tensor product. If the type is `int`, it is promoted first to `[dimensions]`. From there, it should be one of the two-elements `dims` parameter of a `qutip.Qobj` representing an `oper` or `super`, with possible tensor products. Returns ------- size : int Dimension of backing matrix required to represent operator. dimensions : list Dimension list in the form required by ``Qobj`` creation. """ if not isinstance(dimensions, list): dimensions = [dimensions] flat = flatten(dimensions) if not all(isinstance(x, numbers.Integral) and x >= 0 for x in flat): raise ValueError("All dimensions must be integers >= 0") return np.prod(flat), [dimensions, dimensions] def qzero(dimensions): """ Zero operator. Parameters ---------- dimensions : (int) or (list of int) or (list of list of int) Dimension of Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the ``dims`` property of the new Qobj are set to this list. This can produce either `oper` or `super` depending on the passed `dimensions`. Returns ------- qzero : qobj Zero operator Qobj. """ size, dimensions = _implicit_tensor_dimensions(dimensions) # A sparse matrix with no data is equal to a zero matrix. return Qobj(fast_csr_matrix(shape=(size, size), dtype=complex), dims=dimensions, isherm=True) # # QEYE returns identity operator for a Hilbert space with dimensions dims. # a = qeye(N), N is integer or list of integers & all elements >= 0 # def qeye(dimensions): """ Identity operator. Parameters ---------- dimensions : (int) or (list of int) or (list of list of int) Dimension of Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the ``dims`` property of the new Qobj are set to this list. This can produce either `oper` or `super` depending on the passed `dimensions`. Returns ------- oper : qobj Identity operator Qobj. Examples -------- >>> qeye(3) # doctest: +SKIP Quantum object: dims = [[3], [3]], shape = (3, 3), type = oper, \ isherm = True Qobj data = [[ 1. 0. 0.] [ 0. 1. 0.] [ 0. 0. 1.]] >>> qeye([2,2]) # doctest: +SKIP Quantum object: dims = [[2, 2], [2, 2]], shape = (4, 4), type = oper, \ isherm = True Qobj data = [[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]] """ size, dimensions = _implicit_tensor_dimensions(dimensions) return Qobj(fast_identity(size), dims=dimensions, isherm=True, isunitary=True) def identity(dims): """Identity operator. Alternative name to :func:`qeye`. Parameters ---------- dimensions : (int) or (list of int) or (list of list of int) Dimension of Hilbert space. If provided as a list of ints, then the dimension is the product over this list, but the ``dims`` property of the new Qobj are set to this list. This can produce either `oper` or `super` depending on the passed `dimensions`. Returns ------- oper : qobj Identity operator Qobj. """ return qeye(dims) def position(N, offset=0): """ Position operator x=1/sqrt(2)*(a+a.dag()) Parameters ---------- N : int Number of Fock states in Hilbert space. offset : int (default 0) The lowest number state that is included in the finite number state representation of the operator. Returns ------- oper : qobj Position operator as Qobj. """ a = destroy(N, offset=offset) return 1.0 / np.sqrt(2.0) * (a + a.dag()) def momentum(N, offset=0): """ Momentum operator p=-1j/sqrt(2)*(a-a.dag()) Parameters ---------- N : int Number of Fock states in Hilbert space. offset : int (default 0) The lowest number state that is included in the finite number state representation of the operator. Returns ------- oper : qobj Momentum operator as Qobj. """ a = destroy(N, offset=offset) return -1j / np.sqrt(2.0) * (a - a.dag()) def num(N, offset=0): """Quantum object for number operator. Parameters ---------- N : int The dimension of the Hilbert space. offset : int (default 0) The lowest number state that is included in the finite number state representation of the operator. Returns ------- oper: qobj Qobj for number operator. Examples -------- >>> num(4) # doctest: +SKIP Quantum object: dims = [[4], [4]], \ shape = [4, 4], type = oper, isHerm = True Qobj data = [[0 0 0 0] [0 1 0 0] [0 0 2 0] [0 0 0 3]] """ if offset == 0: data = np.arange(1,N, dtype=complex) ind = np.arange(1,N, dtype=np.int32) ptr = np.array([0]+list(range(0,N)), dtype=np.int32) ptr[-1] = N-1 else: data = np.arange(offset, offset + N, dtype=complex) ind = np.arange(N, dtype=np.int32) ptr = np.arange(N+1,dtype=np.int32) ptr[-1] = N return Qobj(fast_csr_matrix((data,ind,ptr), shape=(N,N)), isherm=True) def squeeze(N, z, offset=0): """Single-mode Squeezing operator. Parameters ---------- N : int Dimension of hilbert space. z : float/complex Squeezing parameter. offset : int (default 0) The lowest number state that is included in the finite number state representation of the operator. Returns ------- oper : :class:`qutip.qobj.Qobj` Squeezing operator. Examples -------- >>> squeeze(4, 0.25) # doctest: +SKIP Quantum object: dims = [[4], [4]], \ shape = [4, 4], type = oper, isHerm = False Qobj data = [[ 0.98441565+0.j 0.00000000+0.j 0.17585742+0.j 0.00000000+0.j] [ 0.00000000+0.j 0.95349007+0.j 0.00000000+0.j 0.30142443+0.j] [-0.17585742+0.j 0.00000000+0.j 0.98441565+0.j 0.00000000+0.j] [ 0.00000000+0.j -0.30142443+0.j 0.00000000+0.j 0.95349007+0.j]] """ a = destroy(N, offset=offset) op = (1 / 2.0) * np.conj(z) * (a ** 2) - (1 / 2.0) * z * (a.dag()) ** 2 return op.expm() def squeezing(a1, a2, z): """Generalized squeezing operator. .. math:: S(z) = \\exp\\left(\\frac{1}{2}\\left(z^*a_1a_2 - za_1^\\dagger a_2^\\dagger\\right)\\right) Parameters ---------- a1 : :class:`qutip.qobj.Qobj` Operator 1. a2 : :class:`qutip.qobj.Qobj` Operator 2. z : float/complex Squeezing parameter. Returns ------- oper : :class:`qutip.qobj.Qobj` Squeezing operator. """ b = 0.5 * (np.conj(z) * (a1 * a2) - z * (a1.dag() * a2.dag())) return b.expm() def displace(N, alpha, offset=0): """Single-mode displacement operator. Parameters ---------- N : int Dimension of Hilbert space. alpha : float/complex Displacement amplitude. offset : int (default 0) The lowest number state that is included in the finite number state representation of the operator. Returns ------- oper : qobj Displacement operator. Examples --------- >>> displace(4,0.25) # doctest: +SKIP Quantum object: dims = [[4], [4]], \ shape = [4, 4], type = oper, isHerm = False Qobj data = [[ 0.96923323+0.j -0.24230859+0.j 0.04282883+0.j -0.00626025+0.j] [ 0.24230859+0.j 0.90866411+0.j -0.33183303+0.j 0.07418172+0.j] [ 0.04282883+0.j 0.33183303+0.j 0.84809499+0.j -0.41083747+0.j] [ 0.00626025+0.j 0.07418172+0.j 0.41083747+0.j 0.90866411+0.j]] """ a = destroy(N, offset=offset) D = (alpha * a.dag() - np.conj(alpha) * a).expm() return D def commutator(A, B, kind="normal"): """ Return the commutator of kind `kind` (normal, anti) of the two operators A and B. """ if kind == 'normal': return A * B - B * A elif kind == 'anti': return A * B + B * A else: raise TypeError("Unknown commutator kind '%s'" % kind) def qutrit_ops(): """ Operators for a three level system (qutrit). Returns ------- opers: array `array` of qutrit operators. """ from qutip.states import qutrit_basis one, two, three = qutrit_basis() sig11 = one * one.dag() sig22 = two * two.dag() sig33 = three * three.dag() sig12 = one * two.dag() sig23 = two * three.dag() sig31 = three * one.dag() return np.array([sig11, sig22, sig33, sig12, sig23, sig31], dtype=object) def qdiags(diagonals, offsets, dims=None, shape=None): """ Constructs an operator from an array of diagonals. Parameters ---------- diagonals : sequence of array_like Array of elements to place along the selected diagonals. offsets : sequence of ints Sequence for diagonals to be set: - k=0 main diagonal - k>0 kth upper diagonal - k<0 kth lower diagonal dims : list, optional Dimensions for operator shape : list, tuple, optional Shape of operator. If omitted, a square operator large enough to contain the diagonals is generated. See Also -------- scipy.sparse.diags : for usage information. Notes ----- This function requires SciPy 0.11+. Examples -------- >>> qdiags(sqrt(range(1, 4)), 1) # doctest: +SKIP Quantum object: dims = [[4], [4]], \ shape = [4, 4], type = oper, isherm = False Qobj data = [[ 0. 1. 0. 0. ] [ 0. 0. 1.41421356 0. ] [ 0. 0. 0. 1.73205081] [ 0. 0. 0. 0. ]] """ data = sp.diags(diagonals, offsets, shape, format='csr', dtype=complex) if not dims: dims = [[], []] if not shape: shape = [] return Qobj(data, dims, list(shape)) def phase(N, phi0=0): """ Single-mode Pegg-Barnett phase operator. Parameters ---------- N : int Number of basis states in Hilbert space. phi0 : float Reference phase. Returns ------- oper : qobj Phase operator with respect to reference phase. Notes ----- The Pegg-Barnett phase operator is Hermitian on a truncated Hilbert space. """ phim = phi0 + (2.0 * np.pi * np.arange(N)) / N # discrete phase angles n = np.arange(N).reshape((N, 1)) states = np.array([np.sqrt(kk) / np.sqrt(N) * np.exp(1.0j * n * kk) for kk in phim]) ops = np.array([np.outer(st, st.conj()) for st in states]) return Qobj(np.sum(ops, axis=0)) def enr_destroy(dims, excitations): """ Generate annilation operators for modes in a excitation-number-restricted state space. For example, consider a system consisting of 4 modes, each with 5 states. The total hilbert space size is 5**4 = 625. If we are only interested in states that contain up to 2 excitations, we only need to include states such as (0, 0, 0, 0) (0, 0, 0, 1) (0, 0, 0, 2) (0, 0, 1, 0) (0, 0, 1, 1) (0, 0, 2, 0) ... This function creates annihilation operators for the 4 modes that act within this state space: a1, a2, a3, a4 = enr_destroy([5, 5, 5, 5], excitations=2) From this point onwards, the annihiltion operators a1, ..., a4 can be used to setup a Hamiltonian, collapse operators and expectation-value operators, etc., following the usual pattern. Parameters ---------- dims : list A list of the dimensions of each subsystem of a composite quantum system. excitations : integer The maximum number of excitations that are to be included in the state space. Returns ------- a_ops : list of qobj A list of annihilation operators for each mode in the composite quantum system described by dims. """ from qutip.states import enr_state_dictionaries nstates, state2idx, idx2state = enr_state_dictionaries(dims, excitations) a_ops = [sp.lil_matrix((nstates, nstates), dtype=np.complex) for _ in range(len(dims))] for n1, state1 in idx2state.items(): for n2, state2 in idx2state.items(): for idx, a in enumerate(a_ops): s1 = [s for idx2, s in enumerate(state1) if idx != idx2] s2 = [s for idx2, s in enumerate(state2) if idx != idx2] if (state1[idx] == state2[idx] - 1) and (s1 == s2): a_ops[idx][n1, n2] = np.sqrt(state2[idx]) return [Qobj(a, dims=[dims, dims]) for a in a_ops] def enr_identity(dims, excitations): """ Generate the identity operator for the excitation-number restricted state space defined by the `dims` and `exciations` arguments. See the docstring for enr_fock for a more detailed description of these arguments. Parameters ---------- dims : list A list of the dimensions of each subsystem of a composite quantum system. excitations : integer The maximum number of excitations that are to be included in the state space. state : list of integers The state in the number basis representation. Returns ------- op : Qobj A Qobj instance that represent the identity operator in the exication-number-restricted state space defined by `dims` and `exciations`. """ from qutip.states import enr_state_dictionaries nstates, _, _ = enr_state_dictionaries(dims, excitations) data = sp.eye(nstates, nstates, dtype=np.complex) return Qobj(data, dims=[dims, dims]) def charge(Nmax, Nmin=None, frac = 1): """ Generate the diagonal charge operator over charge states from Nmin to Nmax. Parameters ---------- Nmax : int Maximum charge state to consider. Nmin : int (default = -Nmax) Lowest charge state to consider. frac : float (default = 1) Specify fractional charge if needed. Returns ------- C : Qobj Charge operator over [Nmin,Nmax]. Notes ----- .. versionadded:: 3.2 """ if Nmin is None: Nmin = -Nmax diag = np.arange(Nmin, Nmax+1, dtype=float) if frac != 1: diag *= frac C = sp.diags(diag, 0, format='csr', dtype=complex) return Qobj(C, isherm=True) def tunneling(N, m=1): """ Tunneling operator with elements of the form :math:`\\sum |N><N+m| + |N+m><N|`. Parameters ---------- N : int Number of basis states in Hilbert space. m : int (default = 1) Number of excitations in tunneling event. Returns ------- T : Qobj Tunneling operator. Notes ----- .. versionadded:: 3.2 """ diags = [np.ones(N-m,dtype=int),np.ones(N-m,dtype=int)] T = sp.diags(diags,[m,-m],format='csr', dtype=complex) return Qobj(T, isherm=True) # Break circular dependencies by a trailing import. # Note that we use a relative import here to deal with that # qutip.tensor is the *function* tensor, not the module. from qutip.tensor import tensor
[ 2, 770, 2393, 318, 636, 286, 2264, 40533, 47, 25, 29082, 16984, 3524, 287, 11361, 13, 198, 2, 198, 2, 220, 220, 220, 15069, 357, 66, 8, 2813, 290, 1568, 11, 3362, 360, 13, 8741, 290, 5199, 449, 13, 16053, 44038, 13, 198, 2, 220,...
2.340166
11,415
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from deepsv import deepsv from unittest.mock import patch """Tests for the deepsv module. """ # Fixture example
[ 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, 12972, 9288, 198, 6738, 2769, 21370, 1330, 2769, 21370, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 8529, ...
2.695652
69
#!/usr/bin/env python """TcEx Dependencies Command""" # standard library import os import platform import shutil import subprocess # nosec import sys from distutils.version import StrictVersion # pylint: disable=no-name-in-module from pathlib import Path from typing import List from urllib.parse import quote # third-party import typer # first-party from tcex.app_config.models.tcex_json_model import LibVersionModel from tcex.bin.bin_abc import BinABC
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 51, 66, 3109, 37947, 3976, 9455, 37811, 198, 2, 3210, 5888, 198, 11748, 28686, 198, 11748, 3859, 198, 11748, 4423, 346, 198, 11748, 850, 14681, 220, 1303, 9686, 66, 198, 11748, ...
3.255319
141
from .AST.sentence import * from .AST.expression import * from .AST.error import * import sys sys.path.append("../") from console import *
[ 6738, 764, 11262, 13, 34086, 594, 1330, 1635, 198, 6738, 764, 11262, 13, 38011, 1330, 1635, 198, 6738, 764, 11262, 13, 18224, 1330, 1635, 220, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 33295, 7203, 40720, 4943, 198, 6738, 8624, 1330,...
3.227273
44
# Copyright 2017-present Open Networking Foundation # # 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. # # Copyright 2016-present Ciena Corporation # # 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. # """ Created on 24-Oct-2012 author:s: Anil Kumar ( anilkumar.s@paxterrasolutions.com ), Raghav Kashyap( raghavkashyap@paxterrasolutions.com ) TestON is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or ( at your option ) any later version. TestON is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with TestON. If not, see <http://www.gnu.org/licenses/>. """ import logging from clicommon import * if __name__ != "__main__": import sys sys.modules[ __name__ ] = Component()
[ 198, 2, 15069, 2177, 12, 25579, 4946, 7311, 278, 5693, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
3.554806
593
#!/usr/bin/env python # -*- coding: utf-8 -*- # @author: x.huang # @date:17-8-4 import logging from pony.orm import db_session from handlers.base.base import BaseRequestHandler
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 2488, 9800, 25, 2124, 13, 13415, 648, 198, 2, 2488, 4475, 25, 1558, 12, 23, 12, 19, 198, 198, 11748, 18931,...
2.628571
70
# -*- coding: utf-8 -*- #| This file is part of cony #| #| @package Pysol python cli application #| @author <lotfio lakehal> #| @license MIT #| @version 0.1.0 #| @copyright 2019 lotfio lakehal import sys # load module function # this function loads a module by string name
[ 2, 220, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 91, 770, 2393, 318, 636, 286, 369, 88, 198, 2, 91, 198, 2, 91, 2488, 26495, 220, 220, 220, 220, 350, 893, 349, 21015, 537, 72, 3586, 198, 2, 91, 2488, 98...
2.491525
118
import torch import torch.nn as nn import torch.nn.functional as F import pytest from . import autograd_hacks # Autograd helpers, from https://gist.github.com/apaszke/226abdf867c4e9d6698bd198f3b45fb7 def jacobian(y: torch.Tensor, x: torch.Tensor, create_graph=False): jac = [] flat_y = y.reshape(-1) grad_y = torch.zeros_like(flat_y) for i in range(len(flat_y)): grad_y[i] = 1. grad_x, = torch.autograd.grad(flat_y, x, grad_y, retain_graph=True, create_graph=create_graph) jac.append(grad_x.reshape(x.shape)) grad_y[i] = 0. return torch.stack(jac).reshape(y.shape + x.shape) def hessian(y: torch.Tensor, x: torch.Tensor): return jacobian(jacobian(y, x, create_graph=True), x)
[ 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 11748, 12972, 9288, 198, 198, 6738, 764, 1330, 1960, 519, 6335, 62, 71, 4595, 628, 628, 628, 198, 2, 5231, 519, 6...
2.194118
340
import unittest import mailpile from mock import patch from mailpile.commands import Action as action from tests import MailPileUnittest if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 11748, 6920, 79, 576, 198, 6738, 15290, 1330, 8529, 198, 6738, 6920, 79, 576, 13, 9503, 1746, 1330, 7561, 355, 2223, 198, 198, 6738, 5254, 1330, 11099, 47, 576, 3118, 715, 395, 628, 628, 628, 198, 361, 115...
3.080645
62
from gym import spaces import numpy as np from scipy import interpolate import yaml from navrep.envs.navreptrainenv import NavRepTrainEnv from navrep.rosnav_models.utils.reward import RewardCalculator from navrep.rosnav_models.utils.reward import RewardCalculator
[ 6738, 11550, 1330, 9029, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 1330, 39555, 378, 198, 11748, 331, 43695, 198, 198, 6738, 6812, 7856, 13, 268, 14259, 13, 28341, 260, 457, 3201, 24330, 1330, 13244, 6207, 44077, 4834...
3.271605
81
from __future__ import annotations import sys from functools import wraps from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Optional, Tuple from pdm._types import CandidateInfo, Source from pdm.context import context from pdm.exceptions import CandidateInfoNotFound, CorruptedCacheError from pdm.models.candidates import Candidate from pdm.models.requirements import ( Requirement, filter_requirements_with_extras, parse_requirement, ) from pdm.models.specifiers import PySpecSet, SpecifierSet from pdm.utils import allow_all_wheels if TYPE_CHECKING: from pdm.models.environment import Environment
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 11748, 25064, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 6738, 19720, 1330, 41876, 62, 50084, 2751, 11, 4889, 540, 11, 360, 713, 11, 40806, 540, 11, 7343, 11, 32233, 11, 309, 29291, ...
3.437838
185
import pytest from starsessions import SessionBackend
[ 11748, 12972, 9288, 198, 198, 6738, 5788, 6202, 1330, 23575, 7282, 437, 628, 628, 198 ]
3.933333
15
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging from pyarrow import flight from sqlalchemy_dremio.exceptions import Error, NotSupportedError from sqlalchemy_dremio.flight_auth import HttpDremioClientAuthHandler from sqlalchemy_dremio.query import execute logger = logging.getLogger(__name__) paramstyle = 'qmark' def check_closed(f): """Decorator that checks if connection/cursor is closed.""" return g def check_result(f): """Decorator that checks if the cursor has results from `execute`.""" return d class Cursor(object): """Connection cursor."""
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 11748, 18931, 198, ...
3.275701
214
#!/opt/rasa/anaconda/bin/python # -*-: coding utf-8 -*- """ Snips core and nlu server. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import json import time import os from socket import error as socket_error from SnipsMqttServer import SnipsMqttServer import paho.mqtt.client as mqtt from thread_handler import ThreadHandler import sys,warnings # apt-get install sox libsox-fmt-all import sox server = SnipsTTSServer() server.start()
[ 2, 48443, 8738, 14, 8847, 64, 14, 272, 330, 13533, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 25, 19617, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 5489, 2419, 4755, 290, 299, 2290, 4382, 13, 37227, 198, 6738, 11593, 37443, 834, 13...
3.005348
187
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-08-02 17:53 from __future__ import unicode_literals from django.db import migrations, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 24, 319, 2864, 12, 2919, 12, 2999, 1596, 25, 4310, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.736842
57
from abc import ABCMeta, abstractmethod import random import json import pickle import numpy as np import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import nltk from nltk.stem import WordNetLemmatizer from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout from tensorflow.keras.optimizers import SGD from tensorflow.keras.models import load_model nltk.download('punkt', quiet=True) nltk.download('wordnet', quiet=True)
[ 6738, 450, 66, 1330, 9738, 48526, 11, 12531, 24396, 198, 198, 11748, 4738, 198, 11748, 33918, 198, 11748, 2298, 293, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 198, 418, 13, 268, 2268, 17816, 10234, 62, 8697, 47, 62, ...
2.906832
161
import discord from discord.ext import commands client = commands.Bot(command_prefix='your prefix',owner_ids = {your user id},case_insensitive=True )
[ 11748, 36446, 198, 6738, 36446, 13, 2302, 1330, 9729, 628, 198, 16366, 796, 9729, 13, 20630, 7, 21812, 62, 40290, 11639, 14108, 21231, 3256, 18403, 62, 2340, 796, 1391, 14108, 2836, 4686, 5512, 7442, 62, 1040, 18464, 28, 17821, 1267, 62...
3.731707
41
""" @brief Generate Fe55 images and associated darks and bias images according to section 5.4 of the E/O document (Dec 19, 2012 version). @author J. Chiang <jchiang@slac.stanford.edu> """ import os import numpy as np from sim_inputs import * from sim_tools import * if __name__ == '__main__': nexp = 10 exptimes = np.linspace(1, 5, nexp) nxrays = [int(x*1000) for x in exptimes] generate_Fe55_images(exptimes, nxrays, '.', 'xxx-xx')
[ 37811, 198, 31, 65, 3796, 2980, 378, 5452, 2816, 4263, 290, 3917, 288, 5558, 290, 10690, 4263, 198, 38169, 284, 2665, 642, 13, 19, 286, 262, 412, 14, 46, 3188, 357, 10707, 678, 11, 2321, 2196, 737, 198, 198, 31, 9800, 449, 13, 609...
2.6
175
import math import numpy as np import torch import torch.nn as nn from ....ops.pointnet2.pointnet2_stack import pointnet2_modules as pointnet2_stack_modules from ....ops.pointnet2.pointnet2_stack import pointnet2_utils as pointnet2_stack_utils from ....utils import common_utils from ...backbones_2d.transformer import TransformerEncoderLayer3D, TransformerEncoder from ...roi_heads.target_assigner.proposal_target_layer import ProposalTargetLayer from ...model_utils.model_nms_utils import class_agnostic_nms def bilinear_interpolate_torch(im, x, y): """ Args: im: (H, W, C) [y, x] x: (N) y: (N) Returns: """ x0 = torch.floor(x).long() x1 = x0 + 1 y0 = torch.floor(y).long() y1 = y0 + 1 x0 = torch.clamp(x0, 0, im.shape[1] - 1) x1 = torch.clamp(x1, 0, im.shape[1] - 1) y0 = torch.clamp(y0, 0, im.shape[0] - 1) y1 = torch.clamp(y1, 0, im.shape[0] - 1) Ia = im[y0, x0] Ib = im[y1, x0] Ic = im[y0, x1] Id = im[y1, x1] wa = (x1.type_as(x) - x) * (y1.type_as(y) - y) wb = (x1.type_as(x) - x) * (y - y0.type_as(y)) wc = (x - x0.type_as(x)) * (y1.type_as(y) - y) wd = (x - x0.type_as(x)) * (y - y0.type_as(y)) ans = torch.t((torch.t(Ia) * wa)) + torch.t(torch.t(Ib) * wb) + torch.t(torch.t(Ic) * wc) + torch.t(torch.t(Id) * wd) return ans def sample_points_with_roi(rois, points, sample_radius_with_roi, num_max_points_of_part=200000): """ Args: rois: (M, 7 + C) points: (N, 3) sample_radius_with_roi: num_max_points_of_part: Returns: sampled_points: (N_out, 3) """ if points.shape[0] < num_max_points_of_part: distance = (points[:, None, :] - rois[None, :, 0:3]).norm(dim=-1) min_dis, min_dis_roi_idx = distance.min(dim=-1) roi_max_dim = (rois[min_dis_roi_idx, 3:6] / 2).norm(dim=-1) point_mask = min_dis < roi_max_dim + sample_radius_with_roi else: start_idx = 0 point_mask_list = [] while start_idx < points.shape[0]: distance = (points[start_idx:start_idx + num_max_points_of_part, None, :] - rois[None, :, 0:3]).norm(dim=-1) min_dis, min_dis_roi_idx = distance.min(dim=-1) roi_max_dim = (rois[min_dis_roi_idx, 3:6] / 2).norm(dim=-1) cur_point_mask = min_dis < roi_max_dim + sample_radius_with_roi point_mask_list.append(cur_point_mask) start_idx += num_max_points_of_part point_mask = torch.cat(point_mask_list, dim=0) sampled_points = points[:1] if point_mask.sum() == 0 else points[point_mask, :] return sampled_points, point_mask def sector_fps(points, num_sampled_points, num_sectors): """ Args: points: (N, 3) num_sampled_points: int num_sectors: int Returns: sampled_points: (N_out, 3) """ sector_size = np.pi * 2 / num_sectors point_angles = torch.atan2(points[:, 1], points[:, 0]) + np.pi sector_idx = (point_angles / sector_size).floor().clamp(min=0, max=num_sectors) xyz_points_list = [] xyz_batch_cnt = [] num_sampled_points_list = [] for k in range(num_sectors): mask = (sector_idx == k) cur_num_points = mask.sum().item() if cur_num_points > 0: xyz_points_list.append(points[mask]) xyz_batch_cnt.append(cur_num_points) ratio = cur_num_points / points.shape[0] num_sampled_points_list.append( min(cur_num_points, math.ceil(ratio * num_sampled_points)) ) if len(xyz_batch_cnt) == 0: xyz_points_list.append(points) xyz_batch_cnt.append(len(points)) num_sampled_points_list.append(num_sampled_points) print(f'Warning: empty sector points detected in SectorFPS: points.shape={points.shape}') xyz = torch.cat(xyz_points_list, dim=0) xyz_batch_cnt = torch.tensor(xyz_batch_cnt, device=points.device).int() sampled_points_batch_cnt = torch.tensor(num_sampled_points_list, device=points.device).int() sampled_pt_idxs = pointnet2_stack_utils.stack_farthest_point_sample( xyz.contiguous(), xyz_batch_cnt, sampled_points_batch_cnt ).long() sampled_points = xyz[sampled_pt_idxs] return sampled_points
[ 11748, 10688, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 198, 6738, 19424, 2840, 13, 4122, 3262, 17, 13, 4122, 3262, 17, 62, 25558, 1330, 966, 3262, 17, 62, 18170, 355, 966,...
2.064066
2,076
import os
[ 11748, 28686, 628 ]
3.666667
3
#PRIMARY IMPORTS import discord, os, datetime, sys, json, traceback, logging #SECONDARY IMPORTS from apscheduler.schedulers.asyncio import AsyncIOScheduler from discord.ext import commands from data import config #LOGGING logger = logging.getLogger("ivry") logger.debug("errors.py Started")
[ 2, 4805, 3955, 13153, 30023, 33002, 201, 198, 201, 198, 11748, 36446, 11, 28686, 11, 4818, 8079, 11, 25064, 11, 33918, 11, 12854, 1891, 11, 18931, 201, 198, 201, 198, 2, 23683, 18672, 13153, 30023, 33002, 201, 198, 201, 198, 6738, 257...
2.758929
112
## Problem 5: Extracting Data from JSON # Example: http://py4e-data.dr-chuck.net/comments_42.json # data consists of a number of names and comment counts in JSON # { # comments: [ # { # name: "Matthias" # count: 97 # }, # { # name: "Geomer" # count: 97 # } # ... # ] # } import urllib.request, urllib.parse, urllib.error import json import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE # prompt for a URL url = input('Enter URL: ') # handle for data data_handle = urllib.request.urlopen(url, context=ctx) # read the JSON data from that URL using urllib # decode UTF 8 byte array to Unicode string data = data_handle.read().decode() # parse string containing json into structured object (-> JSON object / Python dictionary) # data_js is dictionary data_js = json.loads(data) # compute the sum of the numbers in the file number_sum = 0 # parse and extract the comment counts from the JSON data, # data_js['comments'] is list of dictionaries # print(data_js['comments']) for user in data_js['comments']: print('Name:', user['name']) print('Count:', user['count']) number_sum = number_sum + user['count'] # Example: Total count 2553 print('Total Count:', number_sum)
[ 2235, 20647, 642, 25, 29677, 278, 6060, 422, 19449, 198, 2, 17934, 25, 2638, 1378, 9078, 19, 68, 12, 7890, 13, 7109, 12, 354, 1347, 13, 3262, 14, 15944, 62, 3682, 13, 17752, 198, 2, 1366, 10874, 286, 257, 1271, 286, 3891, 290, 291...
2.815846
467
from ariadne import make_executable_schema, load_schema_from_path from ariadne.asgi import GraphQL from resolvers import query, skill, person, eye_color, mutation # import schema from GraphQL file type_defs = load_schema_from_path("./schema.gql") schema = make_executable_schema( type_defs, query, skill, person, eye_color, mutation ) app = GraphQL(schema, debug=True)
[ 6738, 257, 21244, 710, 1330, 787, 62, 18558, 18187, 62, 15952, 2611, 11, 3440, 62, 15952, 2611, 62, 6738, 62, 6978, 198, 6738, 257, 21244, 710, 13, 292, 12397, 1330, 29681, 9711, 198, 6738, 581, 349, 690, 1330, 12405, 11, 5032, 11, ...
2.892308
130
import importlib import time from pathlib import Path import os import sys print("Import plugins ..") import_plugins() print("Import app ..") import modules.app.App as piTomation app: piTomation.App print("Start app ..") app = piTomation.App() #try: # app = piTomation.App() #except Exception as ex: # print(ex) # exit() try: while not app.is_disposed: time.sleep(1) except Exception as ex: print(ex)
[ 11748, 1330, 8019, 198, 11748, 640, 198, 6738, 3108, 8019, 1330, 10644, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 4798, 7203, 20939, 20652, 11485, 4943, 198, 11748, 62, 37390, 3419, 198, 198, 4798, 7203, 20939, 598, 11485, 4943, 198...
2.551724
174
""" Functions support other modules. """ import uuid def check_response(response, key=None): """CHeck the api response. Make sure the status call is successful and the response have specific key. Return: class: `Response <Response>` """ code = response.status_code if not 200 <= code < 300: raise Exception('[Decanter Core response Error] Request Error') if key is not None and key not in response.json(): raise KeyError('[Decanter Core response Error] No key value') return response def gen_id(type_, name): """Generate a random UUID if name isn't given. Returns: string """ if name is None: rand_id = uuid.uuid4() rand_id = str(rand_id)[:8] name = type_ + '_' + rand_id return name def isnotebook(): """Return True if SDK is running on Jupyter Notebook.""" try: shell = get_ipython().__class__.__name__ if shell == 'ZMQInteractiveShell': return True # Jupyter notebook or qtconsole if shell == 'TerminalInteractiveShell': return False # Terminal running IPython return False except NameError: return False
[ 37811, 198, 24629, 2733, 1104, 584, 13103, 13, 198, 37811, 198, 11748, 334, 27112, 628, 198, 4299, 2198, 62, 26209, 7, 26209, 11, 1994, 28, 14202, 2599, 198, 220, 220, 220, 37227, 34, 1544, 694, 262, 40391, 2882, 13, 628, 220, 220, ...
2.592275
466
import numpy as np if __name__ == '__main__': main()
[ 11748, 299, 32152, 355, 45941, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198 ]
2.4
25
import tensorflow as tf import numpy as np with tf.variable_scope("student"): input_label = tf.placeholder(dtype=tf.float32, shape=[10, 10], name="label") input_image = tf.placeholder(dtype=tf.float32, shape=[10, 224, 224, 3], name="input") conv1 = tf.layers.conv2d(inputs=input_image, filters=64, kernel_size=[3, 3], padding='same') conv2 = tf.layers.conv2d(conv1, filters=64, kernel_size=[3, 3], padding='same') conv3 = tf.layers.conv2d(conv2, filters=64, kernel_size=[3, 3], padding='same') shape = int(np.prod(conv3.get_shape()[1:])) flat = tf.reshape(conv3, [-1, shape]) fc1 = tf.layers.dense(flat, units=100) fc2 = tf.layers.dense(fc1, units=10, name="logit") probability = tf.nn.softmax(fc2) loss = tf.losses.softmax_cross_entropy(input_label, fc2) print(input_label) image = np.ones(shape=[10, 224, 224, 3]) with tf.Session() as sess: init = tf.global_variables_initializer() sess.run(init) saver = tf.train.Saver() saver.save(sess, "./student/student") print(sess.run(probability, feed_dict={input_image: image}))
[ 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 299, 32152, 355, 45941, 628, 198, 4480, 48700, 13, 45286, 62, 29982, 7203, 50139, 1, 2599, 198, 220, 220, 220, 5128, 62, 18242, 796, 48700, 13, 5372, 13829, 7, 67, 4906, 28, 27110, 13,...
2.37744
461
import scipy.stats import numpy as np def f_test(sample_x, sample_y, larger_varx_alt): """ Computes the F-value and corresponding p-value for a pair of samples and alternative hypothesis. Parameters ---------- sample_x : list A random sample x1,...,xnx. Let its (underlying) variance be ox^2 and its sample variance Sx^2. sample_y : list A random sample y1,...,yny. Let its (underlying) variance be oy^2 and its sample variance Sy^2. larger_varx_alt : bool True if alternative hypothesis is ox^2 > oy^2. False if ox^2 < oy^2. Returns ------- f_value : float Sx^2 / Sy^2 as defined in 'A Quick, Compact, Two-Sample Dispersion Test: Count Five'. p_value : float Let F be the F-distribution with nx, ny df. 1 - P(F < f_value) if larger_varx_alt = True, P(F < f_value) otherwise. More extreme F = Sx^2 / Sy^2 values for alternative ox^2 > oy^2 are to the right. More extreme F values for ox^2 < oy^2 are to the left. """ # calculate unbiased sample variances (n-1 in the denominator) sample_var_x = np.var(sample_x, ddof=1) sample_var_y = np.var(sample_y, ddof=1) f_value = sample_var_x/sample_var_y nx = len(sample_x) ny = len(sample_y) # compute P(F < f_value) with nx-1, ny-1 df cdf = scipy.stats.f.cdf(f_value, nx-1, ny-1) # More extreme f_value = Sx^2 / Sy^2 values for alternative ox^2 > oy^2. ox^2 being even bigger would be represented by larger quotient Sx^2 / Sy^2. # More extreme f_value for ox^2 < oy^2 are to the left. ox^2 being even smaller would be represented by smaller quotient. p_value = 1 - cdf if larger_varx_alt else cdf return f_value, p_value def f1_test(sample_x, sample_y, larger_varx_alt): """ Computes the F1-value as defined in 'Fixing the F Test for Equal Variances' and corresponding p-value for a pair of samples and alternative hypothesis. Parameters ---------- sample_x : list A random sample x1,...,xnx. Let its (underlying) variance be ox^2 and its sample variance Sx^2. sample_y : list A random sample y1,...,yny. Let its (underlying) variance be oy^2 and its sample variance Sy^2. larger_varx_alt : bool True if alternative hypothesis is ox^2 > oy^2. False if ox^2 < oy^2. Returns ------- p_value : float Let F be the F-distribution with rx, ry df as specified in equation (1) of 'Fixing the F Test for Equal Variances'. 1 - P(F < f_value) if larger_varx_alt = True, P(F < f_value) otherwise. """ # calculate unbiased sample variances (n-1 in the denominator) sample_var_x = np.var(sample_x, ddof=1) sample_var_y = np.var(sample_y, ddof=1) f_value = sample_var_x/sample_var_y nx = len(sample_x) ny = len(sample_y) xmean = np.mean(sample_x) ymean = np.mean(sample_y) # compute moment, variance below equatio (1) of Shoemaker paper fourth_moment = (np.sum((sample_x - xmean)**4) + np.sum((sample_y - ymean)**4))/(nx + ny) pooled_var = ((nx-1)*sample_var_x + (ny-1)*sample_var_y)/(nx + ny) # see equation (1) of Shoemaker paper rx = 2*nx / ((fourth_moment/pooled_var**2) - ((nx - 3)/(nx - 1))) ry = 2*ny / ((fourth_moment/pooled_var**2) - ((ny - 3)/(ny - 1))) # compute P(F < f_value) with rx-1, ry-1 df cdf = scipy.stats.f.cdf(f_value, rx-1, ry-1) # More extreme f_value = Sx^2 / Sy^2 values for alternative ox^2 > oy^2. ox^2 being even bigger would be represented by larger quotient Sx^2 / Sy^2. # More extreme f_value for ox^2 < oy^2 are to the left. ox^2 being even smaller would be represented by smaller quotient. p_value = 1 - cdf if larger_varx_alt else cdf return p_value def count_five(sample_x, sample_y, center): """ Computes the extreme counts for samples x and y as defined in 'A Quick, Compact, Two-Sample Dispersion Test: Count Five'. Parameters ---------- sample_x : list A random sample x1,...,xn. sample_y : list A random sample y1,...,ym. center : str Whether to use 'mean' or 'median' for centering. Returns ------- extreme_count_x : int C_x computed with centering mu being sample mean if center = 'mean' and sample median if center = 'median' as defined in equation (1) of 'A Quick, Compact, Two-Sample Dispersion Test: Count Five'. extreme_count_y : int C_y defined analogously to C_x above. Raises ------ ValueError If center is neither 'mean' or 'median'. """ if center not in {'mean', 'median'}: raise ValueError('Invalid center %s' % (center)) if center == 'mean': centering_x = np.mean(sample_x) centering_y = np.mean(sample_y) else: centering_x = np.median(sample_x) centering_y = np.median(sample_y) # compute absolute deviations from centering for x, y samples abs_dev_x = np.abs(np.array(sample_x) - centering_x) abs_dev_y = np.abs(np.array(sample_y) - centering_y) # count number of X deviations greater than max Y deviation and vice versa # see equation (1) of Count Five paper extreme_count_x = np.sum(np.where(abs_dev_x > np.max(abs_dev_y), 1, 0)) extreme_count_y = np.sum(np.where(abs_dev_y > np.max(abs_dev_x), 1, 0)) return extreme_count_x, extreme_count_y
[ 11748, 629, 541, 88, 13, 34242, 198, 11748, 299, 32152, 355, 45941, 628, 198, 4299, 277, 62, 9288, 7, 39873, 62, 87, 11, 6291, 62, 88, 11, 4025, 62, 7785, 87, 62, 2501, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 3082, ...
2.489559
2,155
import os, subprocess def compile_core(comp, scilib): """ ATTENTION, NOT FINISHED """ subprocess.call(("make pawpy_%s"%comp).split()) def compile_core(comp, scilib): """ ATTENTION, NOT FINISHED """ subprocess.call("make hfc".split())
[ 11748, 28686, 11, 850, 14681, 198, 198, 4299, 17632, 62, 7295, 7, 5589, 11, 629, 22282, 2599, 198, 197, 37811, 198, 197, 17139, 45589, 11, 5626, 33642, 18422, 1961, 198, 197, 37811, 198, 197, 7266, 14681, 13, 13345, 7, 7203, 15883, 41...
2.641304
92
""" Example usage of Finnhub socket API. """ from __future__ import print_function # Py2 compat import websocket from finnhub_python.utils import get_finnhub_api_key tick_file = 'raw_ticks.txt' token = get_finnhub_api_key() SYMBOLS = [ "AAPL", "SPY", "VXX", "BINANCE:ETHUSDT", "BINANCE:BTCUSDT" ] if __name__ == "__main__": websocket.enableTrace(True) ws = websocket.WebSocketApp("wss://ws.finnhub.io?token=" + token, on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever()
[ 37811, 198, 16281, 8748, 286, 15368, 40140, 17802, 7824, 13, 198, 37811, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 1303, 9485, 17, 8330, 198, 11748, 2639, 5459, 198, 6738, 957, 77, 40140, 62, 29412, 13, 26791, 1330, 651, ...
1.932551
341
""" Pycovjson - Command line interface Author: rileywilliams Version: 0.1.0 """ import argparse from pycovjson.write import Writer from pycovjson.read_netcdf import NetCDFReader as Reader def main(): """ Command line interface for pycovjson - Converts Scientific Data Formats into CovJSON and saves to disk. :argument -i: Input file path. :argument -o: Output file name. :argument -t: Use Tiling. :argument -v: Which variable to populate coverage with. :argument -s: [tile shape]: Tile shape. :argument -n: Use interactive mode. :argument -u: MongoDB URL """ parser = argparse.ArgumentParser( description='Convert Scientific Data Formats into CovJSON.') parser.add_argument('-i', '--input', dest='inputfile', help='Name of input file', required=True) parser.add_argument('-o', '--output', dest='outputfile', help='Name and location of output file', default='coverage.covjson') parser.add_argument('-t', '--tiled', action='store_true', help='Apply tiling') parser.add_argument('-s', '--shape', nargs='+', help='Tile shape, list', type=int) parser.add_argument('-v', dest='variable', help='Variable to populate coverage with', required=True) parser.add_argument('-n', '--interactive', action='store_true', help='Enter interactive mode') parser.add_argument('-u', '--endpoint_url', dest='endpoint_url', nargs=1, help='MongoDB endpoint for CovJSON persistence') args = parser.parse_args() inputfile = args.inputfile outputfile = args.outputfile variable = args.variable tiled = args.tiled tile_shape = args.shape interactive = args.interactive endpoint_url = args.endpoint_url if interactive: axis = input('Which Axis?', Reader.get_axis(variable)) if tiled and len(tile_shape) == 0: reader = Reader(inputfile) shape_list = reader.get_shape(variable) dims = reader.get_dimensions(variable) print(list(zip(dims, shape_list))) tile_shape = input( 'Enter the shape tile shape as a list of comma separated integers') tile_shape = tile_shape.split(',') tile_shape = list(map(int, tile_shape)) print(tile_shape) if outputfile == None: outputfile = outputfile.default Writer(outputfile, inputfile, [variable], tiled=tiled, tile_shape=tile_shape, endpoint_url=endpoint_url).write() if __name__ == '__main__': main()
[ 37811, 198, 20519, 66, 709, 17752, 532, 9455, 1627, 7071, 198, 13838, 25, 374, 9618, 10594, 1789, 82, 198, 14815, 25, 657, 13, 16, 13, 15, 198, 37811, 198, 11748, 1822, 29572, 198, 198, 6738, 12972, 66, 709, 17752, 13, 13564, 1330, ...
2.572573
999
import discord from discord.ext import commands from .utils import checks from .utils.dataIO import dataIO from __main__ import send_cmd_help from __main__ import settings from datetime import datetime from random import choice from random import sample from copy import deepcopy from collections import namedtuple, defaultdict import os import logging import aiohttp import asyncio import time from time import sleep client = discord.Client() def check_folders(): if not os.path.exists("data/duels"): print("Creating data/duels folder...") os.mkdir("data/duels")
[ 11748, 36446, 201, 198, 6738, 36446, 13, 2302, 1330, 9729, 201, 198, 6738, 764, 26791, 1330, 8794, 201, 198, 6738, 764, 26791, 13, 7890, 9399, 1330, 1366, 9399, 201, 198, 6738, 11593, 12417, 834, 1330, 3758, 62, 28758, 62, 16794, 201, ...
3.085427
199
"""Citizens model.""" # Django from django.db import models from django.contrib.auth.models import AbstractUser from django.core.validators import RegexValidator # models from paranuara.companies.models import Company # PostgreSQL fields from django.contrib.postgres.fields import JSONField # Utilities from paranuara.utils.models import ParanuaraModel
[ 37811, 34, 34100, 2746, 526, 15931, 198, 198, 2, 37770, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 27741, 12982, 198, 6738, 42625, 14208, 13, 7295, 13, 12102, 2024,...
3.485437
103
# -*- coding: utf-8 -*- from cobra.utils import normalize
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 22843, 430, 13, 26791, 1330, 3487, 1096, 198 ]
2.458333
24
import pygame from chess.board import Board from .variable_declaration import black_piece, white_piece, position_piece, board_square_size
[ 11748, 12972, 6057, 198, 6738, 19780, 13, 3526, 1330, 5926, 198, 6738, 764, 45286, 62, 32446, 10186, 1330, 2042, 62, 12239, 11, 2330, 62, 12239, 11, 2292, 62, 12239, 11, 3096, 62, 23415, 62, 7857, 628 ]
3.861111
36
import numpy as np from kivygames.games import Game import kivygames.games.noughtsandcrosses.c as c
[ 11748, 299, 32152, 355, 45941, 198, 198, 6738, 479, 452, 88, 19966, 13, 19966, 1330, 3776, 198, 198, 11748, 479, 452, 88, 19966, 13, 19966, 13, 77, 619, 912, 392, 19692, 274, 13, 66, 355, 269, 628, 198 ]
2.736842
38
#! /usr/bin/env python import argparse import json import time import urllib.error import urllib.request if __name__ == "__main__": main()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 1822, 29572, 198, 11748, 33918, 198, 11748, 640, 198, 11748, 2956, 297, 571, 13, 18224, 198, 11748, 2956, 297, 571, 13, 25927, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366,...
2.754717
53
import functools import re import asyncio from io import BytesIO from discord.ext import commands import discord from Utils import canvas import random
[ 11748, 1257, 310, 10141, 198, 11748, 302, 198, 11748, 30351, 952, 198, 6738, 33245, 1330, 2750, 4879, 9399, 198, 6738, 36446, 13, 2302, 1330, 9729, 198, 11748, 36446, 198, 6738, 7273, 4487, 1330, 21978, 198, 11748, 4738, 628 ]
4.026316
38
# -*- coding: utf-8 -*- from __future__ import unicode_literals from appconf import AppConf from django.conf import settings # noqa
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 598, 10414, 1330, 2034, 18546, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 220, 1303, 645, ...
3
45
import awkward as ak from coffea.nanoevents.methods import vector import pytest ATOL = 1e-8
[ 11748, 13006, 355, 47594, 198, 6738, 763, 16658, 64, 13, 77, 5733, 31534, 13, 24396, 82, 1330, 15879, 198, 11748, 12972, 9288, 628, 198, 1404, 3535, 796, 352, 68, 12, 23, 628, 628, 628 ]
2.911765
34
import roadrunner import teplugins as tel i = 0 #for i in range(100): try: noisePlugin = tel.Plugin ("tel_add_noise") print noisePlugin.listOfProperties() # Create a roadrunner instance rr = roadrunner.RoadRunner() rr.load("sbml_test_0001.xml") # Generate data data = rr.simulate(0, 10, 511) # Want 512 points # Get the dataseries from roadrunner d = tel.getDataSeries (data) # Assign the dataseries to the plugin inputdata noisePlugin.InputData = d # Set parameter for the 'size' of the noise noisePlugin.Sigma = 3.e-6 # Add the noise noisePlugin.execute() # Get the data to plot noisePlugin.InputData.plot() # tel.show() d.writeDataSeries ("testData2.dat") d.readDataSeries ("testData2.dat") print "done" print i except Exception as e: print 'Problem: ' + `e`
[ 11748, 2975, 16737, 198, 11748, 573, 37390, 355, 13632, 198, 198, 72, 796, 657, 198, 2, 1640, 1312, 287, 2837, 7, 3064, 2599, 198, 28311, 25, 198, 220, 220, 220, 7838, 37233, 796, 13632, 13, 37233, 5855, 37524, 62, 2860, 62, 3919, 7...
2.472527
364
from renpy import store
[ 6738, 8851, 9078, 1330, 3650, 628 ]
4.166667
6
import logging from ncservice.ncDeviceOps.nc_device_ops import NcDeviceOps from ncservice.ncDeviceOps.task_report import TaskReport from ncservice.ncDeviceOps.threaded.base_thread_class import BaseThreadClass logger = logging.getLogger('main.{}'.format(__name__)) extra = {'signature': '---SIGNATURE-NOT-SET---'}
[ 11748, 18931, 198, 6738, 299, 66, 15271, 13, 10782, 24728, 41472, 13, 10782, 62, 25202, 62, 2840, 1330, 399, 66, 24728, 41472, 198, 6738, 299, 66, 15271, 13, 10782, 24728, 41472, 13, 35943, 62, 13116, 1330, 15941, 19100, 198, 6738, 299,...
3.088235
102
""" This program visualizes nested for loops by printing number 0 through 3 and then 0 through 3 for the nested loop. """ for i in range(4): print("Outer for loop: " + str(i)) for j in range(4): print(" Inner for loop: " + str(j))
[ 37811, 201, 198, 1212, 1430, 5874, 4340, 28376, 329, 23607, 416, 13570, 1271, 657, 832, 513, 201, 198, 392, 788, 657, 832, 513, 329, 262, 28376, 9052, 13, 201, 198, 37811, 201, 198, 201, 198, 1640, 1312, 287, 2837, 7, 19, 2599, 201,...
2.6875
96
from collections import defaultdict import graphene import pytest from django.core.exceptions import ValidationError from ....shipping.error_codes import ShippingErrorCode from ..mutations import BaseChannelListingMutation
[ 6738, 17268, 1330, 4277, 11600, 198, 198, 11748, 42463, 198, 11748, 12972, 9288, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 3254, 24765, 12331, 198, 198, 6738, 19424, 1477, 4501, 13, 18224, 62, 40148, 1330, 24147, 12331, 10...
4.087719
57
# -*- coding: utf-8 -*- # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Authors: Luc LEGER / Cooprative ARTEFACTS <artefacts.lle@gmail.com> import requests from django.conf import settings from django.contrib import messages from django.core.exceptions import PermissionDenied from django.http import HttpResponseRedirect, Http404 from django.utils.translation import gettext as _ from requests.exceptions import RequestException from rest_framework import status from francoralite.apps.francoralite_front.errors import APPLICATION_ERRORS from .views.related import ( write_fond_related, write_mission_related, write_collection_related, write_item_related) HTTP_ERRORS = { status.HTTP_400_BAD_REQUEST: APPLICATION_ERRORS['HTTP_API_400'], status.HTTP_401_UNAUTHORIZED: APPLICATION_ERRORS['HTTP_API_401'], status.HTTP_403_FORBIDDEN: APPLICATION_ERRORS['HTTP_API_403'], status.HTTP_404_NOT_FOUND: APPLICATION_ERRORS['HTTP_API_404'], status.HTTP_409_CONFLICT: APPLICATION_ERRORS['HTTP_API_409'], } PROBLEM_NAMES = [ "legal_rights", "recording_context", "location_gis", ] def get_token_header(request): """ TODO: renseigner """ auth_token = request.session.get('oidc_access_token') if auth_token: return {'Authorization': 'Bearer ' + auth_token} else: return {} def check_status_code(status_code, allowed_codes=(status.HTTP_200_OK,)): """ TODO: renseigner """ if status_code == status.HTTP_403_FORBIDDEN: raise PermissionDenied(_('Accs interdit.')) if status_code == status.HTTP_404_NOT_FOUND: raise Http404(_('Cette fiche nexiste pas.')) if status_code == status.HTTP_409_CONFLICT: raise UserMessageError(_('Une fiche avec ce code existe dj.')) if status.HTTP_400_BAD_REQUEST <= status_code < status.HTTP_500_INTERNAL_SERVER_ERROR: raise RequestException() if status_code not in allowed_codes: raise Exception(HTTP_ERRORS[status_code]) def handle_message_from_exception(request, exception): """ TODO: renseigner """ if isinstance(exception, UserMessageError): messages.add_message(request, messages.ERROR, exception) elif exception is not None: messages.add_message(request, messages.ERROR, _('Une erreur indtermine est survenue.')) def request_api(endpoint): """ TODO: renseigner """ response = requests.get(settings.FRONT_HOST_URL + endpoint) check_status_code(response.status_code) return response.json() def post(entity, form_entity, request, *args, **kwargs): """ TODO: renseigner """ form = form_entity(request.POST, request.FILES) entity_api = entity entity_url = entity # Processing the problem names entities if entity in PROBLEM_NAMES: entity_api = entity.replace('_', '') # Processing URL for Mission entity if entity == 'fond': entity_url = 'institution/' + kwargs['id_institution'] \ + '/' + entity # Processing URL for Mission entity if entity == 'mission': entity_url = 'institution/' + kwargs['id_institution'] \ + '/fond/' + kwargs['id_fond']\ + '/' + entity # Processing URL for Collection entity if entity == 'collection': entity_url = 'institution/' + kwargs['id_institution'] \ + '/fond/' + kwargs['id_fond']\ + '/mission/' + kwargs['id_mission'] \ + '/' + entity # Processing URL for Item entity if entity == 'item': entity_url = 'institution/' + kwargs['id_institution'] \ + '/fond/' + kwargs['id_fond']\ + '/mission/' + kwargs['id_mission'] \ + '/collection/' + kwargs['id_collection'] \ + '/' + entity # Problem with old Telemeta fields/entities if form.is_valid(): if entity == 'item': # Concatenate domains form.cleaned_data['domain'] = ''.join(form.cleaned_data['domain']) # Remove the 'file' entry : if not, there some bugs del form.cleaned_data['file'] try: post_api(settings.FRONT_HOST_URL + '/api/' + entity_api, data=form.cleaned_data, request=request, entity=entity) if entity == 'fond': return HttpResponseRedirect( '/institution/' + str(form.cleaned_data['institution'])) # Previous page ( not an edit page ... ) if len(request.session["referers"]) > 1: try: for referer in request.session["referers"]: if 'add' not in referer.split('/'): return HttpResponseRedirect(referer) except Exception: return HttpResponseRedirect('/' + entity) return HttpResponseRedirect('/' + entity) except RequestException as e: handle_message_from_exception(request, e) return HttpResponseRedirect('/' + entity_url + '/add') return HttpResponseRedirect('/' + entity_url + '/add') def post_api(endpoint, data, request, entity): """ TODO: renseigner """ headers = get_token_header(request=request) response = requests.post( endpoint, data=data, files=request.FILES, headers=headers, ) check_status_code(response.status_code, allowed_codes=(status.HTTP_200_OK, status.HTTP_201_CREATED)) entity_json = response.json() if entity == "fond": write_fond_related(entity_json, request, headers) if entity == "mission": write_mission_related(entity_json, request, headers) if entity == "collection": write_collection_related(entity_json, request, headers) if entity == "item": write_item_related(entity_json, request, headers) return entity_json def patch(entity, form_entity, request, *args, **kwargs): """ TODO: renseigner """ form = form_entity(request.POST) if entity == 'item': form.fields['file'].required = False id = kwargs.get('id') entity_api = entity if entity in PROBLEM_NAMES: entity_api = entity.replace('_', '') if form.is_valid(): if entity == "collection": form.cleaned_data['recorded_from_year'] = \ form.data['recorded_from_year'] form.cleaned_data['recorded_to_year'] = \ form.data['recorded_to_year'] if form.cleaned_data['year_published'] is None: form.cleaned_data['year_published'] = '' if entity == "item": # Concatenate domains form.cleaned_data['domain'] = ''.join(form.cleaned_data['domain']) try: response = patch_api( settings.FRONT_HOST_URL + '/api/' + entity_api + '/' + str(id), data=form.cleaned_data, request=request, entity=entity ) if(response.status_code != status.HTTP_200_OK): return HttpResponseRedirect('/' + entity + '/edit/' + str(id)) # Previous page ( not an edit page ... ) if len(request.session["referers"]) > 1: for referer in request.session["referers"]: if 'edit' not in referer.split('/'): return HttpResponseRedirect(referer) return HttpResponseRedirect('/' + entity) except RequestException as e: handle_message_from_exception(request, e) return HttpResponseRedirect('/' + entity + '/edit/' + str(id)) return HttpResponseRedirect('/' + entity + '/edit/' + str(id)) def patch_api(endpoint, data, request, entity): """ TODO: renseigner """ response = requests.patch( endpoint, data=data, headers=get_token_header(request=request), ) check_status_code(response.status_code) entity_json = response.json() if entity == "fond": write_fond_related( entity_json, request, headers=get_token_header(request=request), ) if entity == "mission": write_mission_related( entity_json, request, headers=get_token_header(request=request), ) if entity == "collection": write_collection_related( entity_json, request, headers=get_token_header(request=request), ) if entity == "item": write_item_related( entity_json, request, headers=get_token_header(request=request), ) return response def delete(entity, request, *args, **kwargs): """ TODO: renseigner """ id = kwargs.get('id') entity_api = entity if entity in PROBLEM_NAMES: entity_api = entity.replace('_', '') try: delete_api( settings.FRONT_HOST_URL + '/api/' + entity_api + '/' + str(id), request=request, ) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) except RequestException as e: handle_message_from_exception(request, e) return HttpResponseRedirect('/' + entity) def delete_api(endpoint, request): """ TODO: renseigner """ response = requests.delete( endpoint, headers=get_token_header(request=request), ) check_status_code(response.status_code) return response
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 921, 815, 423, 2722, 257, 4866, 286, 262, 22961, 6708, 3529, 3611, 5094, 13789, 198, 2, 1863, 351, 428, 1430, 13, 220, 1002, 407, 11, 766, 1279, 4023, 1378, 2503, ...
2.240092
4,365
# Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. import socket from twisted.persisted import styles from twisted.internet.base import BaseConnector from twisted.internet import defer, interfaces, error from twisted.python import failure from abstract import ConnectedSocket from ops import ConnectExOp from util import StateEventMachineType from zope.interface import implements
[ 2, 15069, 357, 66, 8, 5878, 12, 15724, 40006, 24936, 46779, 13, 198, 2, 4091, 38559, 24290, 329, 3307, 13, 628, 198, 11748, 17802, 198, 198, 6738, 19074, 13, 19276, 6347, 1330, 12186, 198, 6738, 19074, 13, 37675, 13, 8692, 1330, 7308,...
4.446809
94
import unittest from pypika import Table from pypika.analytics import Count from pypika.dialects import MSSQLQuery from pypika.utils import QueryException
[ 11748, 555, 715, 395, 198, 198, 6738, 279, 4464, 9232, 1330, 8655, 198, 6738, 279, 4464, 9232, 13, 38200, 14094, 1330, 2764, 198, 6738, 279, 4464, 9232, 13, 38969, 478, 82, 1330, 337, 5432, 9711, 20746, 198, 6738, 279, 4464, 9232, 13,...
3.340426
47
import cvxpy as cvx import numpy as np from collections import namedtuple from metric import metric, cd import pandas as pd import sys from helper import make_dataset
[ 11748, 269, 85, 87, 9078, 355, 269, 85, 87, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, 6738, 18663, 1330, 18663, 11, 22927, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 25064, 198, 6738, 319...
2.80303
66
import unittest import os import subprocess import base
[ 11748, 555, 715, 395, 198, 11748, 28686, 198, 11748, 850, 14681, 198, 198, 11748, 2779, 628 ]
3.625
16
"""Queue implementation using circularly linked list for storage."""
[ 37811, 34991, 7822, 1262, 18620, 306, 6692, 1351, 329, 6143, 526, 15931, 198 ]
5.307692
13
# -*- encoding: utf-8 """ Various helper constants and functions. """ import os import re import sys import time import traceback def curr_time(): """Current time in %H:%M""" return time.strftime("%H:%M") def curr_time_sec(): """Current time in %H:%M:%S""" return time.strftime("%H:%M:%S") def get_error_info(): """Return info about last error.""" msg = "{0}\n{1}".format(str(traceback.format_exc()), str(sys.exc_info())) return msg def get_string_between(start, stop, s): """Search string for a substring between two delimeters. False if not found.""" i1 = s.find(start) if i1 == -1: return False s = s[i1 + len(start):] i2 = s.find(stop) if i2 == -1: return False s = s[:i2] return s def whitespace(line): """Return index of first non whitespace character on a line.""" i = 0 for char in line: if char != " ": break i += 1 return i def parse_path(path): """Parse a relative path and return full directory and filename as a tuple.""" if path[:2] == "~" + os.sep: p = os.path.expanduser("~") path = os.path.join(p+os.sep, path[2:]) ab = os.path.abspath(path) parts = os.path.split(ab) return parts
[ 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 198, 37811, 198, 40009, 31904, 38491, 290, 5499, 13, 198, 37811, 198, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 12854, 1891, 628, 198, 4299, 1090, ...
2.326606
545
""" :mod:`meshes` -- Discretization =============================== Everything related to meshes appropriate for the multigrid solver. """ # Copyright 2018-2020 The emg3d Developers. # # This file is part of emg3d. # # 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 # # https://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 numpy as np from copy import deepcopy from scipy import optimize __all__ = ['TensorMesh', 'get_hx_h0', 'get_cell_numbers', 'get_stretched_h', 'get_domain', 'get_hx'] def get_hx_h0(freq, res, domain, fixed=0., possible_nx=None, min_width=None, pps=3, alpha=None, max_domain=100000., raise_error=True, verb=1, return_info=False): r"""Return cell widths and origin for given parameters. Returns cell widths for the provided frequency, resistivity, domain extent, and other parameters using a flexible amount of cells. See input parameters for more details. A maximum of three hard/fixed boundaries can be provided (one of which is the grid center). The minimum cell width is calculated through :math:`\delta/\rm{pps}`, where the skin depth is given by :math:`\delta = 503.3 \sqrt{\rho/f}`, and the parameter `pps` stands for 'points-per-skindepth'. The minimum cell width can be restricted with the parameter `min_width`. The actual calculation domain adds a buffer zone around the (survey) domain. The thickness of the buffer is six times the skin depth. The field is basically zero after two wavelengths. A wavelength is :math:`2\pi\delta`, hence roughly 6 times the skin depth. Taking a factor 6 gives therefore almost two wavelengths, as the field travels to the boundary and back. The actual buffer thickness can be steered with the `res` parameter. One has to take into account that the air is very resistive, which has to be considered not just in the vertical direction, but also in the horizontal directions, as the airwave will bounce back from the sides otherwise. In the marine case this issue reduces with increasing water depth. See Also -------- get_stretched_h : Get `hx` for a fixed number `nx` and within a fixed domain. Parameters ---------- freq : float Frequency (Hz) to calculate the skin depth. The skin depth is a concept defined in the frequency domain. If a negative frequency is provided, it is assumed that the calculation is carried out in the Laplace domain. To calculate the skin depth, the value of `freq` is then multiplied by :math:`-2\pi`, to simulate the closest frequency-equivalent. res : float or list Resistivity (Ohm m) to calculate the skin depth. The skin depth is used to calculate the minimum cell width and the boundary thicknesses. Up to three resistivities can be provided: - float: Same resistivity for everything; - [min_width, boundaries]; - [min_width, left boundary, right boundary]. domain : list Contains the survey-domain limits [min, max]. The actual calculation domain consists of this domain plus a buffer zone around it, which depends on frequency and resistivity. fixed : list, optional Fixed boundaries, one, two, or maximum three values. The grid is centered around the first value. Hence it is the center location with the smallest cell. Two more fixed boundaries can be added, at most one on each side of the first one. Default is 0. possible_nx : list, optional List of possible numbers of cells. See :func:`get_cell_numbers`. Default is ``get_cell_numbers(500, 5, 3)``, which corresponds to [16, 24, 32, 40, 48, 64, 80, 96, 128, 160, 192, 256, 320, 384]. min_width : float, list or None, optional Minimum cell width restriction: - None : No restriction; - float : Fixed to this value, ignoring skin depth and `pps`. - list [min, max] : Lower and upper bounds. Default is None. pps : int, optional Points per skindepth; minimum cell width is calculated via `dmin = skindepth/pps`. Default = 3. alpha : list, optional Maximum alpha and step size to find a good alpha. The first value is the maximum alpha of the survey domain, the second value is the maximum alpha for the buffer zone, and the third value is the step size. Default = [1, 1.5, .01], hence no stretching within the survey domain and a maximum stretching of 1.5 in the buffer zone; step size is 0.01. max_domain : float, optional Maximum calculation domain from fixed[0] (usually source position). Default is 100,000. raise_error : bool, optional If True, an error is raised if no suitable grid is found. Otherwise it just prints a message and returns None's. Default is True. verb : int, optional Verbosity, 0 or 1. Default = 1. return_info : bool If True, a dictionary is returned with some grid info (min and max cell width and alpha). Returns ------- hx : ndarray Cell widths of mesh. x0 : float Origin of the mesh. info : dict Dictionary with mesh info; only if ``return_info=True``. Keys: - `dmin`: Minimum cell width; - `dmax`: Maximum cell width; - `amin`: Minimum alpha; - `amax`: Maximum alpha. """ # Get variables with default lists: if alpha is None: alpha = [1, 1.5, 0.01] if possible_nx is None: possible_nx = get_cell_numbers(500, 5, 3) # Cast resistivity value(s). res = np.array(res, ndmin=1) if res.size == 1: res_arr = np.array([res[0], res[0], res[0]]) elif res.size == 2: res_arr = np.array([res[0], res[1], res[1]]) else: res_arr = np.array([res[0], res[1], res[2]]) # Cast and check fixed. fixed = np.array(fixed, ndmin=1) if fixed.size > 2: # Check length. if fixed.size > 3: print("\n* ERROR :: Maximum three fixed boundaries permitted.\n" f" Provided: {fixed.size}.") raise ValueError("Wrong input for fixed") # Sort second and third, so it doesn't matter how it was provided. fixed = np.array([fixed[0], max(fixed[1:]), min(fixed[1:])]) # Check side. if np.sign(np.diff(fixed[:2])) == np.sign(np.diff(fixed[::2])): print("\n* ERROR :: 2nd and 3rd fixed boundaries have to be " "left and right of the first one.\n " f"Provided: [{fixed[0]}, {fixed[1]}, {fixed[2]}]") raise ValueError("Wrong input for fixed") # Calculate skin depth. skind = 503.3*np.sqrt(res_arr/abs(freq)) if freq < 0: # For Laplace-domain calculations. skind /= np.sqrt(2*np.pi) # Minimum cell width. dmin = skind[0]/pps if min_width is not None: # Respect user input. min_width = np.array(min_width, ndmin=1) if min_width.size == 1: dmin = min_width else: dmin = np.clip(dmin, *min_width) # Survey domain; contains all sources and receivers. domain = np.array(domain, dtype=float) # Calculation domain; big enough to avoid boundary effects. # To avoid boundary effects we want the signal to travel two wavelengths # from the source to the boundary and back to the receiver. # => 2*pi*sd ~ 6.3*sd = one wavelength => signal is ~ 0.2 %. # Two wavelengths we can safely assume it is zero. # # The air does not follow the concept of skin depth, as it is a wave rather # than diffusion. For this is the factor `max_domain`, which restricts # the domain in each direction to this value from the center. # (a) Source to edges of domain. dist_in_domain = abs(domain - fixed[0]) # (b) Two wavelengths. two_lambda = skind[1:]*4*np.pi # (c) Required buffer, additional to domain. dist_buff = np.max([np.zeros(2), (two_lambda - dist_in_domain)/2], axis=0) # (d) Add buffer to domain. calc_domain = np.array([domain[0]-dist_buff[0], domain[1]+dist_buff[1]]) # (e) Restrict total domain to max_domain. calc_domain[0] = max(calc_domain[0], fixed[0]-max_domain) calc_domain[1] = min(calc_domain[1], fixed[0]+max_domain) # Initiate flag if terminated. finished = False # Initiate alpha variables for survey and calculation domains. sa, ca = 1.0, 1.0 # Loop over possible cell numbers from small to big. for nx in np.unique(possible_nx): # Loop over possible alphas for domain. for sa in np.arange(1.0, alpha[0]+alpha[2]/2, alpha[2]): # Get current stretched grid cell sizes. thxl = dmin*sa**np.arange(nx) # Left of origin. thxr = dmin*sa**np.arange(nx) # Right of origin. # 0. Adjust stretching for fixed boundaries. if fixed.size > 1: # Move mesh to first fixed boundary. t_nx = np.r_[fixed[0], fixed[0]+np.cumsum(thxr)] ii = np.argmin(abs(t_nx-fixed[1])) thxr *= abs(fixed[1]-fixed[0])/np.sum(thxr[:ii]) if fixed.size > 2: # Move mesh to second fixed boundary. t_nx = np.r_[fixed[0], fixed[0]-np.cumsum(thxl)] ii = np.argmin(abs(t_nx-fixed[2])) thxl *= abs(fixed[2]-fixed[0])/np.sum(thxl[:ii]) # 1. Fill from center to left domain. nl = np.sum((fixed[0]-np.cumsum(thxl)) > domain[0])+1 # 2. Fill from center to right domain. nr = np.sum((fixed[0]+np.cumsum(thxr)) < domain[1])+1 # 3. Get remaining number of cells and check termination criteria. nsdc = nl+nr # Number of domain cells. nx_remain = nx-nsdc # Not good, try next. if nx_remain <= 0: continue # Create the current hx-array. hx = np.r_[thxl[:nl][::-1], thxr[:nr]] hxo = np.r_[thxl[:nl][::-1], thxr[:nr]] # Get actual domain: asurv_domain = [fixed[0]-np.sum(thxl[:nl]), fixed[0]+np.sum(thxr[:nr])] x0 = float(fixed[0]-np.sum(thxl[:nl])) # Get actual stretching (differs in case of fixed layers). sa_adj = np.max([hx[1:]/hx[:-1], hx[:-1]/hx[1:]]) # Loop over possible alphas for calc_domain. for ca in np.arange(sa, alpha[1]+alpha[2]/2, alpha[2]): # 4. Fill to left calc_domain. thxl = hx[0]*ca**np.arange(1, nx_remain+1) nl = np.sum((asurv_domain[0]-np.cumsum(thxl)) > calc_domain[0])+1 # 5. Fill to right calc_domain. thxr = hx[-1]*ca**np.arange(1, nx_remain+1) nr = np.sum((asurv_domain[1]+np.cumsum(thxr)) < calc_domain[1])+1 # 6. Get remaining number of cells and check termination # criteria. ncdc = nl+nr # Number of calc_domain cells. nx_remain2 = nx-nsdc-ncdc if nx_remain2 < 0: # Not good, try next. continue # Create hx-array. nl += int(np.floor(nx_remain2/2)) # If uneven, add one cell nr += int(np.ceil(nx_remain2/2)) # more on the right. hx = np.r_[thxl[:nl][::-1], hx, thxr[:nr]] # Calculate origin. x0 = float(asurv_domain[0]-np.sum(thxl[:nl])) # Mark it as finished and break out of the loop. finished = True break if finished: break if finished: break # Check finished and print info about found grid. if not finished: # Throw message if no solution was found. print("\n* ERROR :: No suitable grid found; relax your criteria.\n") if raise_error: raise ArithmeticError("No grid found!") else: hx, x0 = None, None elif verb > 0: print(f" Skin depth ", end="") if res.size == 1: print(f" [m] : {skind[0]:.0f}") elif res.size == 2: print(f"(m/l-r) [m] : {skind[0]:.0f} / {skind[1]:.0f}") else: print(f"(m/l/r) [m] : {skind[0]:.0f} / {skind[1]:.0f} / " f"{skind[2]:.0f}") print(f" Survey domain [m] : {domain[0]:.0f} - " f"{domain[1]:.0f}") print(f" Calculation domain [m] : {calc_domain[0]:.0f} - " f"{calc_domain[1]:.0f}") print(f" Final extent [m] : {x0:.0f} - " f"{x0+np.sum(hx):.0f}") extstr = f" Min/max cell width [m] : {min(hx):.0f} / " alstr = f" Alpha survey" nrstr = " Number of cells " if not np.isclose(sa, sa_adj): sastr = f"{sa:.3f} ({sa_adj:.3f})" else: sastr = f"{sa:.3f}" print(extstr+f"{max(hxo):.0f} / {max(hx):.0f}") print(alstr+f"/calc : {sastr} / {ca:.3f}") print(nrstr+f"(s/c/r) : {nx} ({nsdc}/{ncdc}/{nx_remain2})") print() if return_info: if not fixed.size > 1: sa_adj = sa info = {'dmin': dmin, 'dmax': np.nanmax(hx), 'amin': np.nanmin([ca, sa, sa_adj]), 'amax': np.nanmax([ca, sa, sa_adj])} return hx, x0, info else: return hx, x0 def get_cell_numbers(max_nr, max_prime=5, min_div=3): r"""Returns 'good' cell numbers for the multigrid method. 'Good' cell numbers are numbers which can be divided by 2 as many times as possible. At the end there will be a low prime number. The function adds all numbers :math:`p 2^n \leq M` for :math:`p={2, 3, ..., p_\text{max}}` and :math:`n={n_\text{min}, n_\text{min}+1, ..., \infty}`; :math:`M, p_\text{max}, n_\text{min}` correspond to `max_nr`, `max_prime`, and `min_div`, respectively. Parameters ---------- max_nr : int Maximum number of cells. max_prime : int Highest permitted prime number p for p*2^n. {2, 3, 5, 7} are good upper limits in order to avoid too big lowest grids in the multigrid method. Default is 5. min_div : int Minimum times the number can be divided by two. Default is 3. Returns ------- numbers : array Array containing all possible cell numbers from lowest to highest. """ # Primes till 20. primes = np.array([2, 3, 5, 7, 11, 13, 17, 19]) # Sanity check; 19 is already ridiculously high. if max_prime > primes[-1]: print(f"* ERROR :: Highest prime is {max_prime}, " "please use a value < 20.") raise ValueError("Highest prime too high") # Restrict to max_prime. primes = primes[primes <= max_prime] # Get possible values. # Currently restricted to prime*2**30 (for prime=2 => 1,073,741,824 cells). numbers = primes[:, None]*2**np.arange(min_div, 30) # Get unique values. numbers = np.unique(numbers) # Restrict to max_nr and return. return numbers[numbers <= max_nr] def get_stretched_h(min_width, domain, nx, x0=0, x1=None, resp_domain=False): """Return cell widths for a stretched grid within the domain. Returns `nx` cell widths within `domain`, where the minimum cell width is `min_width`. The cells are not stretched within `x0` and `x1`, and outside uses a power-law stretching. The actual stretching factor and the number of cells left and right of `x0` and `x1` are find in a minimization process. The domain is not completely respected. The starting point of the domain is, but the endpoint of the domain might slightly shift (this is more likely the case for small `nx`, for big `nx` the shift should be small). The new endpoint can be obtained with ``domain[0]+np.sum(hx)``. If you want the domain to be respected absolutely, set ``resp_domain=True``. However, be aware that this will introduce one stretch-factor which is different from the other stretch factors, to accommodate the restriction. This one-off factor is between the left- and right-side of `x0`, or, if `x1` is provided, just after `x1`. See Also -------- get_hx_x0 : Get `hx` and `x0` for a flexible number of `nx` with given bounds. Parameters ---------- min_width : float Minimum cell width. If x1 is provided, the actual minimum cell width might be smaller than min_width. domain : list [start, end] of model domain. nx : int Number of cells. x0 : float Center of the grid. `x0` is restricted to `domain`. Default is 0. x1 : float If provided, then no stretching is applied between `x0` and `x1`. The non-stretched part starts at `x0` and stops at the first possible location at or after `x1`. `x1` is restricted to `domain`. This will min_width so that an integer number of cells fit within x0 and x1. resp_domain : bool If False (default), then the domain-end might shift slightly to assure that the same stretching factor is applied throughout. If set to True, however, the domain is respected absolutely. This will introduce one stretch-factor which is different from the other stretch factors, to accommodate the restriction. This one-off factor is between the left- and right-side of `x0`, or, if `x1` is provided, just after `x1`. Returns ------- hx : ndarray Cell widths of mesh. """ # Cast to arrays domain = np.array(domain, dtype=float) x0 = np.array(x0, dtype=float) x0 = np.clip(x0, *domain) # Restrict to model domain min_width = np.array(min_width, dtype=float) if x1 is not None: x1 = np.array(x1, dtype=float) x1 = np.clip(x1, *domain) # Restrict to model domain # If x1 is provided (a part is not stretched) if x1 is not None: # Store original values xlim_orig = domain.copy() nx_orig = int(nx) x0_orig = x0.copy() h_min_orig = min_width.copy() # Get number of non-stretched cells n_nos = int(np.ceil((x1-x0)/min_width)) # Re-calculate min_width to fit with x0-x1-limits: min_width = (x1-x0)/n_nos # Subtract one cell, because the standard scheme provides one # min_width-cell. n_nos -= 1 # Reset x0, because the first min_width comes from normal scheme x0 += min_width # Reset xmax for normal scheme domain[1] -= n_nos*min_width # Reset nx for normal scheme nx -= n_nos # If there are not enough points reset to standard procedure. The limit # of five is arbitrary. However, nx should be much bigger than five # anyways, otherwise stretched grid doesn't make sense. if nx <= 5: print("Warning :: Not enough points for non-stretched part," "ignoring therefore `x1`.") domain = xlim_orig nx = nx_orig x0 = x0_orig x1 = None min_width = h_min_orig # Get stretching factor (a = 1+alpha). if min_width == 0 or min_width > np.diff(domain)/nx: # If min_width is bigger than the domain-extent divided by nx, no # stretching is required at all. alpha = 0 else: # Wrap _get_dx into a minimization function to call with fsolve. def find_alpha(alpha, min_width, args): """Find alpha such that min(hx) = min_width.""" return min(get_hx(alpha, *args))/min_width-1 # Search for best alpha, must be at least 0 args = (domain, nx, x0) alpha = max(0, optimize.fsolve(find_alpha, 0.02, (min_width, args))) # With alpha get actual cell spacing with `resp_domain` to respect the # users decision. hx = get_hx(alpha, domain, nx, x0, resp_domain) # Add the non-stretched center if x1 is provided if x1 is not None: hx = np.r_[hx[: np.argmin(hx)], np.ones(n_nos)*min_width, hx[np.argmin(hx):]] # Print warning min_width could not be respected. if abs(hx.min() - min_width) > 0.1: print(f"Warning :: Minimum cell width ({np.round(hx.min(), 2)} m) is " "below `min_width`, because `nx` is too big for `domain`.") return hx def get_domain(x0=0, freq=1, res=0.3, limits=None, min_width=None, fact_min=0.2, fact_neg=5, fact_pos=None): r"""Get domain extent and minimum cell width as a function of skin depth. Returns the extent of the calculation domain and the minimum cell width as a multiple of the skin depth, with possible user restrictions on minimum calculation domain and range of possible minimum cell widths. .. math:: \delta &= 503.3 \sqrt{\frac{\rho}{f}} , \\ x_\text{start} &= x_0-k_\text{neg}\delta , \\ x_\text{end} &= x_0+k_\text{pos}\delta , \\ h_\text{min} &= k_\text{min} \delta . Parameters ---------- x0 : float Center of the calculation domain. Normally the source location. Default is 0. freq : float Frequency (Hz) to calculate the skin depth. The skin depth is a concept defined in the frequency domain. If a negative frequency is provided, it is assumed that the calculation is carried out in the Laplace domain. To calculate the skin depth, the value of `freq` is then multiplied by :math:`-2\pi`, to simulate the closest frequency-equivalent. Default is 1 Hz. res : float, optional Resistivity (Ohm m) to calculate skin depth. Default is 0.3 Ohm m (sea water). limits : None or list [start, end] of model domain. This extent represents the minimum extent of the domain. The domain is therefore only adjusted if it has to reach outside of [start, end]. Default is None. min_width : None, float, or list of two floats Minimum cell width is calculated as a function of skin depth: fact_min*sd. If `min_width` is a float, this is used. If a list of two values [min, max] are provided, they are used to restrain min_width. Default is None. fact_min, fact_neg, fact_pos : floats The skin depth is multiplied with these factors to estimate: - Minimum cell width (`fact_min`, default 0.2) - Domain-start (`fact_neg`, default 5), and - Domain-end (`fact_pos`, defaults to `fact_neg`). Returns ------- h_min : float Minimum cell width. domain : list Start- and end-points of calculation domain. """ # Set fact_pos to fact_neg if not provided. if fact_pos is None: fact_pos = fact_neg # Calculate the skin depth. skind = 503.3*np.sqrt(res/abs(freq)) if freq < 0: # For Laplace-domain calculations. skind /= np.sqrt(2*np.pi) # Estimate minimum cell width. h_min = fact_min*skind if min_width is not None: # Respect user input. if np.array(min_width).size == 1: h_min = min_width else: h_min = np.clip(h_min, *min_width) # Estimate calculation domain. domain = [x0-fact_neg*skind, x0+fact_pos*skind] if limits is not None: # Respect user input. domain = [min(limits[0], domain[0]), max(limits[1], domain[1])] return h_min, domain def get_hx(alpha, domain, nx, x0, resp_domain=True): r"""Return cell widths for given input. Find the number of cells left and right of `x0`, `nl` and `nr` respectively, for the provided alpha. For this, we solve .. math:: \frac{x_\text{max}-x_0}{x_0-x_\text{min}} = \frac{a^{nr}-1}{a^{nl}-1} where :math:`a = 1+\alpha`. Parameters ---------- alpha : float Stretching factor `a` is given by ``a=1+alpha``. domain : list [start, end] of model domain. nx : int Number of cells. x0 : float Center of the grid. `x0` is restricted to `domain`. resp_domain : bool If False (default), then the domain-end might shift slightly to assure that the same stretching factor is applied throughout. If set to True, however, the domain is respected absolutely. This will introduce one stretch-factor which is different from the other stretch factors, to accommodate the restriction. This one-off factor is between the left- and right-side of `x0`, or, if `x1` is provided, just after `x1`. Returns ------- hx : ndarray Cell widths of mesh. """ if alpha <= 0.: # If alpha <= 0: equal spacing (no stretching at all) hx = np.ones(nx)*np.diff(np.squeeze(domain))/nx else: # Get stretched hx a = alpha+1 # Get hx depending if x0 is on the domain boundary or not. if np.isclose(x0, domain[0]) or np.isclose(x0, domain[1]): # Get al a's alr = np.diff(domain)*alpha/(a**nx-1)*a**np.arange(nx) if x0 == domain[1]: alr = alr[::-1] # Calculate differences hx = alr*np.diff(domain)/sum(alr) else: # Find number of elements left and right by solving: # (xmax-x0)/(x0-xmin) = a**nr-1/(a**nl-1) nr = np.arange(2, nx+1) er = (domain[1]-x0)/(x0-domain[0]) - (a**nr[::-1]-1)/(a**nr-1) nl = np.argmin(abs(np.floor(er)))+1 nr = nx-nl # Get all a's al = a**np.arange(nl-1, -1, -1) ar = a**np.arange(1, nr+1) # Calculate differences if resp_domain: # This version honours domain[0] and domain[1], but to achieve # this it introduces one stretch-factor which is different from # all the others between al to ar. hx = np.r_[al*(x0-domain[0])/sum(al), ar*(domain[1]-x0)/sum(ar)] else: # This version moves domain[1], but each stretch-factor is # exactly the same. fact = (x0-domain[0])/sum(al) # Take distance from al. hx = np.r_[al, ar]*fact # Note: this hx is equivalent as providing the following h # to TensorMesh: # h = [(min_width, nl-1, -a), (min_width, n_nos+1), # (min_width, nr, a)] return hx
[ 37811, 198, 198, 25, 4666, 25, 63, 6880, 956, 63, 1377, 8444, 1186, 1634, 198, 4770, 25609, 18604, 198, 198, 19693, 3519, 284, 48754, 5035, 329, 262, 1963, 3692, 312, 1540, 332, 13, 198, 198, 37811, 198, 2, 15069, 2864, 12, 42334, 3...
2.313914
11,844
#! /usr/bin/python2 # -*- coding: utf-8 -*- """ Clock function to take running time following Segmatch. """ # BSD 3-Clause License # # Copyright (c) 2019, FPAI # Copyright (c) 2019, SeriouslyHAO # Copyright (c) 2019, xcj2019 # Copyright (c) 2019, Leonfirst # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder 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 HOLDER 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. import datetime
[ 2, 0, 1220, 14629, 14, 8800, 14, 29412, 17, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 44758, 2163, 284, 1011, 2491, 640, 1708, 31220, 15699, 13, 198, 37811, 198, 2, 347, 10305, 513, 12, 2601, ...
3.467836
513
from office365.runtime.client_object_collection import ClientObjectCollection from office365.runtime.resource_path_service_operation import ResourcePathServiceOperation from office365.sharepoint.view import View
[ 6738, 2607, 24760, 13, 43282, 13, 16366, 62, 15252, 62, 43681, 1330, 20985, 10267, 36307, 198, 6738, 2607, 24760, 13, 43282, 13, 31092, 62, 6978, 62, 15271, 62, 27184, 1330, 20857, 15235, 16177, 32180, 198, 6738, 2607, 24760, 13, 20077, ...
4.630435
46
from common_src.lib.model.post import Post from common_src.lib.model.source import Source from common_src.scrapers.abstract_scraper import make_soup, remove_dups, now SOURCE_CODE = "second_extinction" WEBSITE = "https://www.secondextinctiongame.com/news" ALT_IMAGE = 'https://www.secondextinctiongame.com/static/242486b363d867dc483deb6d7038dde1/d8255/se_screenshot_5.jpg' FILENAME = "../resources/data/second_extinction.txt"
[ 6738, 2219, 62, 10677, 13, 8019, 13, 19849, 13, 7353, 1330, 2947, 198, 6738, 2219, 62, 10677, 13, 8019, 13, 19849, 13, 10459, 1330, 8090, 198, 6738, 2219, 62, 10677, 13, 1416, 2416, 364, 13, 397, 8709, 62, 1416, 38545, 1330, 787, 62...
2.74359
156
# # alexnet.py # # Author(s): # Matteo Spallanzani <spmatteo@iis.ee.ethz.ch> # # Copyright (c) 2020-2021 ETH Zurich. # # 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 torch import torch.nn as nn
[ 2, 220, 198, 2, 257, 2588, 3262, 13, 9078, 198, 2, 220, 198, 2, 6434, 7, 82, 2599, 198, 2, 38789, 78, 1338, 439, 35410, 3216, 1279, 2777, 6759, 660, 78, 31, 72, 271, 13, 1453, 13, 2788, 89, 13, 354, 29, 198, 2, 220, 198, 2, ...
3.268519
216
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 11, 15720, 602, 628 ]
2.891892
37
#!/bin/python3 # Libraries import sys import array import textwrap # Variable Declaration madlib_selection = "example.txt" madlib_array = array.array('i') copy_state = False user_filler = "" new_madlib = [] if len(sys.argv) != 1: print(len(sys.argv)) if sys.argv[1] == "-": print("This program takes the path to a madlib as an argument. Showing default now.") ## TODO: Add input validation, i.e. make sure the input is actully text. else: ## TODO: Add pipe as input option. madlib_selection = sys.argv[1] with open(madlib_selection, 'r') as madlib: read_madlib = madlib.read() for i in range(read_madlib.count("#")//2): first = read_madlib.index("#") second = read_madlib.index("#", first+1) replacement = input("Please give me " + read_madlib[first+1:second] + ":") new_madlib = read_madlib[0:first] + replacement + read_madlib[second+1:] read_madlib = new_madlib print("\n\n\n") print(textwrap.fill(read_madlib, drop_whitespace=False, replace_whitespace=False))
[ 2, 48443, 8800, 14, 29412, 18, 198, 198, 2, 46267, 198, 11748, 25064, 198, 11748, 7177, 198, 11748, 2420, 37150, 198, 198, 2, 35748, 24720, 198, 9937, 8019, 62, 49283, 796, 366, 20688, 13, 14116, 1, 198, 9937, 8019, 62, 18747, 796, ...
2.466513
433
import pytest from django.utils.timezone import now from pretix.base.models import Device, Event, Organizer, Team, User from pretix.base.models.devices import generate_api_token
[ 11748, 12972, 9288, 198, 6738, 42625, 14208, 13, 26791, 13, 2435, 11340, 1330, 783, 198, 198, 6738, 2181, 844, 13, 8692, 13, 27530, 1330, 16232, 11, 8558, 11, 7221, 7509, 11, 4816, 11, 11787, 198, 6738, 2181, 844, 13, 8692, 13, 27530,...
3.418182
55
import numpy as np from PIL import Image, ImageOps, ImageEnhance import albumentations as A # ndarray: H x W x C # ----------------------------------- Blur ------------------------------------------- # ----------------------------------- Noise ------------------------------------------- # ---------------------------------- Distortion --------------------------------------- # ----------------------------------- Histogram ---------------------------------------- # ------------------------------------- Removal ------------------------------------------ # ------------------------------------------- Augmix ------------------------------------------- # Reference: https://www.kaggle.com/haqishen/augmix-based-on-albumentations def int_parameter(level, maxval): """Helper function to scale `val` between 0 and maxval . Args: level: Level of the operation that will be between [0, `PARAMETER_MAX`]. maxval: Maximum value that the operation can have. This will be scaled to level/PARAMETER_MAX. Returns: An int that results from scaling `maxval` according to `level`. """ return int(level * maxval / 10) def float_parameter(level, maxval): """Helper function to scale `val` between 0 and maxval. Args: level: Level of the operation that will be between [0, `PARAMETER_MAX`]. maxval: Maximum value that the operation can have. This will be scaled to level/PARAMETER_MAX. Returns: A float that results from scaling `maxval` according to `level`. """ return float(level) * maxval / 10. def sample_level(n): return np.random.uniform(low=0.1, high=n) def autocontrast(pil_img, _): return ImageOps.autocontrast(pil_img) def equalize(pil_img, _): return ImageOps.equalize(pil_img) def posterize(pil_img, level): level = int_parameter(sample_level(level), 4) return ImageOps.posterize(pil_img, 4 - level) def rotate(pil_img, level): degrees = int_parameter(sample_level(level), 30) if np.random.uniform() > 0.5: degrees = -degrees return pil_img.rotate(degrees, resample=Image.BILINEAR) def solarize(pil_img, level): level = int_parameter(sample_level(level), 256) return ImageOps.solarize(pil_img, 256 - level) def shear_x(pil_img, level): level = float_parameter(sample_level(level), 0.3) if np.random.uniform() > 0.5: level = -level return pil_img.transform(pil_img.size, Image.AFFINE, (1, level, 0, 0, 1, 0), resample=Image.BILINEAR) def shear_y(pil_img, level): level = float_parameter(sample_level(level), 0.3) if np.random.uniform() > 0.5: level = -level return pil_img.transform(pil_img.size, Image.AFFINE, (1, 0, 0, level, 1, 0), resample=Image.BILINEAR) def translate_x(pil_img, level): level = int_parameter(sample_level(level), pil_img.size[0] / 3) if np.random.random() > 0.5: level = -level return pil_img.transform(pil_img.size, Image.AFFINE, (1, 0, level, 0, 1, 0), resample=Image.BILINEAR) def translate_y(pil_img, level): level = int_parameter(sample_level(level), pil_img.size[0] / 3) if np.random.random() > 0.5: level = -level return pil_img.transform(pil_img.size, Image.AFFINE, (1, 0, 0, 0, 1, level), resample=Image.BILINEAR) # operation that overlaps with ImageNet-C's test set # operation that overlaps with ImageNet-C's test set # operation that overlaps with ImageNet-C's test set # operation that overlaps with ImageNet-C's test set def normalize(image): """Normalize input image channel-wise to zero mean and unit variance.""" return image - 127 def augment_and_mix(image, severity=3, width=3, depth=-1, alpha=1.): """Perform AugMix augmentations and compute mixture. Args: image: Raw input image as float32 np.ndarray of shape (h, w, c) severity: Severity of underlying augmentation operators (between 1 to 10). width: Width of augmentation chain depth: Depth of augmentation chain. -1 enables stochastic depth uniformly from [1, 3] alpha: Probability coefficient for Beta and Dirichlet distributions. Returns: mixed: Augmented and mixed image. """ augmentations = [ autocontrast, equalize, posterize, rotate, solarize, shear_x, shear_y, translate_x, translate_y ] ws = np.float32(np.random.dirichlet([alpha] * width)) m = np.float32(np.random.beta(alpha, alpha)) mix = np.zeros_like(image).astype(np.float32) for i in range(width): image_aug = image.copy() depth = depth if depth > 0 else np.random.randint(1, 4) for _ in range(depth): op = np.random.choice(augmentations) image_aug = apply_op(image_aug, op, severity) # Preprocessing commutes since all coefficients are convex mix += ws[i] * image_aug # mix += ws[i] * normalize(image_aug) mixed = (1 - m) * image + m * mix # mixed = (1 - m) * normalize(image) + m * mix return mixed
[ 11748, 299, 32152, 355, 45941, 198, 6738, 350, 4146, 1330, 7412, 11, 7412, 41472, 11, 7412, 35476, 590, 198, 11748, 435, 65, 1713, 602, 355, 317, 198, 198, 2, 299, 67, 18747, 25, 367, 2124, 370, 2124, 327, 628, 198, 198, 2, 20368, ...
2.597022
2,015
# -*- coding: utf-8 -*- import bleach import json def strip_html(unclean): """Sanitize a string, removing (as opposed to escaping) HTML tags :param unclean: A string to be stripped of HTML tags :return: stripped string :rtype: str """ return bleach.clean(unclean, strip=True, tags=[], attributes=[], styles=[]) def clean_tag(data): """Format as a valid Tag :param data: A string to be cleaned :return: cleaned string :rtype: str """ # TODO: make this a method of Tag? return escape_html(data).replace('"', '&quot;').replace("'", '&#39') def is_iterable_but_not_string(obj): """Return True if ``obj`` is an iterable object that isn't a string.""" return (hasattr(obj, '__iter__') and not hasattr(obj, 'strip')) def escape_html(data): """Escape HTML characters in data. :param data: A string, dict, or list to clean of HTML characters :return: A cleaned object :rtype: str or list or dict """ if isinstance(data, dict): return { key: escape_html(value) for (key, value) in data.iteritems() } if is_iterable_but_not_string(data): return [ escape_html(value) for value in data ] if isinstance(data, basestring): return bleach.clean(data) return data def assert_clean(data): """Ensure that data is cleaned :raise: AssertionError """ return escape_html(data) # TODO: Remove safe_unescape_html when mako html safe comes in def safe_unescape_html(value): """ Return data without html escape characters. :param value: A string, dict, or list :return: A string or list or dict without html escape characters """ safe_characters = { '&amp;': '&', '&lt;': '<', '&gt;': '>', } if isinstance(value, dict): return { key: safe_unescape_html(value) for (key, value) in value.iteritems() } if is_iterable_but_not_string(value): return [ safe_unescape_html(each) for each in value ] if isinstance(value, basestring): for escape_sequence, character in safe_characters.items(): value = value.replace(escape_sequence, character) return value return value def safe_json(value): """ Dump a string to JSON in a manner that can be used for JS strings in mako templates. Providing additional forward-slash escaping to prevent injection of closing markup in strings. See: http://benalpert.com/2012/08/03/preventing-xss-json.html :param value: A string to be converted :return: A JSON-formatted string that explicitly escapes forward slashes when needed """ return json.dumps(value).replace('</', '<\\/') # Fix injection of closing markup in strings
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 49024, 198, 11748, 33918, 628, 198, 4299, 10283, 62, 6494, 7, 403, 27773, 2599, 198, 220, 220, 220, 37227, 15017, 270, 1096, 257, 4731, 11, 10829, 357, 292, 6886,...
2.568733
1,113
import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.tensorboard import SummaryWriter from torch.utils import data from torch import optim import torchvision.models as models from torch.autograd import Variable import torchvision as tv import random import math import time from datetime import datetime import os import argparse import subprocess from util.LFUtil import * import numpy as np from networks.LFMNet import LFMNet if __name__ == '__main__': main()
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 28034, 13, 26791, 13, 83, 22854, 3526, 1330, 21293, 34379, 198, 6738, 28034, 13, 26791, 1330, 1366, 198, 6738, 28034...
3.582734
139
"""Utilities""" import pandas as pd import numpy as np from attrdict import AttrDict import yaml def average_predictions(cv_predictions, n_splits, num_samples = 153164, num_labels = 6): """Average k-fold predictions stored in a dict""" preds = np.zeros((num_samples, num_labels)) for preds_i in cv_predictions: preds += preds_i preds /= n_splits return preds def geom_average_predictions(cv_predictions, n_splits, num_samples = 153164, num_labels = 6): """Average k-fold predictions stored in a dict""" preds = np.ones((num_samples, num_labels)) for preds_i in cv_predictions: preds *= preds_i preds = preds **(1/n_splits) return preds
[ 37811, 18274, 2410, 37811, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 708, 4372, 713, 1330, 3460, 81, 35, 713, 198, 11748, 331, 43695, 198, 198, 4299, 2811, 62, 28764, 9278, 7, 33967, 62, 2876...
2.469751
281
import airflow from airflow.models import DAG from airflow.operators.dummy_operator import DummyOperator args = { 'owner': 'Mike', 'start_date': airflow.utils.dates.days_ago(2), } dag = DAG( dag_id='exercise1', default_args=args, schedule_interval=None ) t1 = DummyOperator(task_id='task1', dag=dag) t2 = DummyOperator(task_id='task2', dag=dag) t3 = DummyOperator(task_id='task3', dag=dag) t4 = DummyOperator(task_id='task4', dag=dag) t5 = DummyOperator(task_id='task5', dag=dag) t1 >> t2 >> [t3,t4] >> t5
[ 11748, 45771, 198, 6738, 45771, 13, 27530, 1330, 360, 4760, 198, 6738, 45771, 13, 3575, 2024, 13, 67, 13513, 62, 46616, 1330, 360, 13513, 18843, 1352, 198, 198, 22046, 796, 1391, 198, 220, 220, 220, 705, 18403, 10354, 705, 16073, 3256, ...
2.294372
231
# -*- coding: utf-8 -*- """ Created on Tue Feb 27 10:54:25 2018 @author: jsgosselin """ # ---- Standard Library Imports from itertools import product import os.path as osp import os # ---- Third Party Imports import netCDF4 from geopandas import GeoDataFrame import pandas as pd from shapely.geometry import Point, Polygon import numpy as np dirpath_netcdf = "D:/MeteoGrilleDaily" # %% Get lat/lon from the netCDF filename = osp.join(dirpath_netcdf, 'GCQ_v2_2000.nc') netcdf_dset = netCDF4.Dataset(filename, 'r+') lat = np.array(netcdf_dset['lat']) lon = np.array(netcdf_dset['lon']) netcdf_dset.close() # %% Read the weather data from the InfoClimat grid stack_precip = [] stack_tasmax = [] stack_tasmin = [] nyear = 0 for year in range(2000, 2015): print("\rProcessing year %d" % year, end=' ') filename = osp.join(dirpath_netcdf, 'GCQ_v2_%d.nc' % year) netcdf_dset = netCDF4.Dataset(filename, 'r+') stack_precip.append(np.array(netcdf_dset['pr'])) stack_tasmax.append(np.array(netcdf_dset['tasmax'])) stack_tasmin.append(np.array(netcdf_dset['tasmin'])) netcdf_dset.close() nyear += 1 print('') daily_precip = np.vstack(stack_precip) daily_tasmax = np.vstack(stack_tasmax) daily_tasmin = np.vstack(stack_tasmin) daily_tasavg = (daily_tasmax + daily_tasmin) / 2 yearly_avg_precip = np.sum(daily_precip, axis=0) / nyear yearly_avg_tasavg = np.average(daily_tasavg, axis=0) yearly_avg_tasmax = np.average(daily_tasmax, axis=0) yearly_avg_tasmin = np.average(daily_tasmin, axis=0) # %% Create a grid Np = len(lat) * len(lon) geometry = [] arr_yearly_avg_precip = np.zeros(Np) arr_avg_yearly_tasavg = np.zeros(Np) arr_avg_yearly_tasmax = np.zeros(Np) arr_avg_yearly_tasmin = np.zeros(Np) i = 0 dx = dy = 0.1/2 for j, k in product(range(len(lat)), range(len(lon))): print("\rProcessing cell %d of %d" % (i, Np), end=' ') point = Point((lon[k], lat[j])) # polygon = Polygon([(lon[k]-dx, lat[j]-dy), # (lon[k]-dx, lat[j]+dy), # (lon[k]+dx, lat[j]+dy), # (lon[k]+dx, lat[j]-dy)]) geometry.append(point) arr_yearly_avg_precip[i] = yearly_avg_precip[j, k] arr_avg_yearly_tasavg[i] = yearly_avg_tasavg[j, k] arr_avg_yearly_tasmax[i] = yearly_avg_tasmax[j, k] arr_avg_yearly_tasmin[i] = yearly_avg_tasmin[j, k] i += 1 print("\rProcessing cell %d of %d" % (i, Np)) # %% print('\rFormating the data in a shapefile...', end=' ') df = pd.DataFrame(data={'precip': arr_yearly_avg_precip, 'tasavg': arr_avg_yearly_tasavg, 'tasmax': arr_avg_yearly_tasmax, 'tasmin': arr_avg_yearly_tasmin}) crs = "+proj=longlat +ellps=GRS80 +datum=NAD83 +towgs84=0,0,0,0,0,0,0 +no_defs" gdf = GeoDataFrame(df, crs=crs, geometry=geometry) print('\rFormating the data in a shapefile... done') print('\rSaving to Shapefile...', end=' ') path_shp_out = ("D:/MeteoGrilleDaily/grid_yearly_meteo/grid_yearly_meteo.shp") if not osp.exists(path_shp_out): os.makedirs(path_shp_out) gdf.to_file(path_shp_out) print('\rSaving to Shapefile... done', end=' ')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 30030, 3158, 2681, 838, 25, 4051, 25, 1495, 2864, 198, 31, 9800, 25, 44804, 70, 418, 741, 259, 198, 37811, 198, 198, 2, 13498, 8997, 10074, 184...
2.029658
1,551
# pylint:disable=ungrouped-imports import uuid import pytest import activitylogs from db.models.activitylogs import ActivityLog from events.registry.experiment import EXPERIMENT_DELETED_TRIGGERED from events.registry.user import USER_ACTIVATED from factories.factory_experiments import ExperimentFactory from factories.factory_users import UserFactory from tests.base.case import BaseTest
[ 2, 279, 2645, 600, 25, 40223, 28, 2150, 3233, 276, 12, 320, 3742, 198, 11748, 334, 27112, 198, 198, 11748, 12972, 9288, 198, 198, 11748, 3842, 6404, 82, 198, 198, 6738, 20613, 13, 27530, 13, 21797, 6404, 82, 1330, 24641, 11187, 198, ...
3.477876
113
import unittest from shapy.framework.tcelements import * from shapy.framework.executor import run from tests import TCTestCase
[ 11748, 555, 715, 395, 198, 198, 6738, 427, 12826, 13, 30604, 13, 83, 344, 3639, 1330, 1635, 198, 6738, 427, 12826, 13, 30604, 13, 18558, 38409, 1330, 1057, 198, 198, 6738, 5254, 1330, 309, 4177, 395, 20448, 198 ]
3.394737
38
from colorsys import hsv_to_rgb from math import fabs, fmod import os from hippietrap.color import Color
[ 6738, 7577, 893, 1330, 289, 21370, 62, 1462, 62, 81, 22296, 198, 6738, 10688, 1330, 7843, 82, 11, 277, 4666, 198, 11748, 28686, 198, 6738, 18568, 1155, 2416, 13, 8043, 1330, 5315, 198 ]
3.181818
33
from stix_shifter_utils.utils.entry_point_base import EntryPointBase from stix_shifter_utils.modules.cim.stix_translation.cim_data_mapper import CimDataMapper from stix_shifter_utils.modules.car.stix_translation.car_data_mapper import CarDataMapper from .stix_translation.stix_to_elastic import StixToElastic
[ 6738, 336, 844, 62, 1477, 18171, 62, 26791, 13, 26791, 13, 13000, 62, 4122, 62, 8692, 1330, 21617, 12727, 14881, 198, 6738, 336, 844, 62, 1477, 18171, 62, 26791, 13, 18170, 13, 66, 320, 13, 301, 844, 62, 41519, 13, 66, 320, 62, 78...
2.942857
105
from PyQt5.QtWidgets import (QMainWindow, QToolButton, QWidget, QHBoxLayout) from PyQt5.QtGui import QIcon from PyQt5 import QtCore from math import floor import sys
[ 6738, 9485, 48, 83, 20, 13, 48, 83, 54, 312, 11407, 1330, 357, 48, 13383, 27703, 11, 1195, 25391, 21864, 11, 1195, 38300, 11, 1195, 39, 14253, 32517, 8, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 8205, 72, 1330, 1195, 19578, 198, ...
2.75
60
""" Crack a password using a genetic algorithm! """ import random as rnd def main(): """ This file implements a genetic algorithm to solve the problem of cracking a given password, by creating 'generations' of different words, selecting the best, breeeding them, applying a simple crossover (randomized) and a mutation chance. """ #variables dict: Define the problem constants genetic_variables = { 'password' : "verylongwordpass", 'size_population' : 100, 'best_sample' : 20, 'lucky_few' : 20, 'number_of_child' : 5, 'number_of_generations' : 10000, #Overkill >:D 'chance_of_mutation' : .5 } prob = genetic_variables #program if (prob['best_sample'] + prob['lucky_few'])/2*prob['number_of_child'] != prob['size_population']: print ("population size not stable") return last_gen, _ = genetic_algorithm(**genetic_variables) print("Last generation: \n\n") print(last_gen) def genetic_algorithm(**kwargs): """ Execute the genetic algorithm. This algorithm takes a dict as an argument. It will iterate based on the variable 'number_of_generations', and return the last_gen and the historic """ # Unpack the values from the dict password = kwargs['password'] size_population = kwargs['size_population'] best_sample = kwargs['best_sample'] lucky_few = kwargs['lucky_few'] number_of_child = kwargs['number_of_child'] number_of_generations = kwargs['number_of_generations'] chance_of_mutation = kwargs['chance_of_mutation'] hist = [] # The genetic algorithm curr_pop = initial_pop(size_population, password) hist = curr_pop last_found = -1 for _ in range (number_of_generations): curr_pop = next_gen(curr_pop, password, best_sample, lucky_few, number_of_child, chance_of_mutation) hist.append(curr_pop) if check_solution(curr_pop, password): last_found = _ break if last_found != -1: print(f"Found a solution in the {last_found} generation!!") else: print("No solution found! D':") return curr_pop, hist def next_gen(curr_pop, password, best_sample, lucky_few, number_of_child, chance_of_mutation): """ -> This is the main task of the Genetic Algorithm <- Given the current population, apply the following steps: - Compute the fitness of each individual in the population - Select the best ones (and some lucky guys) - Make them reproduce - Mutate the children - Return this new population """ pop_sorted = compute_perf_pop(curr_pop, password) next_breeders = select_from_population(pop_sorted, best_sample, lucky_few) next_pop = create_children(next_breeders, number_of_child) next_gen = mutate_pop(next_pop, chance_of_mutation) return next_gen def initial_pop(size, password): """ Generate a population consisting of random words, each with the same length as the password, and the population has the size specified. """ return [word_generate(len(password)) for _ in range(size)] def fitness (password, test_word): """ The fitness function: fitness(test_word): (# of correct chars) / (total number of chars) fitness(test_word) = 0 if # of correct chars = 0 fitness(test_word) = 100 if # of correct chars = total number of chars """ if (len(test_word) != len(password)): print("Incompatible password...") return else: score = (1 if password[i] == test_word[i] else 0 for i in range(len(password))) return sum(score)*100/len(password) def compute_perf_pop(population, password): """ Return the population, sorted by the fitness from each individual """ populationPerf = {ind:fitness(password, ind) for ind in population} # Sort by fitness, reversed (best ones in the beginning of the list) return sorted(populationPerf.items(), key= lambda it: it[1], reverse=True) def select_from_population(pop_sorted, best_sample, lucky_few): """ Create the next breeders, with 'best_sample' individuals which have the top fitness value from the population, and 'lucky_few' individuals which are randomly selected. """ next_gen = [] for i in range(best_sample): next_gen.append(pop_sorted[i][0]) # Simple lucky few: randomly select some elements from the population for i in range(lucky_few): next_gen.append(rnd.choice(pop_sorted)[0]) rnd.shuffle(next_gen) return next_gen def create_children(breeders, nof_childs): """ Create the next population of individuals, by breeding two by two """ next_pop = [] mid_pos = len(breeders)//2 # len(breeders) must be an even number for ind_1, ind_2 in zip(breeders[:mid_pos], breeders[mid_pos:]): for _ in range(nof_childs): next_pop.append(create_child(ind_1, ind_2)) return next_pop def mutate_pop(population, chance): """ Given a chance for mutation, this apply the mutation layer to the genetic algorithm, by generating a mutation with the chance specified. """ for i in range(len(population)): if rnd.random() < chance: population[i] = mutate_word(population[i]) return population def mutate_word(word): """ Mutate a letter(gene) from the word, then return it """ pos = int(rnd.random()*len(word)) word = word[:pos] + chr(97 + int(26*rnd.random())) + word[pos + 1:] return word def create_child(ind_1, ind_2): """ For each letter of the child, get a random gene from ind_1 or ind_2 in the i-th position. """ temp = [ind_1[i] if rnd.random() < 0.5 else ind_2[i] for i in range(len(ind_1))] return "".join(temp) def word_generate(length): """ Generate a string with random lowercase letters, with length = length! """ # Generate a random letter from alphabet, lowercase, and add to result return "".join((chr(97 + rnd.randint(0, 26)) for _ in range(length))) def check_solution(population, password): """ Check if the population found a solution to the problem """ return any(ind == password for ind in population) if __name__ == '__main__': main()
[ 37811, 198, 13916, 441, 257, 9206, 1262, 257, 8513, 11862, 0, 198, 37811, 198, 11748, 4738, 355, 374, 358, 198, 198, 4299, 1388, 33529, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 770, 2393, 23986, 257, 8513, 11862, 284, 8494, 262,...
2.667229
2,371