content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
from regression_tests import * # https://github.com/avast-tl/retdec/issues/246 # Test for ordinals that are translated by YARA/pefile LUT. # https://github.com/avast-tl/retdec/issues/246 # Test for ordinals that are NOT translated by YARA/pefile LUT. # https://github.com/avast-tl/retdec/issues/121 # Test export hashes for PE format # https://github.com/avast-tl/retdec/issues/121 # Test export hashes for ELF format # https://github.com/avast-tl/retdec/issues/121 # Test export hashes for ELF format # Test average hash of a PE icon
[ 6738, 20683, 62, 41989, 1330, 1635, 628, 198, 2, 3740, 1378, 12567, 13, 785, 14, 615, 459, 12, 28781, 14, 1186, 12501, 14, 37165, 14, 26912, 198, 2, 6208, 329, 2760, 6897, 326, 389, 14251, 416, 575, 24401, 14, 431, 7753, 406, 3843, ...
3.016667
180
""" Jinja support adds the following abilities: 1. Adds a ``YamlFrontMatterLoader``, which searchs the beginning of the file for YAML between two lines of an equal number of three or more dashes. These lines are stripped off before rendering. 2. Jinja has nice support for displaying errors, but the YAML front matter confuses things. This module fixes that, too, using a ``StrangeCaseStr`` which keeps track of how many lines to ignore. The blank lines are included during compilation, and removed after the file is generated. 3. Provides a ``fix_paths`` function that returns a slash-separated relative path, even on Windows. Note: This function will also chomp any in-filename backslashes. Hopefully you don't have any of those in the relative path to your template. """ import re import os from jinja2 import FileSystemLoader, Environment, Template from jinja2.utils import internalcode class YamlFrontMatterLoader(FileSystemLoader): """ After getting the file content, this loader parses out YAML front matter, which must be the first thing in the file. It consists of three or more dashes or backticks, a newline, YAML content, a newline and then the same number of dashes or backticks, and a newline again. Examples:: ---- yaml: {goes: 'here'} ---- <!-- template --> ```` python = {'goes': 'here'} ```` <!-- template --> When the python code is executed, it is given ``config`` as the local context, so changes to local variables result in changes to the page context. """ def get_source(self, environment, template): """ Matches 3 or more dashes or backticks to the beginning of the content, and then tries to match the same delimiter. """ contents, filename, uptodate = super(YamlFrontMatterLoader, self).get_source(environment, template) front_matter_match = re.match(r"\A([-]{3,}|[`]{3,})(\r\n|\r|\n)", contents) number_yaml_lines = 0 if front_matter_match: newline = front_matter_match.group(2) # group(2) contains the newline/CRLF number_yaml_lines += 1 offset = len(front_matter_match.group(0)) delim = re.compile("^" + front_matter_match.group(1) + "$") lines = contents.splitlines() for line in lines[1:]: # skip the first line, the opening front matter offset += len(line) + len(newline) number_yaml_lines += 1 if delim.match(line): break contents = (newline * number_yaml_lines) + contents[offset:] return StrangeCaseStr(contents, number_yaml_lines), filename, uptodate @internalcode def load(self, environment, name, globals=None): """ If a ``StrangeCaseStr`` is found, ``str.number_yaml_lines`` are stripped off the front of the file after it is generated. """ code = None if globals is None: globals = {} # first we try to get the source for this template together # with the filename and the uptodate function. source, filename, uptodate = self.get_source(environment, name) # try to load the code from the bytecode cache if there is a # bytecode cache configured. bcc = environment.bytecode_cache if bcc is not None: bucket = bcc.get_bucket(environment, name, filename, source) code = bucket.code # if we don't have code so far (not cached, no longer up to # date) etc. we compile the template if code is None: code = environment.compile(source, name, filename) # if the bytecode cache is available and the bucket doesn't # have a code so far, we give the bucket the new code and put # it back to the bytecode cache. if bcc is not None and bucket.code is None: bucket.code = code bcc.set_bucket(bucket) t = environment.template_class.from_code(environment, code, globals, uptodate) if isinstance(source, StrangeCaseStr): t.number_yaml_lines = source.number_yaml_lines return t def fix_path(path): """ Provides a ``fix_paths`` function that returns a slash-separated relative path, even on Windows. Jinja chokes on backslash-separated paths, and slash-separated paths work well enough in Windows anyway. See also Jinja2-99_, Jinja2-98_. .. _Jinja2-98: https://github.com/mitsuhiko/jinja2/issues/98 .. _Jinja2-99: https://github.com/mitsuhiko/jinja2/pull/99 Note: This function will also chomp any in-filename backslashes. Hopefully you don't have any of those in the relative path to your template. """ return path.replace(os.path.sep, '/')
[ 37811, 198, 41, 259, 6592, 1104, 6673, 262, 1708, 7883, 25, 198, 198, 16, 13, 34333, 257, 7559, 56, 43695, 25886, 44, 1436, 17401, 15506, 11, 543, 2989, 82, 262, 3726, 286, 262, 2393, 329, 198, 220, 220, 575, 2390, 43, 1022, 734, ...
2.642431
1,843
import matplotlib.pyplot as plt from read_file import select_original_breakpoints from collections import defaultdict if __name__ == '__main__': N = 5 slopes, intervals = select_original_breakpoints(N, 'segm/segmented_curves_filtered.txt') slopes_hist = defaultdict(lambda: []) intervals_hist = defaultdict(lambda: []) for sample in slopes: for i in range(N): slopes_hist[i].append(sample[i]) for sample in intervals: for i in range(N): intervals_hist[i].append(sample[i]) fig, axs = plt.subplots(5, 2, figsize=(6.5, 10), sharex='col') for i in range(N): axs[i][0].hist(slopes_hist[i]) axs[i][0].set_xlabel('$\\alpha_%d$' % (i + 1)) axs[i][0].set_ylabel('Occurrences', fontsize=12) for i in range(N): axs[i][1].hist(intervals_hist[i]) axs[i][1].set_xlabel('$l_%d$' % (i + 1), fontsize=12) plt.tight_layout() plt.savefig('histogram_by_var.pdf')
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 1100, 62, 7753, 1330, 2922, 62, 14986, 62, 9032, 13033, 198, 6738, 17268, 1330, 4277, 11600, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, ...
2.205882
442
# -*- coding:utf-8 -*- import base64 import numpy as np
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 11748, 2779, 2414, 198, 11748, 299, 32152, 355, 45941, 628, 198 ]
2.416667
24
# generated by appcreator import django_filters from django import forms from dal import autocomplete from vocabs.filters import generous_concept_filter from vocabs.models import SkosConcept from .models import ( NerDataSet, NerSample, Dataset, Example, ProdigyServer)
[ 2, 7560, 416, 598, 45382, 198, 11748, 42625, 14208, 62, 10379, 1010, 198, 6738, 42625, 14208, 1330, 5107, 198, 198, 6738, 288, 282, 1330, 1960, 42829, 6677, 198, 198, 6738, 12776, 8937, 13, 10379, 1010, 1330, 14431, 62, 43169, 62, 24455...
3.041667
96
import numpy as np from typing import Callable, Tuple, Union def assert_model_predictions_deviations( y_pred: float, y_pred_perturb: float, threshold: float = 0.01 ): """Check that model predictions does not deviate more than a given threshold.""" if abs(y_pred - y_pred_perturb) > threshold: return True else: return False def assert_model_predictions_correct( y_pred: float, y_pred_perturb: float, ): """Assert that model predictions are the same.""" if y_pred == y_pred_perturb: return True else: return False def assert_features_in_step(features_in_step: int, input_shape: Tuple[int, ...]) -> None: """Assert that features in step is compatible with the image size.""" assert np.prod(input_shape) % features_in_step == 0, ( "Set 'features_in_step' so that the modulo remainder " "returns zero given the product of the input shape." f" ({np.prod(input_shape)} % {features_in_step} != 0)" ) def assert_max_steps(max_steps_per_input: int, input_shape: Tuple[int, ...]) -> None: """Assert that max steps per inputs is compatible with the image size.""" assert np.prod(input_shape) % max_steps_per_input == 0, ( "Set 'max_steps_per_input' so that the modulo remainder " "returns zero given the product of the input shape." ) def assert_patch_size(patch_size: int, shape: Tuple[int, ...]) -> None: """Assert that patch size is compatible with given shape.""" if isinstance(patch_size, int): patch_size = (patch_size, ) patch_size = np.array(patch_size) if len(patch_size) == 1 and len(shape) != 1: patch_size = tuple(patch_size for _ in shape) elif patch_size.ndim != 1: raise ValueError("patch_size has to be either a scalar or a 1d-sequence") elif len(patch_size) != len(shape): raise ValueError( "patch_size sequence length does not match shape length" f" (len(patch_size) != len(shape))" ) patch_size = tuple(patch_size) if np.prod(shape) % np.prod(patch_size) != 0: raise ValueError( "Set 'patch_size' so that the input shape modulo remainder returns 0" f" [np.prod({shape}) % np.prod({patch_size}) != 0" f" => {np.prod(shape)} % {np.prod(patch_size)} != 0]" ) def assert_attributions_order(order: str) -> None: """Assert that order is in pre-defined list.""" assert order in [ "random", "morf", "lorf", ], "The order of sorting the attributions must be either random, morf, or lorf." def assert_nr_segments(nr_segments: int) -> None: """Assert that the number of segments given the segmentation algorithm is more than one.""" assert ( nr_segments > 1 ), "The number of segments from the segmentation algorithm must be more than one." def assert_perturbation_caused_change(x: np.ndarray, x_perturbed: np.ndarray) -> None: """Assert that perturbation applied to input caused change so that input and perturbed input is not the smae.""" assert (x.flatten() != x_perturbed.flatten()).any(), ( "The settings for perturbing input e.g., 'perturb_func' " "didn't cause change in input. " "Reconsider the parameter settings." ) def assert_layer_order(layer_order: str) -> None: """Assert that layer order is in pre-defined list.""" assert layer_order in ["top_down", "bottom_up", "independent"] def assert_attributions(x_batch: np.array, a_batch: np.array) -> None: """Asserts on attributions. Assumes channel first layout.""" assert ( type(a_batch) == np.ndarray ), "Attributions 'a_batch' should be of type np.ndarray." assert np.shape(x_batch)[0] == np.shape(a_batch)[0], ( "The inputs 'x_batch' and attributions 'a_batch' should " "include the same number of samples." "{} != {}".format(np.shape(x_batch)[0], np.shape(a_batch)[0]) ) assert np.shape(x_batch)[2:] == np.shape(a_batch)[2:], ( "The inputs 'x_batch' and attributions 'a_batch' " "should share the same dimensions." "{} != {}".format(np.shape(x_batch)[2:], np.shape(a_batch)[2:]) ) assert not np.all((a_batch == 0)), ( "The elements in the attribution vector are all equal to zero, " "which may cause inconsistent results since many metrics rely on ordering. " "Recompute the explanations." ) assert not np.all((a_batch == 1.0)), ( "The elements in the attribution vector are all equal to one, " "which may cause inconsistent results since many metrics rely on ordering. " "Recompute the explanations." ) assert len(set(a_batch.flatten().tolist())) > 1, ( "The attributions are uniformly distributed, " "which may cause inconsistent results since many " "metrics rely on ordering." "Recompute the explanations." ) assert not np.all((a_batch < 0.0)), "Attributions should not all be less than zero." def assert_segmentations(x_batch: np.array, s_batch: np.array) -> None: """Asserts on segmentations.""" assert ( type(s_batch) == np.ndarray ), "Segmentations 's_batch' should be of type np.ndarray." assert ( np.shape(x_batch)[0] == np.shape(s_batch)[0] ), "The inputs 'x_batch' and segmentations 's_batch' should include the same number of samples." assert ( np.shape(x_batch)[2:] == np.shape(s_batch)[2:] ), "The inputs 'x_batch' and segmentations 's_batch' should share the same dimensions." assert ( np.shape(s_batch)[1] == 1 ), "The second dimension of the segmentations 's_batch' should be equal to 1." # TODO. assert ( len(np.nonzero(s_batch)) > 0 ), "The segmentation 's_batch' must contain non-zero elements." assert ( np.isin(s_batch.flatten(), [0, 1]).all() or np.isin(s_batch.flatten(), [True, False]).all() ), ("The segmentation 's_batch' should contain only [1, 0] or [True, False].") def assert_value_smaller_than_input_size(x: np.ndarray, value: int, value_name: str): """ Checks if value is smaller than input size. Assumes batch and channel first dimension """ if value >= np.prod(x.shape[2:]): raise ValueError( f"'{value_name}' must be smaller than input size." f" [{value} >= {np.prod(x.shape[2:])}]" )
[ 11748, 299, 32152, 355, 45941, 198, 6738, 19720, 1330, 4889, 540, 11, 309, 29291, 11, 4479, 628, 198, 198, 4299, 6818, 62, 19849, 62, 28764, 9278, 62, 7959, 40356, 7, 198, 220, 220, 220, 331, 62, 28764, 25, 12178, 11, 331, 62, 28764...
2.54307
2,554
import json import urllib.request from collections import defaultdict from datetime import datetime
[ 11748, 33918, 198, 11748, 2956, 297, 571, 13, 25927, 198, 6738, 17268, 1330, 4277, 11600, 198, 6738, 4818, 8079, 1330, 4818, 8079, 628, 198 ]
4.25
24
import requests import re import urllib from lxml import etree from bs4 import BeautifulSoup headers ={"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1","Referer": "http://fanyi.baidu.com/translate?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh"} url ='http://www.meizitu.com/a/legs.html' html = urllib.urlopen(url).read() html = html.decode('gbk') # element = etree.HTML(response.content) # result = element.xpath("//div[@class='pic']/a//@src") # titles = element.xpath("//div[@class='pic']/a/img/@alt") req =r'<img src="(.*?)" alt="(.*?)">' result = re.findall(req,html) for res in result: mainurl =res[0] maintitle =res[1] print(mainurl,maintitle) f = open(u'{}.jpg'.format(maintitle[5]), 'w') print(type(mainurl)) f.write(mainurl) f.close() print(maintitle[5])
[ 11748, 7007, 198, 11748, 302, 198, 11748, 2956, 297, 571, 198, 6738, 300, 19875, 1330, 220, 2123, 631, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 198, 50145, 796, 4895, 12982, 12, 36772, 1298, 366, 44, 8590, 5049, 14, 20, ...
2.377551
392
import datetime as dt from typing import ClassVar, Optional, cast from cuenca_validations.types import SessionRequest, SessionType from pydantic import AnyUrl from pydantic.dataclasses import dataclass from .. import http from .base import Creatable, Queryable, Retrievable @dataclass
[ 11748, 4818, 8079, 355, 288, 83, 198, 6738, 19720, 1330, 5016, 19852, 11, 32233, 11, 3350, 198, 198, 6738, 18912, 268, 6888, 62, 12102, 602, 13, 19199, 1330, 23575, 18453, 11, 23575, 6030, 198, 6738, 279, 5173, 5109, 1330, 4377, 28165, ...
3.52439
82
# -*- coding: iso-8859-15 -*- # Copyright (c) 2014 The New York Times Company # # 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. """ Module that contains utility classes and functions """ import re import logging import json from urllib.parse import urlparse def load_config(config_file_path): """ Converts a collectd configuration into rabbitmq configuration. """ conf_logger = logging.getLogger('Main.StatsModule.Setup') conf_logger.debug('Configuring RabbitMQ Plugin') data_to_ignore = dict() scheme = 'http' validate_certs = True vhost_prefix = None with open(config_file_path, "r") as fp: conf_data = json.load(fp) print(conf_data) for conf_key, conf_value in conf_data.items(): conf_logger.debug("%s = %s", conf_key, conf_value) if conf_value: if conf_key == 'StatsdAddress': statsd_host = conf_value elif conf_key == 'StatsdPort': statsd_port = conf_value elif conf_key == 'StatsdPrefix': statsd_prefix = conf_value elif conf_key == 'Username': username = conf_value elif conf_key == 'Password': password = conf_value elif conf_key == 'Host': host = conf_value elif conf_key == 'Port': port = conf_value elif conf_key == 'Realm': realm = conf_value elif conf_key == 'Scheme': scheme = conf_value elif conf_key == 'VHostPrefix': vhost_prefix = conf_value elif conf_key == 'ValidateCerts': validate_certs = conf_value elif conf_key == 'Ignore': for ignore_param_set in conf_value: type_rmq = ignore_param_set[0] ignore_type = ignore_param_set[1] assert ignore_type == 'Regex' conf_logger.debug("Ignore parameters: '%s', type: '%s'", ignore_param_set, type_rmq) data_to_ignore.setdefault(type_rmq, list()) data_to_ignore[type_rmq].append(ignore_param_set[2]) auth = Auth(username, password, realm) conn = ConnectionInfo(host, port, scheme, validate_certs=validate_certs) statsd_conn = StatsDConnectionInfo(statsd_host, statsd_port, statsd_prefix) config = Config(auth, conn, statsd_conf=statsd_conn, data_to_ignore=data_to_ignore, vhost_prefix=vhost_prefix) return config class Auth(object): """ Stores Auth data. """ class ConnectionInfo(object): """ Stores connection information. """ @property def url(self): """ Returns a url made from scheme, host and port. """ return "{0}://{1}:{2}".format(self.scheme, self.host, self.port) @url.setter def url(self, value): """ Sets scheme, host, and port from URL. """ parsed_url = urlparse(value) self.host = parsed_url.hostname self.port = parsed_url.port self.scheme = parsed_url.scheme class StatsDConnectionInfo(object): """ Stores connection information. """ class Config(object): """ Class that contains configuration data. """ def is_ignored(self, stat_type, name): """ Return true if name of type qtype should be ignored. """ print("Ignore check for %s->%s" % (stat_type, name)) if stat_type in self.data_to_ignore: # print("Params: '%s' -> %s" % (stat_type, self.data_to_ignore[stat_type])) # print("self.data_to_ignore: '%s'" % (self.data_to_ignore, )) for regex in self.data_to_ignore[stat_type]: match = regex.match(name) if match: print("Ignored") return True return False def filter_dictionary(dictionary, keys): """ Returns a dictionary with only keys. """ if not keys: return dict() if not dictionary: return dict() return dict((key, dictionary[key]) for key in keys if key in dictionary) def is_sequence(arg): """ Returns true if arg behaves like a sequence, unless it also implements strip, such as strings. """ return (not hasattr(arg, "strip") and hasattr(arg, "__getitem__") or hasattr(arg, "__iter__"))
[ 2, 532, 9, 12, 19617, 25, 47279, 12, 3459, 3270, 12, 1314, 532, 9, 12, 198, 198, 2, 15069, 357, 66, 8, 1946, 383, 968, 1971, 3782, 5834, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34...
2.281768
2,172
import sys sys.path.append("../../external/CollMetric/") import numpy as np import tensorflow as tf import os from datetime import datetime from sampler import WarpSampler from CML_utils import Evaluator, Monitor, parse_args, dataset_to_uimatrix from CML import CML, optimize if __name__ == '__main__': args = parse_args() os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu random_seed = 2017 np.random.seed(random_seed) tf.compat.v1.set_random_seed(random_seed) print("%s reading dataset %s" % (datetime.now(), args.dataset)) train, valid = dataset_to_uimatrix(args.train_data, args.test_data) n_users, n_items = train.shape print("%s #users=%d, #items=%d" % (datetime.now(), n_users, n_items)) sampler = WarpSampler(train, batch_size=args.batch_size, n_negative=args.num_negative, check_negative=True) # WITHOUT features # Train a user-item joint embedding, where the items a user likes will be pulled closer to this users. # Once the embedding is trained, the recommendations are made by finding the k-Nearest-Neighbor to each user. model = CML(n_users, n_items, # set features to None to disable feature projection features=None, # size of embedding embed_dim=args.embed_dim, # the size of hinge loss margin. margin=args.margin, # clip the embedding so that their norm <= clip_norm clip_norm=args.clip_norm, # learning rate for AdaGrad master_learning_rate=args.lr, # dropout_rate = 1 - keep_prob dropout_rate=args.dropout, # whether to enable rank weight. If True, the loss will be scaled by the estimated # log-rank of the positive items. If False, no weight will be applied. # This is particularly useful to speed up the training for large item set. # Weston, Jason, Samy Bengio, and Nicolas Usunier. # "Wsabie: Scaling up to large vocabulary image annotation." IJCAI. Vol. 11. 2011. use_rank_weight=True, # whether to enable covariance regularization to encourage efficient use of the vector space. # More useful when the size of embedding is smaller (e.g. < 20 ). use_cov_loss=False, # weight of the cov_loss cov_loss_weight=1 ) log_file = open('dataset_' + args.dataset + '_margin_' + str(args.margin) + '_lr_' + str(args.lr) + '.csv', "w") monitor = Monitor(log_file=log_file) optimize(model, sampler, train, valid, max_steps=args.max_steps, monitor=monitor, verbose=args.verbose) print("%s close sampler, close and save to log file" % datetime.now()) log_file.close() sampler.close() # important! stop multithreading print("%s log file and sampler have closed" % datetime.now())
[ 11748, 25064, 198, 17597, 13, 6978, 13, 33295, 7203, 40720, 40720, 22615, 14, 22667, 9171, 1173, 14, 4943, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 28686, 198, 6738, 4818, 8079, 1330, 4818...
2.363284
1,291
import matplotlib.pyplot as plt x = [1,2,3] y = [1,2,1] yerrormin = [0.1,0.5,0.9] yerrormax = [0.2,0.4,0.6] xerror = 0.5 yerror = [yerrormin, yerrormax] plt.plot(x,y,'o') plt.errorbar(x,y,yerr=yerror, xerr=xerror, fmt='o', ecolor='black',elinewidth=2, capsize=5,capthick=2, barsabove=False, errorevery=1, lolims=False, uplims=False, xlolims=False, xuplims=False, alpha=1, ms=10) plt.show()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 87, 796, 685, 16, 11, 17, 11, 18, 60, 198, 88, 796, 685, 16, 11, 17, 11, 16, 60, 198, 88, 8056, 579, 259, 796, 685, 15, 13, 16, 11, 15, 13, 20, 11, 15, 13,...
1.88785
214
""" Example of capturing the average image width VideoCaptureEX class. The averaged image can reduce random noise. """ import EasyPySpin import cv2 if __name__ == "__main__": main()
[ 37811, 198, 16281, 286, 21430, 262, 2811, 2939, 9647, 7623, 49630, 6369, 1398, 13, 198, 464, 16449, 2939, 460, 4646, 4738, 7838, 13, 198, 37811, 198, 11748, 16789, 20519, 4561, 259, 198, 11748, 269, 85, 17, 628, 198, 198, 361, 11593, ...
3.375
56
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_utils import netutils from ovn_octavia_provider.common import constants def remove_macs_from_lsp_addresses(addresses): """Remove the mac addreses from the Logical_Switch_Port addresses column. :param addresses: The list of addresses from the Logical_Switch_Port. Example: ["80:fa:5b:06:72:b7 158.36.44.22", "ff:ff:ff:ff:ff:ff 10.0.0.2"] :returns: A list of IP addesses (v4 and v6) """ ip_list = [] for addr in addresses: ip_list.extend([x for x in addr.split() if (netutils.is_valid_ipv4(x) or netutils.is_valid_ipv6(x))]) return ip_list
[ 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, 198, 2, 220, 220, ...
2.585774
478
for i in range(2, 21): with open(f"tables/Multiplication_table_of_{i}.txt", 'w') as f: for j in range(1, 11): f.write(f"{i}X{j}={i*j}") if j!=10: f.write('\n')
[ 201, 198, 1640, 1312, 287, 2837, 7, 17, 11, 2310, 2599, 201, 198, 220, 220, 220, 351, 1280, 7, 69, 1, 83, 2977, 14, 15205, 24705, 3299, 62, 11487, 62, 1659, 23330, 72, 27422, 14116, 1600, 705, 86, 11537, 355, 277, 25, 201, 198, ...
1.605839
137
""" Module Name: ip_traffic.py Description: Module provides functionality to monitor IP traffic. Authors: Columbia University, the Internet Real-Time Lab (IRT Lab). 2018-2019. """ import random import db import utils from scapy.all import sniff from datetime import datetime def run_ip_traffic_monitor(db_connection, net_interfaces, device_id, agent_ip): """ Function monitors IP traffic in real time using Scapy's sniff function. If an exception occurres it will run again in 5 seconds. Arguments: - db_connection: sqlite3 database connection. - net_interfaces: A list of provided network interfaces. - device_id: An ID (UUID) of current device. - agent_ip: An IPv4 address of agent. """ while 1: try: arp_traffic_out = sniff(prn = ip_monitoring_callback(db_connection, net_interfaces, device_id, agent_ip), filter = "ip", store = 0); except: utc_time_now = str(datetime.utcnow()) print('[' + utc_time_now + '] ' + 'An exception in ip_monitoring_callback function') # Just random sleep between 1 and 5 seconds before starting next round. # This will happen if an exception occurs in ip_monitoring_callback. random_seconds = random.randint(1, 6) time.sleep(random_seconds) def ip_monitoring_callback(db_connection, net_interfaces, device_id, host_ip): """ Function monitors IP traffic in real time using Scapy's sniff function and result stores in the sqlite3 database. Arguments: - db_connection: sqlite3 database connection - net_interfaces: A list of provided network interfaces - device_id: An ID (UUID) of current device - host_ip: An IP address of current device """ # For example, if 10.2.x.x talks to 10.1.x.x that is fine. subnet_ip_list = [] for data in net_interfaces: local_ip = data['ip'] local_ip = local_ip.split('.') subnet_ip_list.append(str(local_ip[0])) host_parts = host_ip.split('.') host_parts = str(host_parts[0]) + '.' + str(host_parts[1]) subnet_ip_list.append(host_parts) """ Note that if I want to pass parameters into the sniff's custom_action function for additional control or the ability to modularize out the custom_action function, I have to use a nested function. """ return upload_packet
[ 37811, 198, 26796, 6530, 25, 198, 220, 20966, 62, 9535, 2108, 13, 9078, 628, 198, 11828, 25, 198, 220, 19937, 3769, 11244, 284, 5671, 6101, 4979, 13, 628, 198, 30515, 669, 25, 198, 220, 9309, 2059, 11, 262, 4455, 6416, 12, 7575, 349...
3.077236
738
""" iota-dust-manager A thread safe, stateless python package that manages your receiving dust address. """ __version__ = "0.1.5" __author__ = 'F-Node-Karlsruhe' import iota_client import threading IOTA_DUST = 1_000_000 IOTA_PER_DUST_TRANSACTION = 100_000 class DustManager: """Create a DustManager. :param seed: The managers own seed. Create a seperate seed for this and don't use your principal seed. :param node: The url of the node to use for the iota client used by the dust manager. :param number_of_dust_transactions: How many dust transactions are possible before the dust alloance must be refreshed on the dust address. Must be between 10 and 100. Default is ``10``. Reminder: for 10 dust transactions you need 1 Mi. Max is 100 dust transactions for 10 Mi. :param swipe_address: The address where the excess IOTAs on the dust address are transfered to. If not specified a dedicated address is generated for this purpose and the funds can be accessed by calling the ``pay_out(iota_address)`` function. :param swipe_threshold: Specifies the amount of IOTAs which shall be swiped to the ``swipe_address`` if the ``dust_address`` exceeds this amount. Default: 1_000_000 """ def get_dust_address(self, for_transaction:bool = True) -> str: """Returns a valid dust address with ``dust_allowance`` :param for_transaction: If the returned address is used for a transaction and shall be undergo the dust checks. Default: ``True`` """ if for_transaction: threading.Thread(target=self.__check_dust_active).start() return self._dust_address def pay_out(self, iota_address:str = None, amount:int = 0, all:bool = False) -> str: """Pays out the entire balance available above the ``working_balance`` to the specified iota address. Alternatively you can define a dedicated swipe address on creation to pay out the summoned dust transactions directly. Returns the message_id of the payout transaction. :param iota_address: The iota address to which the funds shall be payed out. :param amount: The payout amount. Gets refused if the ``working_balance`` is affected. Default: 0. If 0, the entire balance above the ``working_balance`` is payed out. :param all: Default ``False``. When ``True`` the seed gets payed out completely, including the ``working_balance``. """ pay_out_amount = amount if pay_out_amount > self.get_balance(): raise Exception('Payout not possible without affecting the dust working balance of %s iota' % self._working_balance) if pay_out_amount == 0: pay_out_amount = self.get_balance() if all: pay_out_amount = self.get_balance(all=True) output = { 'address': iota_address, 'amount': pay_out_amount } if all: return self._client.message(seed=self._seed, outputs=[output]) return self._client.message(seed=self._seed, input_range_begin=1, input_range_end=2, outputs=[output]) def get_balance(self, all:bool = False) -> int: """Gives the balance of the dust manager which exceeds the ``working_balance`` :param all: Default ``False``. When ``True`` the balance includs the ``working_balance``. """ balance = self._client.get_balance(self._seed) if all: return balance return balance - self._working_balance
[ 37811, 198, 72, 4265, 12, 48859, 12, 37153, 198, 198, 32, 4704, 3338, 11, 1181, 1203, 21015, 5301, 326, 15314, 534, 6464, 8977, 2209, 13, 198, 37811, 198, 198, 834, 9641, 834, 796, 366, 15, 13, 16, 13, 20, 1, 198, 834, 9800, 834, ...
2.300506
1,777
from django.db import models from hvad.models import TranslatableModel, TranslatedFields from django.utils.translation import ugettext_lazy as _
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 289, 85, 324, 13, 27530, 1330, 3602, 49009, 17633, 11, 3602, 17249, 15878, 82, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 334, 1136, 5239, 62, 75, 12582, 355, 4808, 628, 1...
3.5
42
n,m,k=map(int,input().split()) a=min(m,k)+min(n-m,n-k) print(a)
[ 77, 11, 76, 11, 74, 28, 8899, 7, 600, 11, 15414, 22446, 35312, 28955, 198, 64, 28, 1084, 7, 76, 11, 74, 47762, 1084, 7, 77, 12, 76, 11, 77, 12, 74, 8, 198, 4798, 7, 64, 8 ]
1.657895
38
from wurst.transformations.geo import * import pytest @pytest.fixture(scope="function")
[ 6738, 266, 24962, 13, 35636, 602, 13, 469, 78, 1330, 1635, 198, 11748, 12972, 9288, 628, 198, 31, 9078, 9288, 13, 69, 9602, 7, 29982, 2625, 8818, 4943, 628, 628, 628, 628, 628, 628 ]
2.970588
34
# from.import invoice_report
[ 2, 422, 13, 11748, 45458, 62, 13116 ]
4
7
import numpy as np import pandas as pd def batch(l, b=1, n=None): """ Create batch from iterable. Parameters ---------- l : list list to create batches from b : int, optional, [default = 1] batch size n : int, optional, [default = None] if None: len(batches[-1]) < b if len(iterable) % b != 0 else: len(batches[-1]) == b if len(iterable) % b == 0 this will override b param Returns ------- batches : iterable generator of batch Example ------- If n is None, or not inputted >>> l = list(range(10)) >>> batches = batch(l, 3) >>> batches <generator object batch at 0x005A0370> >>> for b in batches: ... print(b) ... [0, 1, 2] [3, 4, 5] [6, 7, 8] [9] if n is not None: >>> l = list(range(10)) >>> batches = batch(l, n=3) >>> batches <generator object batch at 0x006C0F30> >>> for b in batches: ... print(b) ... [0, 1, 2] [3, 4, 5] [6, 7, 8, 9] """ if n is not None: assert n > 0 b = int(len(l) / n) for ndx in range(0, n - 1): yield l[ndx * b:ndx * b + b] yield l[n * b - b:] else: assert b > 0 m = len(l) for ndx in range(0, m, b): yield l[ndx:min(ndx + b, m)] def lookup_date(s): """ This is an extremely fast approach to datetime parsing. For large data, the same dates are often repeated. Rather than re-parse these, we store all unique dates, parse them, and use a lookup to convert all dates. Example: df['date'] = lookup_date(df['date']) """ dates = {date:pd.to_datetime(date) for date in s.unique()} return s.map(dates) def sample_numpy(A, n, replace=False): """ Sample numpy array. Parameters ---------- A : numpy.ndarray(shape=[m, *dims]) numpy array to be sampled from, with number of examples in first dimension n : int number of samples replace : bool False to perform sampling without replacement Returns ------- sample : numpy.ndarray(shape=[n, *dims]) sampled numpy array from A """ return A[np.random.choice(A.shape[0], n, replace=replace), :] def trunc_string(s, limit=100): """Aku adalah dia --> Aku ada...""" return s[:limit]+'...' if len(s) > limit else s
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 628, 198, 4299, 15458, 7, 75, 11, 275, 28, 16, 11, 299, 28, 14202, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 13610, 15458, 422, 11629, 540, 13, 628, 2...
2.249533
1,070
import logging from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, KeyboardButton from autobot import AutoBotConstants from autobot.configuration import AutoBotConfig
[ 11748, 18931, 198, 198, 6738, 573, 30536, 1330, 14883, 9218, 3526, 9704, 929, 11, 14883, 9218, 3526, 27914, 11, 31973, 21864, 198, 198, 6738, 1960, 672, 313, 1330, 11160, 20630, 34184, 1187, 198, 6738, 1960, 672, 313, 13, 11250, 3924, 1...
4.068182
44
# coding: utf-8 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # pylint: disable=undefined-all-variable """NLP Toolkit Data Stream API. It allows easy and customizable streaming of corpora and dataset files. Files can be streamed into formats that are ready for training and evaluation.""" __all__ = ['DataStream', 'CorpusStream', 'LanguageModelStream', 'SimpleDataStream'] import os import glob import numpy as np import mxnet as mx from mxnet.gluon.data import RandomSampler, SequentialSampler from .dataset import CorpusDataset class DataStream(object): """Abstract Data Stream Interface.""" def transform(self, fn): """ Returns ------- DataStream The data stream that lazily transforms the data while streaming. """ return _LazyTransformDataStream(self, fn) class SimpleDataStream(DataStream): """Simple DataStream wrapper for a stream.""" class _LazyTransformDataStream(DataStream): """Data stream that lazily transforms the data.""" class CorpusStream(DataStream): """Common text data stream that streams a corpus consisting of multiple text files that match provided `file_pattern`. One file is read at a time. The returned dataset includes samples, each of which can either be a list of tokens if tokenizer is specified, or otherwise a single string segment produced by the `sample_splitter`. Parameters ---------- file_pattern: str Path to the input text files. encoding : str, default 'utf8' File encoding format. flatten : bool, default False Whether to return all samples as flattened tokens. If True, each sample is a token. skip_empty : bool, default True Whether to skip the empty samples produced from sample_splitters. If False, `bos` and `eos` will be added in empty samples. sample_splitter : function, default str.splitlines A function that splits the dataset string into samples. tokenizer : function or None, default str.split A function that splits each sample string into list of tokens. If None, raw samples are returned according to `sample_splitter`. bos : str or None, default None The token to add at the begining of each sequence. If None, or if tokenizer is not specified, then nothing is added. eos : str or None, default None The token to add at the end of each sequence. If None, or if tokenizer is not specified, then nothing is added. sampler : str, {'sequential', 'random'}, defaults to 'random' The sampler used to sample texts within a file. - 'sequential': SequentialSampler - 'random': RandomSampler file_sampler : str, {'sequential', 'random'}, defaults to 'random' The sampler used to sample a file. - 'sequential': SequentialSampler - 'random': RandomSampler """ class LanguageModelStream(CorpusStream): """Streams a corpus consisting of multiple text files that match provided `file_pattern`, and produces a language modeling stream given the provided sample splitter and word tokenizer. Parameters ---------- file_pattern: str Path to the input text files. encoding : str, default 'utf8' File encoding format. skip_empty : bool, default True Whether to skip the empty samples produced from sample_splitters. If False, `bos` and `eos` will be added in empty samples. sample_splitter : function, default str.splitlines A function that splits the dataset string into samples. tokenizer : function or None, default str.split A function that splits each sample string into list of tokens. If None, raw samples are returned according to `sample_splitter`. bos : str or None, default None The token to add at the begining of each sequence. If None, or if tokenizer is not specified, then nothing is added. eos : str or None, default None The token to add at the end of each sequence. If None, or if tokenizer is not specified, then nothing is added. sampler : str, {'sequential', 'random'}, defaults to 'random' The sampler used to sample texts within a file. - 'sequential': SequentialSampler - 'random': RandomSampler file_sampler : str, {'sequential', 'random'}, defaults to 'random' The sampler used to sample a file. - 'sequential': SequentialSampler - 'random': RandomSampler """ def bptt_batchify(self, vocab, seq_len, batch_size, last_batch='keep'): """The corpus is transformed into batches of numericalized samples, in the way that the recurrent states from last batch connects with the current batch for each sample. Each sample is of shape `(seq_len, batch_size)`. For example, the following 4 sequences:: <bos> a b c d <eos> <bos> e f g h i j <eos> <bos> k l m n <eos> <bos> o <eos> will generate 2 batches with seq_len = 5, batch_size = 2 as follow (transposed): batch_0.data.T:: <bos> a b c d <bos> e f g h batch_0.target.T:: a b c d <eos> e f g h i batch_0.mask.T:: 1 1 1 1 1 1 1 1 1 1 batch_1.data.T:: <bos> k l m n i j <bos> o <padding> batch_1.target.T:: k l m n <eos> j <bos> o <eos> <padding> batch_1.mask.T:: 1 1 1 1 1 1 1 1 1 0 Parameters ---------- vocab : gluonnlp.Vocab The vocabulary to use for numericalizing the dataset. Each token will be mapped to the index according to the vocabulary. seq_len : int The length of each of the samples for truncated back-propagation-through-time (TBPTT). batch_size : int The number of samples in each batch. last_batch : {'keep', 'discard'} How to handle the last batch if the remaining length is less than `seq_len`. - keep: A batch with less samples than previous batches is returned. - discard: The last batch is discarded if it's smaller than `(seq_len, batch_size)`. """ corpus = CorpusStream(self._file_pattern, flatten=False, encoding=self._encoding, skip_empty=self._skip_empty, sample_splitter=self._sample_splitter, tokenizer=self._tokenizer, bos=self._bos, eos=self._eos, sampler=self._sampler, file_sampler=self._file_sampler) return _LanguageModelBPTTStream(corpus, vocab, seq_len, batch_size, last_batch=last_batch) class _LanguageModelBPTTStream(DataStream): """Streams a corpus and produces a language modeling data stream. Parameters ---------- vocab : gluonnlp.Vocab The vocabulary to use for numericalizing the dataset. Each token will be mapped to the index according to the vocabulary. seq_len : int The length of each of the samples for truncated back-propagation-through-time (TBPTT). batch_size : int The number of samples in each batch. last_batch : {'keep', 'discard'} How to handle the last batch if the remaining length is less than `seq_len`. - keep: A batch with less samples than previous batches is returned. - discard: The last batch is discarded if it's smaller than `(seq_len, batch_size)`. """
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, 9387, 351, 428, 670, 329, 3224, 1321, 1...
2.78306
2,987
''' Created on Oct 11, 2017 @author: William Tucker ''' import logging from django.conf import settings from django.contrib.auth import logout, login, get_user_model logger = logging.getLogger(__name__) class LoginMiddleware(): """ Middleware that checks for a valid login in the request and logs the user in """
[ 7061, 6, 198, 41972, 319, 2556, 1367, 11, 2177, 198, 198, 31, 9800, 25, 3977, 25951, 198, 7061, 6, 198, 198, 11748, 18931, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, ...
3.082569
109
# coding: utf-8 from sqkb_api_testing.model.case.http_case import HttpCase from sqkb_api_testing.model.case.mysql_case import MySQLCase from sqkb_api_testing.model.case.rpc_case import RPCCase from sqkb_api_testing.model.case.wait_case import WaitCase
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 6738, 19862, 32812, 62, 15042, 62, 33407, 13, 19849, 13, 7442, 13, 4023, 62, 7442, 1330, 367, 29281, 20448, 198, 6738, 19862, 32812, 62, 15042, 62, 33407, 13, 19849, 13, 7442, 13, 28744, 139...
2.769231
91
import os import requests import shutil import tempfile from zipfile import ZipFile, ZIP_DEFLATED from flask import current_app name = 'JMeter' plugin_name = 'jmeter' plugin_type = 'radon.policies.testing.JMeterLoadTest' """ 'SimpleJMeterLoadTest': { 'type': 'radon.policies.testing.JMeterLoadTest', 'properties': { 'jmx_file': 'sockshop.jmx', 'hostname': 'localhost', 'port': 8080, 'ti_blueprint': 'radon.blueprints.testing.JMeterMasterOnly', 'user.properties': None, 'test_id': 'loadtest213', }, 'targets': ['SockShop'], } """
[ 11748, 28686, 198, 11748, 7007, 198, 11748, 4423, 346, 198, 11748, 20218, 7753, 198, 6738, 19974, 7753, 1330, 38636, 8979, 11, 42977, 62, 7206, 3697, 11617, 198, 198, 6738, 42903, 1330, 1459, 62, 1324, 198, 198, 3672, 796, 705, 50229, 2...
2.386454
251
# -- coding: utf-8 -- # xml解析 dom sax from xml.parsers.expat import ParserCreate from urllib import request xml = r'''<?xml version="1.0"?> <ol> <li><a href="/python">Python</a></li> <li><a href="/ruby">Ruby</a></li> </ol> ''' handler = DefaultSaxHandler() parser = ParserCreate() parser.StartElementHandler = handler.start_element parser.EndElementHandler = handler.end_element parser.CharacterDataHandler = handler.char_data parser.Parse(xml) # 练习:请利用SAX编写程序解析Yahoo的XML格式的天气预报,获取天气预报: # woeid 城市名称 print('\nBegin:=====================================') beijing_weather = WeatherQuery('202141331') beijing_weather.show() print('End:=======================================')
[ 2, 1377, 19617, 25, 3384, 69, 12, 23, 1377, 198, 198, 2, 35555, 164, 100, 96, 162, 252, 238, 2401, 46909, 198, 198, 6738, 35555, 13, 79, 945, 364, 13, 1069, 8071, 1330, 23042, 263, 16447, 198, 6738, 2956, 297, 571, 1330, 2581, 198...
2.292994
314
'''this module acts as a driver for instrumentation definitions + application''' import logging FLASK_KEY = 'flask' DJANGO_KEY = 'django' GRPC_SERVER_KEY = 'grpc:server' GRPC_CLIENT_KEY = 'grpc:client' POSTGRESQL_KEY = 'postgresql' MYSQL_KEY = 'mysql' REQUESTS_KEY = 'requests' AIOHTTP_CLIENT_KEY = 'aiohttp:client' SUPPORTED_LIBRARIES = [ FLASK_KEY, DJANGO_KEY, GRPC_SERVER_KEY, GRPC_CLIENT_KEY, POSTGRESQL_KEY, MYSQL_KEY, REQUESTS_KEY, AIOHTTP_CLIENT_KEY ] # map of library_key => instrumentation wrapper instance _INSTRUMENTATION_STATE = {} logger = logging.getLogger(__name__) def is_already_instrumented(library_key): """check if an instrumentation wrapper is already registered""" return library_key in _INSTRUMENTATION_STATE.keys() def _mark_as_instrumented(library_key, wrapper_instance): """mark an instrumentation wrapper as registered""" _INSTRUMENTATION_STATE[library_key] = wrapper_instance def get_instrumentation_wrapper(library_key): """load an initialize an instrumentation wrapper""" if is_already_instrumented(library_key): return None try: wrapper_instance = None if DJANGO_KEY == library_key: from hypertrace.agent.instrumentation.django import DjangoInstrumentationWrapper #pylint:disable=C0415 wrapper_instance = DjangoInstrumentationWrapper() elif FLASK_KEY == library_key: from hypertrace.agent.instrumentation.flask import FlaskInstrumentorWrapper #pylint:disable=C0415 wrapper_instance = FlaskInstrumentorWrapper() elif GRPC_SERVER_KEY == library_key: from hypertrace.agent.instrumentation.grpc import GrpcInstrumentorServerWrapper #pylint:disable=C0415 wrapper_instance = GrpcInstrumentorServerWrapper() elif GRPC_CLIENT_KEY == library_key: from hypertrace.agent.instrumentation.grpc import GrpcInstrumentorClientWrapper #pylint:disable=C0415 wrapper_instance = GrpcInstrumentorClientWrapper() elif POSTGRESQL_KEY == library_key: from hypertrace.agent.instrumentation.postgresql import PostgreSQLInstrumentorWrapper #pylint:disable=C0415 wrapper_instance = PostgreSQLInstrumentorWrapper() elif MYSQL_KEY == library_key: from hypertrace.agent.instrumentation.mysql import MySQLInstrumentorWrapper #pylint:disable=C0415 wrapper_instance = MySQLInstrumentorWrapper() elif REQUESTS_KEY == library_key: from hypertrace.agent.instrumentation.requests import RequestsInstrumentorWrapper #pylint:disable=C0415 wrapper_instance = RequestsInstrumentorWrapper() elif AIOHTTP_CLIENT_KEY == library_key: from hypertrace.agent.instrumentation.aiohttp import AioHttpClientInstrumentorWrapper #pylint:disable=C0415 wrapper_instance = AioHttpClientInstrumentorWrapper() else: return None _mark_as_instrumented(library_key, wrapper_instance) return wrapper_instance except Exception as _err: # pylint:disable=W0703 logger.debug("Error while attempting to load instrumentation wrapper for %s", library_key) return None
[ 7061, 6, 5661, 8265, 6529, 355, 257, 4639, 329, 8875, 341, 17336, 1343, 3586, 7061, 6, 198, 11748, 18931, 198, 198, 3697, 1921, 42, 62, 20373, 796, 705, 2704, 2093, 6, 198, 35028, 1565, 11230, 62, 20373, 796, 705, 28241, 14208, 6, 1...
2.566294
1,252
import json import os
[ 11748, 33918, 198, 11748, 28686, 628 ]
3.833333
6
from . import lstm, transformer
[ 6738, 764, 1330, 300, 301, 76, 11, 47385, 198 ]
3.555556
9
# -*- coding: utf-8 -*- ### BEGIN LICENSE # Copyright (C) 2010 Mads Chr. Olesen <mchro@cs.aau.dk> #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, 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 this program. If not, see <http://www.gnu.org/licenses/>. ### END LICENSE from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() from numpy import array import messages #Colors for termination detection ( WHITE, BLACK ) = range(2) class TerminationDetection: """Termination detection, implementation of "Derivation of a termination detection algorithm for distributed computations" by Dijkstra, Feijen and Gasteren""" def sentMessage(self): """Node sent a message, mark as black""" self.term_detect_color = BLACK def noMoreWork(self): """Node has no more work, pass the token on, if applicable""" self.has_work = False if self.has_term_detect_token: #print "Rank %d passing on term detect token" % (rank) self.termination_detection_received() # vim:ts=4:sw=4:expandtab
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 21017, 347, 43312, 38559, 24290, 198, 2, 15069, 357, 34, 8, 3050, 4627, 82, 49369, 13, 440, 829, 268, 1279, 76, 354, 305, 31, 6359, 13, 64, 559, 13, 34388, 29, 198, ...
2.968932
515
import PySimpleGUI as sg from alarmClock.clock import Clock from alarmClock.settings import dayList, hourList, minuteList, periodList, clocks def newAlarm(): '''Opens window to create a new alarm, and select days in which alarm plays.''' layout = [ [ sg.Combo(hourList, size=(3, 1), key="-Hour-", default_value='12'), sg.Text(":"), sg.Combo(minuteList, size=(3, 1), enable_events=True, key="-Minute-", default_value='01'), sg.Combo(periodList, size=(3, 2), enable_events=True, key='-Period-', default_value='PM'), ], [ sg.Listbox(dayList, key='-DaySelect-', size=(25, 8), select_mode='multiple'), ], [ sg.Submit(), sg.Exit(), ], ] window = sg.Window("New Alarm", layout, finalize=True) for i in [window['-Hour-'], window['-Minute-'],window['-Period-']]: #Bind window elements in list to <Enter> i.bind('<Enter>', 'Enter-') #creating `i=Enter-` event, causing the associated #combo box to drop down automatically on mouse over while True: event, values = window.read() if event in ['Exit', sg.WIN_CLOSED]: break elif event == '-Hour-Enter-': window['-Hour-'].Widget.event_generate('<Button-1>') elif event == '-Minute-Enter-': window['-Minute-'].Widget.event_generate('<Button-1>') elif event == '-Period-Enter-': window['-Period-'].Widget.event_generate('<Button-1>') elif event == 'Submit': daysOn = [idx for idx, i in enumerate(dayList) if i in values['-DaySelect-']] #Maps days selected in `-DaySelect-` to ints clocks.append(Clock(values['-Hour-'], values['-Minute-'], values['-Period-'], daysOn)) #create a new #instance of the `Clock` class break window.close()
[ 11748, 9485, 26437, 40156, 355, 264, 70, 198, 6738, 10436, 44758, 13, 15750, 1330, 21328, 198, 6738, 10436, 44758, 13, 33692, 1330, 1110, 8053, 11, 1711, 8053, 11, 5664, 8053, 11, 2278, 8053, 11, 29906, 198, 198, 4299, 649, 2348, 1670, ...
1.974217
1,086
from bs4 import BeautifulSoup import requests import time if __name__ == "__main__": while True: find_jobs() time_wait = 10 time.sleep(time_wait*60) print(f"waiting {time_wait} minutes")
[ 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 11748, 7007, 198, 11748, 640, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 197, 4514, 6407, 25, 198, 197, 197, 19796, 62, 43863, 3419, 198, 197, 197, 2435, 6...
2.605263
76
from pinpayments.tests.models import * from pinpayments.tests.templatetags import *
[ 6738, 6757, 15577, 902, 13, 41989, 13, 27530, 1330, 1635, 198, 6738, 6757, 15577, 902, 13, 41989, 13, 11498, 489, 265, 316, 3775, 1330, 1635, 198 ]
3.230769
26
################################################## # Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2021 # ################################################## from .yaml import load_yaml from .yaml import dump_yaml from .check import check_paper_and_correct_format from .check import check_and_sort_by_date
[ 29113, 14468, 2235, 198, 2, 15069, 357, 66, 8, 33591, 1092, 72, 28831, 685, 38, 270, 16066, 360, 12, 55, 12, 56, 4357, 33448, 1303, 198, 29113, 14468, 2235, 198, 6738, 764, 88, 43695, 1330, 3440, 62, 88, 43695, 198, 6738, 764, 88, ...
3.858974
78
from .io import * from .dataset import *
[ 6738, 764, 952, 1330, 1635, 198, 6738, 764, 19608, 292, 316, 1330, 1635 ]
3.076923
13
ORDER_SIDE_BUY = "BUY" ORDER_SIDE_SELL = "SELL" BITMEX_ORDER_SIDE_BUY = "Buy" BITMEX_ORDER_SIDE_SELL = "Sell"
[ 198, 198, 12532, 1137, 62, 50, 14114, 62, 19499, 56, 796, 366, 19499, 56, 1, 198, 12532, 1137, 62, 50, 14114, 62, 5188, 3069, 796, 366, 5188, 3069, 1, 198, 198, 26094, 44, 6369, 62, 12532, 1137, 62, 50, 14114, 62, 19499, 56, 796, ...
1.723077
65
# TODO: Display an image along with the top 5 classes
[ 2, 16926, 46, 25, 16531, 281, 2939, 1863, 351, 262, 1353, 642, 6097 ]
4.076923
13
from typing import List from fastapi import APIRouter from .tags import tags tags_router = APIRouter() @tags_router.get("/", response_model=List[str]) async def list_tags(): """ List of all tag slugs :return: List[str] """ return tags
[ 6738, 19720, 1330, 7343, 198, 6738, 3049, 15042, 1330, 3486, 4663, 39605, 198, 198, 6738, 764, 31499, 1330, 15940, 628, 198, 31499, 62, 472, 353, 796, 3486, 4663, 39605, 3419, 628, 198, 31, 31499, 62, 472, 353, 13, 1136, 7203, 14, 160...
2.708333
96
#!/usr/bin/env python3 import unittest from tconnectsync.parser.nightscout import NightscoutEntry, InvalidBolusTypeException if __name__ == '__main__': unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 555, 715, 395, 198, 6738, 256, 8443, 27261, 13, 48610, 13, 3847, 1416, 448, 1330, 5265, 1416, 448, 30150, 11, 17665, 33, 349, 385, 6030, 16922, 628, 198, 361, 11593, ...
2.9
60
import torch import torch.nn.functional as F from torch import nn from model import ResNeXt101
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 28034, 1330, 299, 77, 198, 198, 6738, 2746, 1330, 1874, 8199, 55, 83, 8784, 628 ]
3.464286
28
import logging import torchvision from kerosene.config.parsers import YamlConfigurationParser from kerosene.config.trainers import RunConfiguration from kerosene.events import Event from kerosene.events.handlers.console import PrintTrainingStatus, PrintModelTrainersStatus from kerosene.events.handlers.visdom import PlotAllModelStateVariables, PlotGradientFlow from kerosene.loggers.visdom.config import VisdomConfiguration from kerosene.loggers.visdom.visdom import VisdomLogger from kerosene.training.trainers import ModelTrainerFactory, SimpleTrainer from torch.utils.data import DataLoader from torchvision.transforms import Compose, ToTensor, Normalize from kerosene_mnist.models import SimpleNet if __name__ == "__main__": logging.basicConfig(level=logging.INFO) CONFIG_FILE_PATH = "config.yml" model_trainer_config, training_config = YamlConfigurationParser.parse(CONFIG_FILE_PATH) train_loader = DataLoader(torchvision.datasets.MNIST('./files/', train=True, download=True, transform=Compose( [ToTensor(), Normalize((0.1307,), (0.3081,))])), batch_size=training_config.batch_size_train, shuffle=True) test_loader = DataLoader(torchvision.datasets.MNIST('./files/', train=False, download=True, transform=Compose( [ToTensor(), Normalize((0.1307,), (0.3081,))])), batch_size=training_config.batch_size_valid, shuffle=True) # Initialize the loggers visdom_logger = VisdomLogger(VisdomConfiguration.from_yml(CONFIG_FILE_PATH)) # Initialize the model trainers model_trainer = ModelTrainerFactory(model=SimpleNet()).create(model_trainer_config, RunConfiguration(use_amp=False)) # Train with the training strategy trainer = SimpleTrainer("MNIST Trainer", train_loader, test_loader, model_trainer) \ .with_event_handler(PrintTrainingStatus(every=100), Event.ON_TRAIN_BATCH_END) \ .with_event_handler(PrintModelTrainersStatus(every=100), Event.ON_BATCH_END) \ .with_event_handler(PlotAllModelStateVariables(visdom_logger), Event.ON_EPOCH_END) \ .with_event_handler(PlotGradientFlow(visdom_logger, every=100), Event.ON_TRAIN_BATCH_END) \ .train(training_config.nb_epochs)
[ 11748, 18931, 198, 198, 11748, 28034, 10178, 198, 6738, 479, 27498, 1734, 13, 11250, 13, 79, 945, 364, 1330, 14063, 75, 38149, 46677, 198, 6738, 479, 27498, 1734, 13, 11250, 13, 27432, 364, 1330, 5660, 38149, 198, 6738, 479, 27498, 1734...
2.931359
743
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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. """Binary for generating predictions over a set of videos.""" import os import time import numpy import numpy as np import tensorflow as tf from tensorflow import app from tensorflow import flags from tensorflow import gfile from tensorflow import logging import utils import eval_util import losses import readers import ensemble_level_models FLAGS = flags.FLAGS if __name__ == '__main__': flags.DEFINE_string("model_checkpoint_path", None, "The file path to load the model from.") flags.DEFINE_string("train_dir", "", "The directory to load the model from.") flags.DEFINE_string("output_dir", "", "The file to save the predictions to.") flags.DEFINE_string( "input_data_patterns", "", "File globs defining the evaluation dataset in tensorflow.SequenceExample format.") flags.DEFINE_string( "input_data_pattern", None, "File globs for original model input.") flags.DEFINE_string("feature_names", "predictions", "Name of the feature " "to use for training.") flags.DEFINE_string("feature_sizes", "4716", "Length of the feature vectors.") # Model flags. flags.DEFINE_string( "model", "MeanModel", "Which architecture to use for the model.") flags.DEFINE_integer("batch_size", 256, "How many examples to process per batch.") flags.DEFINE_string("label_loss", "CrossEntropyLoss", "Loss computed on validation data") flags.DEFINE_integer("file_size", 4096, "Number of frames per batch for DBoF.") def find_class_by_name(name, modules): """Searches the provided modules for the named class and returns it.""" modules = [getattr(module, name, None) for module in modules] return next(a for a in modules if a) def build_graph(all_readers, all_data_patterns, input_reader, input_data_pattern, model, label_loss_fn, batch_size=256): """Creates the Tensorflow graph for evaluation. Args: all_readers: The data file reader. It should inherit from BaseReader. model: The core model (e.g. logistic or neural net). It should inherit from BaseModel. all_data_patterns: glob path to the evaluation data files. label_loss_fn: What kind of loss to apply to the model. It should inherit from BaseLoss. batch_size: How many examples to process at a time. """ global_step = tf.Variable(0, trainable=False, name="global_step") model_input_raw_tensors = [] labels_batch_tensor = None video_id_batch = None for reader, data_pattern in zip(all_readers, all_data_patterns): unused_video_id, model_input_raw, labels_batch, unused_num_frames = ( get_input_data_tensors( reader, data_pattern, batch_size=batch_size)) if labels_batch_tensor is None: labels_batch_tensor = labels_batch if video_id_batch is None: video_id_batch = unused_video_id model_input_raw_tensors.append(tf.expand_dims(model_input_raw, axis=2)) original_input = None if input_data_pattern is not None: unused_video_id, original_input, unused_labels_batch, unused_num_frames = ( get_input_data_tensors( input_reader, input_data_pattern, batch_size=batch_size)) model_input = tf.concat(model_input_raw_tensors, axis=2) labels_batch = labels_batch_tensor with tf.name_scope("model"): result = model.create_model(model_input, labels=labels_batch, vocab_size=reader.num_classes, original_input=original_input, is_training=False) predictions = result["predictions"] if "loss" in result.keys(): label_loss = result["loss"] else: label_loss = label_loss_fn.calculate_loss(predictions, labels_batch) tf.add_to_collection("global_step", global_step) tf.add_to_collection("loss", label_loss) tf.add_to_collection("predictions", predictions) tf.add_to_collection("input_batch", model_input) tf.add_to_collection("video_id_batch", video_id_batch) tf.add_to_collection("labels", tf.cast(labels_batch, tf.float32)) if __name__ == "__main__": app.run()
[ 2, 15069, 1584, 3012, 3457, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
2.554928
1,948
#!/usr/bin/env python3
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 628 ]
2.4
10
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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. """Cron handlers responsible for all Bit9 syncing.""" import datetime import logging import random import time import webapp2 from webapp2_extras import routes from google.appengine.ext import deferred from google.appengine.ext import ndb from common import memcache_decorator from common import datastore_locks from upvote.gae.bigquery import tables from upvote.gae.datastore import utils as datastore_utils from upvote.gae.datastore.models import base from upvote.gae.datastore.models import bit9 from upvote.gae.datastore.models import host as host_models from upvote.gae.datastore.models import rule as rule_models from upvote.gae.datastore.models import user as user_models from upvote.gae.datastore.models import utils as model_utils from upvote.gae.lib.analysis import metrics from upvote.gae.lib.bit9 import api from upvote.gae.lib.bit9 import change_set from upvote.gae.lib.bit9 import constants as bit9_constants from upvote.gae.lib.bit9 import monitoring from upvote.gae.lib.bit9 import utils as bit9_utils from upvote.gae.taskqueue import utils as taskqueue_utils from upvote.gae.utils import handler_utils from upvote.gae.utils import time_utils from upvote.gae.utils import user_utils from upvote.shared import constants _PULL_MAX_QUEUE_SIZE = 10 _DISPATCH_MAX_QUEUE_SIZE = 10 # Automatic scaling sets a 10 minute deadline for tasks queues. We specify a # task duration slightly less than that in order to allow enough time for # everything to finish cleanly (e.g. a 30 second request). See also: # https://cloud.google.com/appengine/docs/standard/java/taskqueue/#push_queues_and_pull_queues _TASK_DURATION = datetime.timedelta(minutes=9, seconds=15) _PULL_LOCK_ID = 'pull_events_lock' _PULL_LOCK_TIMEOUT = int( datetime.timedelta(minutes=10, seconds=30).total_seconds()) _PULL_LOCK_MAX_ACQUIRE_ATTEMPTS = 5 _PULL_BATCH_SIZE = 128 # The lock timeout should be just over the 10 minute task queue timeout, to # ensure that the lock isn't released prematurely during task execution, but # also is not held onto longer than is absolutely necessary. _PROCESS_LOCK_TIMEOUT = int( datetime.timedelta(minutes=10, seconds=30).total_seconds()) _PROCESS_LOCK_MAX_ACQUIRE_ATTEMPTS = 1 _CERT_MEMCACHE_KEY = 'bit9_cert_%s' _CERT_MEMCACHE_TIMEOUT = datetime.timedelta(days=7).total_seconds() _GET_CERT_ATTEMPTS = 3 # Done for the sake of brevity. _POLICY = constants.RULE_POLICY class Error(Exception): """Base error.""" class MalformedCertificateError(Error): """A malformed cert has been received from Bit9.""" class _UnsyncedEvent(ndb.Model): """Model for storing unsynced Event protobufs. Attributes: event: An api.Event API response dict object with FileCatalog and Computer expansions. signing_chain: List[api.Certificate] the binary's signing chain. occurred_dt: Timestamp of when this event occurred on the client. sha256: SHA256 string from the Event proto. Added primarily for easier debugging and investigating. bit9_id: The Bit9 database entity ID associated with this event. """ event = ndb.JsonProperty() signing_chain = ndb.JsonProperty() occurred_dt = ndb.DateTimeProperty() sha256 = ndb.StringProperty() host_id = ndb.IntegerProperty() bit9_id = ndb.IntegerProperty() @classmethod def _Now(): """Returns the current datetime. Primarily for easier unit testing.""" return datetime.datetime.utcnow() @memcache_decorator.Cached( expire_time=_CERT_MEMCACHE_TIMEOUT, create_key_func=lambda f, key, args, kwargs: _CERT_MEMCACHE_KEY % args[0], namespace=None) def _GetCertificate(cert_id): """Gets a certificate entity.""" for _ in xrange(_GET_CERT_ATTEMPTS): cert = api.Certificate.get(cert_id, bit9_utils.CONTEXT) # Attempt to parse the cert before caching it, in case the related # fileCatalog contains an "embedded signer". In such cases, the fileCatalog # contains a certificateId, but the actual cert data comes back empty, # causing breakage here. try: cert.to_raw_dict() except Exception: # pylint: disable=broad-except message = 'Unable to parse Certificate %s' % cert_id logging.exception(message) else: return cert raise MalformedCertificateError(message) def _GetSigningChain(cert_id): """Gets the signing chain of a leaf certificate. Args: cert_id: int, The id of the certificate to get the signing chain of. Returns: The signing chain of the certificate objects in Leaf->Root order. """ signing_chain = [] next_cert_id = cert_id while next_cert_id: cert = _GetCertificate(next_cert_id) signing_chain.append(cert) next_cert_id = cert.parent_certificate_id return signing_chain def GetEvents(last_synced_id, limit=_PULL_BATCH_SIZE): """Get one or more events from Bit9. If events have been retrieved in the last five minutes, gets all recent events. Otherwise, gets events in the oldest unseen five minute interval, so as not to overwhelm Bit9. Args: last_synced_id: The ID of the most recent event that was successfully synced to Upvote. limit: int, If provided, the maximum number of events to pull from the events table. Otherwise, the module default is used. Returns: A list of events not yet pushed to Upvote. """ logging.info('Retrieving events after ID=%s (Max %s)', last_synced_id, limit) events = ( api.Event.query() .filter(api.Event.id > last_synced_id) .filter(api.Event.file_catalog_id > 0) .filter(BuildEventSubtypeFilter()) .expand(api.Event.file_catalog_id) .expand(api.Event.computer_id) .limit(limit) .execute(bit9_utils.CONTEXT)) logging.info('Retrieved %d event(s)', len(events)) event_cert_tuples = [] # Maintain a set of (host_id, sha256) tuples for deduping purposes, in case # a host gets into a bad state and keeps hammering Bit9 with executions of the # same binary. deduping_tuples = set() # Reverse-sort the events by Bit9 ID. This is done so that if we filter out # repeat events during a later iteration, we're still left with the event that # has numerically largest ID. for event in sorted(events, key=lambda e: e.id, reverse=True): logging.info('Constructing event %s', event.id) logging.info('Retrieving fileCatalog %s', event.file_catalog_id) file_catalog = event.get_expand(api.Event.file_catalog_id) if file_catalog is None: logging.warning('Skipping event %s (No fileCatalog found)', event.id) monitoring.events_skipped.Increment() continue # At bare minimum we need a SHA256 out of the fileCatalog, so if it's not # there we have to skip this event. if not file_catalog.sha256: logging.warning('Skipping event %s (Incomplete fileCatalog)', event.id) monitoring.events_skipped.Increment() continue logging.info('Retrieving computer %s', event.computer_id) computer = event.get_expand(api.Event.computer_id) if computer is None: logging.warning('Skipping event %s (No computer found)', event.id) monitoring.events_skipped.Increment() continue # If we've already encountered an event with this host_id and sha256, then # drop it and move on. deduping_tuple = (str(computer.id), file_catalog.sha256) if deduping_tuple in deduping_tuples: logging.warning('Skipping event %s (Duplicate)', event.id) monitoring.events_skipped.Increment() continue else: deduping_tuples.add(deduping_tuple) try: logging.info('Retrieving signing chain %s', file_catalog.certificate_id) signing_chain = _GetSigningChain(file_catalog.certificate_id) # If a MalformedCertificateError makes it all the way out here, we've # already retried the retrieval a number of times, and have likely hit # another fileCatalog containing an "embedded signer". We have to skip this # particular event, otherwise event syncing will halt. except MalformedCertificateError: logging.warning('Skipping event %s (MalformedCertificateError)', event.id) monitoring.events_skipped.Increment() continue # If signing chain retrieval fails for any other reason, just return the # events constructed so far. except Exception as e: # pylint: disable=broad-except logging.exception('Error encountered while retrieving signing chain') logging.warning('Skipping event %s (%s)', event.id, e.__class__.__name__) monitoring.events_skipped.Increment() continue event_cert_tuples.append((event, signing_chain)) # Flip the event tuples back into order of increasing event ID before # returning. return sorted(event_cert_tuples, key=lambda t: t[0].id, reverse=False) def Pull(batch_size=_PULL_BATCH_SIZE): """Retrieve events to sync from Bit9. Args: batch_size: int, The number of events to retrieve in each batch. """ total_pull_count = 0 start_time = _Now() logging.info('Starting a new pull task') try: with datastore_locks.DatastoreLock( _PULL_LOCK_ID, default_timeout=_PULL_LOCK_TIMEOUT, default_max_acquire_attempts=_PULL_LOCK_MAX_ACQUIRE_ATTEMPTS): while time_utils.TimeRemains(start_time, _TASK_DURATION): last_synced_id = GetLastSyncedId() logging.info('Syncing from ID=%s', last_synced_id) # Make an API call for a batch of events. If it fails, just log it and # try again. try: event_tuples = GetEvents(last_synced_id, batch_size) except Exception as e: # pylint: disable=broad-except logging.warning('Event retrieval failed: %s', e) continue pull_count = len(event_tuples) total_pull_count += pull_count logging.info( 'Retrieved %d events (%d events total)', pull_count, total_pull_count) monitoring.events_pulled.IncrementBy(pull_count) # Persist an _UnsyncedEvent for each retrieved Event proto. ndb.put_multi( _UnsyncedEvent.Generate(event, signing_chain) for event, signing_chain in event_tuples) # Briefly pause between requests in order to avoid hammering the Bit9 # server too hard. time.sleep(0.25) except datastore_locks.AcquireLockError: logging.info('Unable to acquire datastore lock') def Dispatch(): """Dispatches per-host tasks onto the event processing queue.""" total_dispatch_count = 0 logging.info('Starting a new dispatch task') # Query for all distinct host_id values among the _UnsyncedEvents, in batches, # either until we run out, or the task nears its deadline. query = _UnsyncedEvent.query( projection=[_UnsyncedEvent.host_id], distinct=True) for event_page in datastore_utils.Paginate(query, page_size=25): host_ids = [event.host_id for event in event_page] for host_id in host_ids: deferred.defer(Process, host_id, _queue=constants.TASK_QUEUE.BIT9_PROCESS) total_dispatch_count += 1 logging.info('Dispatched %d task(s)', total_dispatch_count) def Process(host_id): """Processes _UnsyncedEvents for a single Windows host. Args: host_id: The integer ID of this host in Bit9. """ try: with datastore_locks.DatastoreLock( 'bit9-process-%d' % host_id, default_timeout=_PROCESS_LOCK_TIMEOUT, default_max_acquire_attempts=_PROCESS_LOCK_MAX_ACQUIRE_ATTEMPTS): total_process_count = 0 start_time = _Now() logging.info('Starting a new processing task for %d', host_id) # Query for all _UnsyncedEvents that belong to the given host, in batches, # and process them until we run out, or the task nears its deadline. query = (_UnsyncedEvent.query(_UnsyncedEvent.host_id == host_id) .order(_UnsyncedEvent.bit9_id)) event_pages = datastore_utils.Paginate(query, page_size=25) event_page = next(event_pages, None) while time_utils.TimeRemains(start_time, _TASK_DURATION) and event_page: for unsynced_event in event_page: event = api.Event.from_dict(unsynced_event.event) signing_chain = [ api.Certificate.from_dict(cert) for cert in unsynced_event.signing_chain ] file_catalog = event.get_expand(api.Event.file_catalog_id) computer = event.get_expand(api.Event.computer_id) # Persist the event data. persist_futures = [ _PersistBit9Certificates(signing_chain), _PersistBit9Binary( event, file_catalog, signing_chain, datetime.datetime.utcnow()), _PersistBanNote(file_catalog), _PersistBit9Host(computer, event.timestamp), _PersistBit9Events(event, file_catalog, computer, signing_chain) ] ndb.Future.wait_all(persist_futures) for persist_future in persist_futures: persist_future.check_success() # Now that the event sync has completed successfully, remove the # intermediate proto entity. unsynced_event.key.delete() monitoring.events_processed.Increment() total_process_count += 1 event_page = next(event_pages, None) logging.info('Processed %d event(s)', total_process_count) except datastore_locks.AcquireLockError: logging.info('Unable to acquire datastore lock') def _PersistBit9Certificates(signing_chain): """Creates Bit9Certificates from the given Event protobuf. Args: signing_chain: List[api.Certificate] the signing chain of the event. Returns: An ndb.Future that resolves when all certs are created. """ if not signing_chain: return datastore_utils.GetNoOpFuture() to_create = [] for cert in signing_chain: thumbprint = cert.thumbprint existing_cert = bit9.Bit9Certificate.get_by_id(thumbprint) if existing_cert is None: cert = bit9.Bit9Certificate( id=thumbprint, id_type=cert.thumbprint_algorithm, valid_from_dt=cert.valid_from, valid_to_dt=cert.valid_to) # Insert a row into the Certificate table. Allow the timestamp to be # generated within InsertBigQueryRow(). The Blockable.recorded_dt Property # is set to auto_now_add, but this isn't filled in until persist time. cert.InsertBigQueryRow(constants.BLOCK_ACTION.FIRST_SEEN) to_create.append(cert) futures = ndb.put_multi_async(to_create) return datastore_utils.GetMultiFuture(futures) @ndb.tasklet def _CheckAndResolveInstallerState(blockable_key, bit9_policy): """Ensures Bit9's installer state is consistent with Upvote policy. If there is no Upvote policy or the existing policy conflicts with Bit9's, the function creates rules to reflect Bit9's policy. Args: blockable_key: The key of the blockable that was blocked. bit9_policy: RULE_POLICY.SET_INSTALLER, The installer force policy reported by Bit9. Yields: Whether the installer state was changed. """ logging.info( 'Detected forced installer policy in Bit9 for ID=%s: policy=%s', blockable_key.id(), bit9_policy) assert ndb.in_transaction(), 'Policy changes require a transaction' # pylint: disable=g-explicit-bool-comparison, singleton-comparison installer_query = rule_models.Bit9Rule.query( rule_models.Bit9Rule.in_effect == True, ndb.OR( rule_models.Bit9Rule.policy == _POLICY.FORCE_INSTALLER, rule_models.Bit9Rule.policy == _POLICY.FORCE_NOT_INSTALLER), ancestor=blockable_key) # pylint: enable=g-explicit-bool-comparison, singleton-comparison installer_rule = yield installer_query.get_async() logging.info( 'Forced installer policy in Upvote for ID=%s: policy=%s', blockable_key.id(), ( 'NONE' if installer_rule is None else installer_rule.policy)) has_existing_rule = installer_rule is not None has_conflicting_rule = ( has_existing_rule and installer_rule.is_committed and installer_rule.policy != bit9_policy) if has_existing_rule and not has_conflicting_rule: # The existing rule matches the forced Bit9 policy so no rules need to be # created. raise ndb.Return(False) elif has_conflicting_rule: # If there is a conflicting policy in Upvote, disable it so the new one can # take effect. logging.warning('Forced installer status in Bit9 conflicts with Upvote') installer_rule.in_effect = False yield installer_rule.put_async() logging.info('Importing detected forced installer status from Bit9') # Create a rule to reflect the policy in Bit9. It's marked committed and # fulfilled because the data's already in Bit9, after all. new_rule = rule_models.Bit9Rule( rule_type=constants.RULE_TYPE.BINARY, in_effect=True, is_committed=True, is_fulfilled=True, policy=bit9_policy, parent=blockable_key) new_rule.InsertBigQueryRow( comment=( 'Created to mirror the detected forced installer status already ' 'present in Bit9')) yield new_rule.put_async() raise ndb.Return(True) @ndb.transactional_tasklet def _PersistBit9Binary(event, file_catalog, signing_chain, now): """Creates or updates a Bit9Binary from the given Event protobuf.""" changed = False # Grab the corresponding Bit9Binary. bit9_binary = yield bit9.Bit9Binary.get_by_id_async(file_catalog.sha256) detected_installer = bool( file_catalog.file_flags & bit9_constants.FileFlags.DETECTED_INSTALLER) is_installer = ( bit9_utils.GetEffectiveInstallerState(file_catalog.file_flags)) # Doesn't exist? Guess we better fix that. if bit9_binary is None: logging.info('Creating new Bit9Binary') bit9_binary = bit9.Bit9Binary( id=file_catalog.sha256, id_type=bit9_constants.SHA256_TYPE.MAP_TO_ID_TYPE[ file_catalog.sha256_hash_type], blockable_hash=file_catalog.sha256, file_name=event.file_name, company=file_catalog.company, product_name=file_catalog.product_name, version=file_catalog.product_version, cert_key=_GetCertKey(signing_chain), occurred_dt=event.timestamp, sha1=file_catalog.sha1, product_version=file_catalog.product_version, first_seen_name=file_catalog.file_name, first_seen_date=file_catalog.date_created, first_seen_path=file_catalog.path_name, first_seen_computer=str(file_catalog.computer_id), publisher=file_catalog.publisher, file_type=file_catalog.file_type, md5=file_catalog.md5, file_size=file_catalog.file_size, detected_installer=detected_installer, is_installer=is_installer, file_catalog_id=str(file_catalog.id)) # Insert a row into the Binary table. Use the timestamp passed in from # outside this transaction, otherwise we could end up with duplicate rows in # BigQuery in the case of transaction retries. The Blockable.recorded_dt # Property is set to auto_now_add, but this isn't filled in until persist # time. bit9_binary.InsertBigQueryRow( constants.BLOCK_ACTION.FIRST_SEEN, timestamp=now) metrics.DeferLookupMetric( file_catalog.sha256, constants.ANALYSIS_REASON.NEW_BLOCKABLE) changed = True # If the file catalog ID has changed, update it. if (not bit9_binary.file_catalog_id or bit9_binary.file_catalog_id != str(file_catalog.id)): bit9_binary.file_catalog_id = str(file_catalog.id) changed = True # Binary state comes from clients, which may have outdated policies. Only # update Bit9Binary state if the client claims BANNED and the # Bit9Binary is still UNTRUSTED. if (event.subtype == bit9_constants.SUBTYPE.BANNED and bit9_binary.state == constants.STATE.UNTRUSTED): logging.info( 'Changing Bit9Binary state from %s to %s', bit9_binary.state, constants.STATE.BANNED) bit9_binary.state = constants.STATE.BANNED bit9_binary.InsertBigQueryRow( constants.BLOCK_ACTION.STATE_CHANGE, timestamp=event.timestamp) changed = True if bit9_binary.detected_installer != detected_installer: bit9_binary.detected_installer = detected_installer bit9_binary.is_installer = bit9_binary.CalculateInstallerState() changed = True # Create installer Rules for Bit9Binary installer status if it's been forced # one way or the other in Bit9. marked = file_catalog.file_flags & bit9_constants.FileFlags.MARKED_INSTALLER marked_not = ( file_catalog.file_flags & bit9_constants.FileFlags.MARKED_NOT_INSTALLER) if marked or marked_not: bit9_policy = ( _POLICY.FORCE_INSTALLER if marked else _POLICY.FORCE_NOT_INSTALLER) changed_installer_state = yield _CheckAndResolveInstallerState( bit9_binary.key, bit9_policy) if changed_installer_state: bit9_binary.is_installer = ( bit9_policy == _POLICY.FORCE_INSTALLER) changed = changed_installer_state or changed # Only persist if needed. if changed: logging.info('Attempting to put Bit9Binary...') yield bit9_binary.put_async() # Indicate whether there was a change, primarily for better unit testing. raise ndb.Return(changed) def _PersistBanNote(file_catalog): """Creates a Note entity containing a ban description if needed.""" tuples = [ (file_catalog.certificate_state, 'certificate'), (file_catalog.file_state, 'file'), (file_catalog.publisher_state, 'publisher')] ban_strings = sorted([ 'Banned by %s' % string for state, string in tuples if state == bit9_constants.APPROVAL_STATE.BANNED]) if ban_strings: full_message = '\n'.join(ban_strings) blockable_key = ndb.Key(bit9.Bit9Binary, file_catalog.sha256) note_key = base.Note.GenerateKey(full_message, blockable_key) if note_key.get() is None: logging.info( 'Persisting new ban Note for %s: %s', file_catalog.sha256, ', '.join(ban_strings)) note = base.Note(key=note_key, message=full_message) return note.put_async() return datastore_utils.GetNoOpFuture() @ndb.tasklet def _CopyLocalRules(user_key, dest_host_id): """Copy over a user's local rules to a newly-associated host. NOTE: Because of the implementation of local whitelisting on Bit9, many of these new copied local rules will likely be initially unfulfilled, that is, held in Upvote and not saved to Bit9. Args: user_key: str, The user for whom the rules will be copied. dest_host_id: str, The ID of the host for which the new rules will be created. """ logging.info( 'Copying rules for user %s to host %s', user_key.id(), dest_host_id) # Query for a host belonging to the user. username = user_utils.EmailToUsername(user_key.id()) query = host_models.Bit9Host.query(host_models.Bit9Host.users == username) src_host = yield query.get_async() if src_host is None: logging.warning('User %s has no hosts to copy from', username) raise ndb.Return() src_host_id = src_host.key.id() # Query for all the Bit9Rules in effect for the given user on the chosen host. query = rule_models.Bit9Rule.query( rule_models.Bit9Rule.host_id == src_host_id, rule_models.Bit9Rule.user_key == user_key, rule_models.Bit9Rule.in_effect == True) # pylint: disable=g-explicit-bool-comparison, singleton-comparison src_rules = yield query.fetch_async() logging.info( 'Found a total of %d rule(s) for user %s', len(src_rules), user_key.id()) # Copy the local rules to the new host. logging.info('Copying %d rule(s) to host %s', len(src_rules), dest_host_id) new_rules = [] for src_rule in src_rules: new_rule = datastore_utils.CopyEntity( src_rule, new_parent=src_rule.key.parent(), host_id=dest_host_id, user_key=user_key) new_rules.append(new_rule) new_rule.InsertBigQueryRow() yield ndb.put_multi_async(new_rules) # Create the change sets necessary to submit the new rules to Bit9. changes = [] for new_rule in new_rules: change = bit9.RuleChangeSet( rule_keys=[new_rule.key], change_type=new_rule.policy, parent=new_rule.key.parent()) changes.append(change) logging.info('Creating %d RuleChangeSet(s)', len(changes)) yield ndb.put_multi_async(changes) @ndb.tasklet def _PersistBit9Host(computer, occurred_dt): """Creates a Bit9Host from the Event protobuf if one does not already exist. NOTE: This function could be transactional but, at least for now, host puts in multiple requests don't really need to be processed in a fixed order. last_event_dt is the only frequently modified property and there's currently no need for it to be perfectly accurate. Args: computer: api.Computer object associated with the event. occurred_dt: datetime object corresponding to the time of the event. Returns: ndb.Future that resolves when the host is updated. """ host_id = str(computer.id) policy = computer.policy_id policy_key = ( ndb.Key(host_models.Bit9Policy, str(policy)) if policy is not None else None) hostname = bit9_utils.ExpandHostname( bit9_utils.StripDownLevelDomain(computer.name)) policy_entity = policy_key.get() mode = (policy_entity.enforcement_level if policy_entity is not None else constants.HOST_MODE.UNKNOWN) # Grab the corresponding Bit9Host. bit9_host = yield host_models.Bit9Host.get_by_id_async(host_id) existing_users = set(bit9_host.users if bit9_host is not None else []) extracted_users = list(bit9_utils.ExtractHostUsers(computer.users)) # Ignore any 'Desktop Window Manager' users, otherwise a user can temporarily # become disassociated with their machine. If they vote for something to be # locally whitelisted during such a period, they won't get a rule for it. incoming_users = set() for extracted_user in extracted_users: if r'Window Manager\DWM-' in extracted_user: logging.warning('Ignoring user "%s"', extracted_user) else: incoming_users.add(extracted_user) # If there are incoming users, either because it was only all 'Desktop Window # Manager' entries, or because Bit9 didn't report any users for whatever # reason, then just stick with the existing users, otherwise we'll # disassociate the machine from the user. if not incoming_users: incoming_users = existing_users # Perform initialization for users new to this host. new_users = incoming_users - existing_users for new_user in new_users: # Create User if we haven't seen this user before. email = user_utils.UsernameToEmail(new_user) user = user_models.User.GetOrInsert(email_addr=email) # Copy the user's local rules over from a pre-existing host. yield _CopyLocalRules(user.key, host_id) # List of all row action that need to be persisted. row_actions = [] # Doesn't exist? Guess we better fix that. if bit9_host is None: logging.info('Creating new Bit9Host') bit9_host = host_models.Bit9Host( id=host_id, hostname=hostname, last_event_dt=occurred_dt, policy_key=policy_key, users=sorted(list(incoming_users))) row_actions.append(constants.HOST_ACTION.FIRST_SEEN) else: changed = False if not bit9_host.last_event_dt or bit9_host.last_event_dt < occurred_dt: bit9_host.last_event_dt = occurred_dt changed = True if bit9_host.hostname != hostname: logging.info( 'Hostname for %s changed from %s to %s', host_id, bit9_host.hostname, hostname) bit9_host.hostname = hostname changed = True if bit9_host.policy_key != policy_key: bit9_host.policy_key = policy_key changed = True row_actions.append(constants.HOST_ACTION.MODE_CHANGE) if existing_users != incoming_users: existing_users_list = sorted(list(existing_users)) incoming_users_list = sorted(list(incoming_users)) logging.info( 'Users for %s changed from %s to %s', host_id, existing_users_list, incoming_users_list) bit9_host.users = incoming_users_list changed = True row_actions.append(constants.HOST_ACTION.USERS_CHANGE) if not changed: raise ndb.Return() logging.info('Attempting to put Bit9Host...') yield bit9_host.put_async() for action in row_actions: tables.HOST.InsertRow( device_id=host_id, timestamp=( bit9_host.recorded_dt if action == constants.HOST_ACTION.FIRST_SEEN else bit9_host.last_event_dt), action=action, hostname=hostname, platform=constants.PLATFORM.WINDOWS, users=sorted(list(incoming_users)), mode=mode) def _CheckAndResolveAnomalousBlock(blockable_key, host_id): """Checks whether an unfulfilled rule already existed for this blockable. If there are unfulfilled rules, triggers an attempt to commit them back to the database. Args: blockable_key: The key of the blockable that was blocked. host_id: The host on which the block occurred. Returns: Whether the block was anomalous (i.e. whether an unfulfilled rule existed for the blockable-host pair). """ # Check and handle anomalous block events by detecting unfulfilled rules and, # if present, attempting to commit them. # pylint: disable=g-explicit-bool-comparison, singleton-comparison unfulfilled_rule_query = rule_models.Bit9Rule.query( rule_models.Bit9Rule.is_committed == True, rule_models.Bit9Rule.is_fulfilled == False, rule_models.Bit9Rule.host_id == host_id, ancestor=blockable_key ).order(rule_models.Bit9Rule.updated_dt) # pylint: enable=g-explicit-bool-comparison, singleton-comparison unfulfilled_rules = unfulfilled_rule_query.fetch() # Installer rules shouldn't be local (e.g. have host_id's) so they shouldn't # have been returned by the query. Still, the sanity check couldn't hurt. assert all( rule.policy in _POLICY.SET_EXECUTION for rule in unfulfilled_rules) if unfulfilled_rules: logging.info( 'Processing %s unfulfilled rules for %s', len(unfulfilled_rules), blockable_key.id()) # Mark all outstanding unfulfilled rules _except_ the most recent one as # fulfilled as we're going to ignore them. for rule in unfulfilled_rules[:-1]: rule.is_fulfilled = True # Mark the most recent unfulfilled rule as uncommitted as we're going to # commit it. unfulfilled_rules[-1].is_committed = False # Create and trigger a change set to commit the most recent rule. change = bit9.RuleChangeSet( rule_keys=[unfulfilled_rules[-1].key], change_type=unfulfilled_rules[-1].policy, parent=blockable_key) ndb.put_multi(unfulfilled_rules + [change]) change_set.DeferCommitBlockableChangeSet(blockable_key) return bool(unfulfilled_rules) def _PersistBit9Events(event, file_catalog, computer, signing_chain): """Creates a Bit9Event from the given Event protobuf. Args: event: The api.Event instance to be synced to Upvote. file_catalog: The api.FileCatalog instance associated with this event. computer: The api.Computer instance associated with this event. signing_chain: List of api.Certificate instances associated with this event. Returns: An ndb.Future that resolves when all events are created. """ logging.info('Creating new Bit9Event') host_id = str(computer.id) blockable_key = ndb.Key(bit9.Bit9Binary, file_catalog.sha256) host_users = list(bit9_utils.ExtractHostUsers(computer.users)) occurred_dt = event.timestamp _CheckAndResolveAnomalousBlock(blockable_key, host_id) new_event = bit9.Bit9Event( blockable_key=blockable_key, cert_key=_GetCertKey(signing_chain), event_type=constants.EVENT_TYPE.BLOCK_BINARY, last_blocked_dt=occurred_dt, first_blocked_dt=occurred_dt, host_id=host_id, file_name=event.file_name, file_path=event.path_name, publisher=file_catalog.publisher, version=file_catalog.product_version, description=event.description, executing_user=bit9_utils.ExtractHostUser(event.user_name), bit9_id=event.id) tables.EXECUTION.InsertRow( sha256=new_event.blockable_key.id(), device_id=host_id, timestamp=occurred_dt, platform=new_event.GetPlatformName(), client=new_event.GetClientName(), file_path=new_event.file_path, file_name=new_event.file_name, executing_user=new_event.executing_user, associated_users=host_users, decision=new_event.event_type) keys_to_insert = model_utils.GetEventKeysToInsert( new_event, host_users, host_users) futures = [_PersistBit9Event(new_event, key) for key in keys_to_insert] return datastore_utils.GetMultiFuture(futures) @ndb.transactional_tasklet class CommitAllChangeSets(handler_utils.CronJobHandler): """Attempt a deferred commit for each Blockable with pending change sets.""" class UpdateBit9Policies(handler_utils.CronJobHandler): """Ensures locally cached policies are up-to-date.""" ROUTES = routes.PathPrefixRoute('/bit9', [ webapp2.Route('/commit-pending-change-sets', handler=CommitAllChangeSets), webapp2.Route('/update-policies', handler=UpdateBit9Policies), webapp2.Route('/count-events-to-pull', handler=CountEventsToPull), webapp2.Route('/pull-events', handler=PullEvents), webapp2.Route('/count-events-to-process', handler=CountEventsToProcess), webapp2.Route('/process-events', handler=ProcessEvents), ])
[ 2, 15069, 2177, 3012, 3457, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
2.732433
12,509
#!/usr/bin/env python # encoding: utf-8 """ !----------------------------------------------------------------------- ! HDF5 and XDMF routines for creating output files for VisIt. !----------------------------------------------------------------------- """ import os,sys import h5py from numpy import * # Write a 2D HDF5 File for Rectilinear Mesh # Write a 3D HDF5 File for Rectilinear Mesh # Write a 3D HDF5 File for Curvilinear Mesh # Write a XDMF (.xmf) File for 2D Rectilinear Mesh # Write a XDMF (.xmf) File for 3D Rectilinear Mesh # Write a XDMF (.xmf) File for 3D Curvilinear Mesh # Write a XDMF (.xmf) File for 3D Rectilinear Mesh with HyperSlab Data
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 198, 37811, 220, 198, 0, 10097, 26866, 198, 0, 5572, 37, 20, 290, 1395, 23127, 37, 31878, 329, 4441, 5072, 3696, 329, 6911, 1026, 13, 198, 0, ...
3.100917
218
# -*- coding: utf-8 -*- # Soft NMS for rotated rectangle, cpu implementation. # Author: Gongjie Zhang # GongjieZhang@ntu.edu.sg # or GongjieZhang007@gmail.com import numpy as np import cv2 def softnms_rotate_cpu(boxes, scores, iou_threshold, final_threshold=0.001): """ :param boxes: format [x_c, y_c, w, h, theta(degrees)] :param scores: scores of boxes :param iou_threshold: iou threshold (usually 0.7 or 0.3) :param final_threshold: usually 0.001, if weighted score less than this value, discard the box :return: the remaining INDEX of boxes Note that this function changes """ EPSILON = 1e-5 # a very small number pos = 0 # a position index N = boxes.shape[0] # number of input bounding boxes for i in range(N): maxscore = scores[i] maxpos = i tbox = boxes[i,:] tscore = scores[i] pos = i + 1 # get bounding box with maximum score while pos < N: if maxscore < scores[pos]: maxscore = scores[pos] maxpos = pos pos = pos + 1 # Add max score bounding box as a detection result boxes[i,:] = boxes[maxpos,:] scores[i] = scores[maxpos] # swap ith box with position of max box boxes[maxpos,:] = tbox scores[maxpos] = tscore tbox = boxes[i,:] tscore = scores[i] tarea = tbox[2] * tbox[3] pos = i + 1 # NMS iterations, note that N changes if detection boxes fall below final_threshold while pos < N: box = boxes[pos, :] score = scores[pos] area = box[2] * box[3] try: int_pts = cv2.rotatedRectangleIntersection(((tbox[0], tbox[1]), (tbox[2], tbox[3]), tbox[4]), ((box[0], box[1]), (box[2], box[3]), box[4]))[1] if int_pts is not None: order_pts = cv2.convexHull(int_pts, returnPoints=True) int_area = cv2.contourArea(order_pts) inter = int_area * 1.0 / (tarea + area - int_area + EPSILON) # compute IoU else: inter = 0 except: """ cv2.error: /io/opencv/modules/imgproc/src/intersection.cpp:247: error: (-215) intersection.size() <= 8 in function rotatedRectangleIntersection """ inter = 0.9999 # Soft NMS, weight computation. if inter > iou_threshold: weight = 1 - inter else: weight = 1 scores[pos] = weight * scores[pos] # if box score fall below final_threshold, discard it by swapping with last box # also, update N if scores[pos] < final_threshold: boxes[pos, :] = boxes[N-1, :] scores[pos] = scores[N-1] N = N - 1 pos = pos - 1 pos = pos + 1 keep = [i for i in range(N)] return np.array(keep, np.int64) # for testing if __name__ == '__main__': boxes = np.array([[50, 50, 100, 100, 0], [50, 50, 100, 100, 0], [50, 50, 100, 100, -45.], [200, 200, 100, 105, 0.]]) scores = np.array([0.99, 0.88, 0.66, 0.77]) result = softnms_rotate_cpu(boxes, scores, 0.3) print(boxes) print(result)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 8297, 399, 5653, 329, 38375, 35991, 11, 42804, 7822, 13, 198, 2, 6434, 25, 47142, 73, 494, 19439, 220, 198, 2, 47142, 73, 494, 57, 33255, 31, 429, 84, 13, 15532, ...
1.957699
1,773
# -------------- #Header files import pandas as pd import numpy as np import matplotlib.pyplot as plt #path of the data file- path data = pd.read_csv(path) #Code starts here data['Gender'] = data['Gender'].replace('-','Agender') #print(data['Gender']) gender_count = data['Gender'].value_counts() #print(gender_count) gender_count.plot.bar() # -------------- #Code starts here import matplotlib.pyplot as plt alignment = data['Alignment'].value_counts() plt.pie(alignment) # -------------- #Code starts here sc_df = data[['Strength','Combat']] sc_covariance = sc_df.cov().iloc[0,1] sc_strength = sc_df['Strength'].std() sc_combat = sc_df['Combat'].std() sc_pearson = sc_covariance/(sc_strength*sc_combat) print('Pearson\'s correlation coefficient between Strength & Combat is: ',sc_pearson) ic_df = data[['Intelligence','Combat']] ic_covariance = ic_df.cov().iloc[0,1] ic_intelligence = ic_df['Intelligence'].std() ic_combat = ic_df['Combat'].std() ic_pearson = ic_covariance/(ic_intelligence*ic_combat) print('Pearson\'s correlation coefficient between Intelligence & Comba is: ',ic_pearson) # -------------- #Code starts here total_high = round(data['Total'].quantile([.99]).values[0],2) print('Total High: ',total_high) print(type(total_high)) #print(total_high.values) super_best = data[data['Total'].values>total_high] print(type(super_best)) super_best_names = super_best['Name'].values.tolist() print(super_best_names) # -------------- #Code starts here ''' ax_1 = plt.figure().add_subplot(111) ax_2 = plt.figure().add_subplot(111) ax_3 = plt.figure().add_subplot(111) ax1.boxplot(super_best) ax2.boxplot(super_best) ax3.boxplot(super_best) ax1.set_title('Intelligence') ax2.set_title('Speed') ax3.set_title('Power') plt.show() ''' #Setting up the subplots fig, (ax_1, ax_2,ax_3) = plt.subplots(1,3, figsize=(20,8)) #Plotting box plot ax_1.boxplot(super_best['Intelligence']) #Setting the subplot axis title ax_1.set(title='Intelligence') #Plotting box plot ax_2.boxplot(super_best['Speed']) #Setting the subplot axis title ax_2.set(title='Speed') #Plotting box plot ax_3.boxplot(super_best['Power']) #Setting the subplot axis title ax_3.set(title='Power') #Code ends here
[ 2, 220, 26171, 198, 2, 39681, 3696, 201, 198, 11748, 19798, 292, 355, 279, 67, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 201, 198, 201, 198, 201, 198, 2, 6978, 286, ...
2.509868
912
import os from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) meta_info = {} with open(os.path.join(here, 'jsons', '_package_info.py'), 'r') as f: exec(f.read(), meta_info) with open('README.md', 'r') as f: long_description = f.read() setup( name=meta_info['__title__'], version=meta_info['__version__'], author=meta_info['__author__'], author_email=meta_info['__author_email__'], description=meta_info['__description__'], url=meta_info['__url__'], long_description=long_description, long_description_content_type='text/markdown', license=meta_info['__license__'], packages=[ 'jsons', 'jsons.classes', 'jsons.deserializers', 'jsons.serializers', ], python_requires='>=3.5', install_requires=[ 'typish>=1.9.2', ], extras_require={ 'test': [ 'dataclasses;python_version=="3.6"', 'tzdata;python_version>="3.9"', 'attrs', 'coverage', 'codecov', 'pytest', 'scons', ] }, test_suite='tests', zip_safe=False, classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Natural Language :: English', 'Programming Language :: Python', 'Programming Language :: Python :: 3', *['Programming Language :: Python :: {}'.format(version) for version in meta_info['__python_versions__']], ] )
[ 11748, 28686, 198, 6738, 900, 37623, 10141, 1330, 9058, 628, 198, 1456, 796, 28686, 13, 6978, 13, 397, 2777, 776, 7, 418, 13, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 4008, 198, 28961, 62, 10951, 796, 23884, 198, 4480, 1280, 7, 418...
2.201964
713
from .eLABJournalPager import *
[ 6738, 764, 68, 48780, 25296, 47, 3536, 1330, 1635, 198 ]
3.2
10
# Uses python3 import sys def sort_list(left, right): '''MergeSort(𝐴) returns a sorted array 𝐴 and the number of inversions in 𝐴.''' sort_a = list() count = 0 while left and right: first_l = left[0] first_r = right[0] if first_l <= first_r: sort_a.append(first_l) left.remove(first_l) # An inversion is when the largest number is on the left, # and is moved to the bottom of the list. else: count += len(left) sort_a.append(first_r) right.remove(first_r) if len(left) > 0: sort_a.extend(left) if len(right) > 0: sort_a.extend(right) return sort_a, count def get_number_of_inversions(array): '''Count the number of inversions of a given sequence. Merge(𝐵, 𝐶) returns the resulting sorted array and the number of pairs (𝑏, 𝑐) such that 𝑏 ∈ 𝐵, 𝑐 ∈ 𝐶, and 𝑏 > 𝑐''' if len(array) == 1: return array, 0 mid = len(array) // 2 mid_l = array[:mid] mid_r = array[mid:] m_lf, inv_lf = get_number_of_inversions(mid_l) m_rg, inv_rg = get_number_of_inversions(mid_r) sort_array, inversions = sort_list(m_lf, m_rg) return sort_array, (inv_lf + inv_rg + inversions) if __name__ == '__main__': numbers = sys.stdin.read() n, *a = list(map(int, numbers.split())) n_inversions = get_number_of_inversions(a)[1] print(n_inversions)
[ 2, 36965, 21015, 18, 198, 11748, 25064, 198, 198, 4299, 3297, 62, 4868, 7, 9464, 11, 826, 2599, 198, 220, 220, 220, 705, 7061, 13102, 469, 42758, 7, 47728, 238, 112, 8, 5860, 257, 23243, 7177, 220, 47728, 238, 112, 290, 262, 1271, ...
2.092888
689
from __future__ import print_function, division from pdb import set_trace import pandas as pd from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import LeaveOneOut from itertools import islice
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 11, 7297, 201, 198, 201, 198, 6738, 279, 9945, 1330, 900, 62, 40546, 201, 198, 201, 198, 11748, 19798, 292, 355, 279, 67, 201, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 29186, ...
3.050633
79
import torch import argparse import os import logging import torch.nn as nn import torch.optim as optim import albumentations as A from albumentations.pytorch import ToTensorV2 from cnn.evaluate import evaluate, prettify_eval from cnn.dataset import Mit67Dataset import json from torch.utils.tensorboard import SummaryWriter from cnn.utils import load_arch from cnn.utils import LabelSmoothingLoss from math import inf if __name__ == '__main__': main()
[ 11748, 28034, 198, 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 18931, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 40085, 355, 6436, 198, 11748, 435, 65, 1713, 602, 355, 317, 198, 6738, 435, 65, 1713, 602, ...
3.269504
141
# ------------------------------------------------------------------------------ # MIT License # # Copyright (c) 2019-2021 ThatRedKite # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or substantial portions of # the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO # THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ------------------------------------------------------------------------------ import os import redis from datetime import datetime from pathlib import Path import aiohttp import psutil import discord from discord.ext import commands import thatkitebot.tkb_first_setup tempdir = "/tmp/tkb/" datadir = "/app/data" intents = discord.Intents.default() intents.typing = False intents.members = True intents.invites = False intents.presences = False intents.reactions = False dirname = Path(os.path.dirname(os.path.realpath(__file__))) with redis.Redis(host="redis", db=0,charset="utf-8", decode_responses=True) as tr: print("Loading tokens from redis") tokens = tr.mget(["DISCORDTOKEN", "TENORTOKEN", "PREFIX"]) if None in tokens: print("Trying to initialize tokens from settings.json ...") thatkitebot.tkb_first_setup.initial() tokens = tr.mget(["DISCORDTOKEN", "TENORTOKEN", "PREFIX"]) discord_token, tenor_token, prefix = tokens enabled_ext = [ "thatkitebot.cogs.funstuffcog", "thatkitebot.cogs.imagecog", "thatkitebot.cogs.nsfwcog", "thatkitebot.cogs.listenercog", "thatkitebot.cogs.sudocog", "thatkitebot.cogs.utilitiescog", "thatkitebot.cogs.settings", "thatkitebot.cogs.help", "thatkitebot.cogs.chemistry", "thatkitebot.cogs.electronics", "thatkitebot.cogs.laser" ] bot = ThatKiteBot(prefix, dirname, tt=tenor_token, intents=intents) print(f"Loading extensions: \n") for ext in enabled_ext: try: print(f" loading {ext}") bot.load_extension(ext) except Exception as exc: print(f"error loading {ext}") raise exc # cogs try: bot.run(discord_token) except discord.errors.LoginFailure: with redis.Redis(host="redis", db=0, charset="utf-8", decode_responses=True) as tr: tr.delete("DISCORDTOKEN") print("Improper token in your settings. Please re-enter your token in init_settings.yml!")
[ 2, 16529, 26171, 198, 2, 220, 17168, 13789, 198, 2, 198, 2, 220, 15069, 357, 66, 8, 13130, 12, 1238, 2481, 1320, 7738, 42, 578, 198, 2, 198, 2, 220, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 2...
2.922006
1,077
from .models import S3Parquetifier
[ 6738, 764, 27530, 1330, 311, 18, 10044, 21108, 7483, 198 ]
3.5
10
from pyspark import SparkContext, SparkConf from pyspark.sql import SQLContext from pyspark.sql.types import * from pyspark.sql.functions import udf from pyspark.sql.functions import col from pyspark.sql.types import StringType, DoubleType, IntegerType from abbreviations_dict import tofullname, toevent from operator import itemgetter from pyspark import StorageLevel import pyspark_cassandra sc = SparkContext() sqlContext = SQLContext(sc) c_exists = udf(country_exists,StringType()) e_exists = udf(event_exists,StringType()) dfsub1 = df.withColumn("ActionGeo_CountryCode",c_exists(col("ActionGeo_CountryCode"))) \ .withColumn("Actor1Type1Code",e_exists(col("Actor1Type1Code"))) sqlContext.registerDataFrameAsTable(dfsub1, 'temp') df2 = sqlContext.sql("""SELECT ActionGeo_CountryCode, CAST(SQLDATE AS INTEGER), CAST(MonthYear AS INTEGER), CAST(Year AS INTEGER), CASE WHEN Actor1Type1Code = '' AND Actor2Type1Code <> '' THEN Actor2Type1Code ELSE Actor1Type1Code END AS Actor1Type1Code, CAST(NumArticles AS INTEGER), CAST(GoldsteinScale AS INTEGER), CAST(AvgTone AS INTEGER) FROM temp WHERE ActionGeo_CountryCode <> '' AND ActionGeo_CountryCode IS NOT NULL AND Actor1Type1Code <> '' AND Actor1Type1Code IS NOT NULL AND NumArticles <> '' AND NumArticles IS NOT NULL AND GoldsteinScale <> '' AND GoldsteinScale IS NOT NULL AND AvgTone <> '' AND AvgTone IS NOT NULL""") sqlContext.dropTempTable('temp') sqlContext.registerDataFrameAsTable(df2, 'temp3') sqlContext.cacheTable('temp3') dfdaily = sqlContext.sql("""SELECT ActionGeo_CountryCode, SQLDATE, Actor1Type1Code, SUM(NumArticles) AS NumArticles, ROUND(AVG(GoldsteinScale),0) AS GoldsteinScale, ROUND(AVG(AvgTone),0) AS AvgTone FROM temp3 GROUP BY ActionGeo_CountryCode, SQLDATE, Actor1Type1Code""") dfmonthly = sqlContext.sql("""SELECT ActionGeo_CountryCode, MonthYear, Actor1Type1Code, SUM(NumArticles) AS NumArticles, ROUND(AVG(GoldsteinScale),0) AS GoldsteinScale, ROUND(AVG(AvgTone),0) as AvgTone FROM temp3 GROUP BY ActionGeo_CountryCode, MonthYear, Actor1Type1Code""") dfyearly = sqlContext.sql("""SELECT ActionGeo_CountryCode, Year, Actor1Type1Code, SUM(NumArticles) AS NumArticles, ROUND(AVG(GoldsteinScale),0) AS GoldsteinScale, ROUND(AVG(AvgTone),0) as AvgTone FROM temp3 GROUP BY ActionGeo_CountryCode, Year, Actor1Type1Code""") rdd_format = rd.map(lambda y: ((y["ActionGeo_CountryCode"],y[timeframe]), ([(y["Actor1Type1Code"],y["NumArticles"])], [(y["Actor1Type1Code"], {"Goldstein":y["GoldsteinScale"],"ToneAvg":y["AvgTone"]})]))) \ .reduceByKey(lambda a, b: (a[0]+b[0], a[1]+b[1])) \ .map(lambda v: (v[0], sorted(v[1][0],key=itemgetter(1),reverse=True), dict(v[1][1]))) \ .map(sum_allevents) \ .map(popular_avg) \ .map(event_todict) \ .map(merge_info) \ .map(lambda d: ((d[0][0],d[0][1],d[1]))) return rdd_format
[ 6738, 279, 893, 20928, 1330, 17732, 21947, 11, 17732, 18546, 198, 6738, 279, 893, 20928, 13, 25410, 1330, 16363, 21947, 198, 6738, 279, 893, 20928, 13, 25410, 13, 19199, 1330, 1635, 198, 6738, 279, 893, 20928, 13, 25410, 13, 12543, 2733...
1.986376
1,835
SEND_MESSAGE_DATASET_TRAIN = [ { "query": "Text mom I love her", "actions": [ { "action": "SendMessage", "params": { "recipient": "mom", "body": "I love her", "application": "???" } }, ] }, { "query": "text message steve and ask if he's coming to the meeting", "actions": [ { "action": "SendMessage", "params": { "recipient": "steve", "body": "Are you coming to the meeting?", "application": "???" } }, ] }, { "query": "msg Jackie and let her know I'll be home by 10 tonight", "actions": [ { "action": "SendMessage", "params": { "recipient": "Jackie", "body": "I'll be home by 10pm", "application": "???" } }, ] }, { "query": "text Colin on Facebook Messenger and ask him if he's free for tennis tomorrow", "actions": [ { "action": "SendMessage", "params": { "recipient": "Colin", "body": "Are you free for tennis tomorrow?", "application": "Facebook Messenger" } }, ] }, { "query": "Want to hang out tonight?", "actions": [ { "action": "SendMessage", "params": { "recipient": "???", "body": "Do you want to hang out tonight?", "application": "???" } }, ] }, { "query": "Reply to Sam Fortuner on WhatsApp", "actions": [ { "action": "SendMessage", "params": { "recipient": "Sam Fortuner", "body": "???", "application": "WhatsApp" } }, ] }, { "query": "slack Sean Bean and tell him I'm running late to the meeting", "actions": [ { "action": "SendMessage", "params": { "recipient": "Sean Bean", "body": "I'm running late to the meeting", "application": "Slack" } }, ] }, { "query": "Let Hari know I just pushed my latest changes to the github repo", "actions": [ { "action": "SendMessage", "params": { "recipient": "Hari", "body": "I pushed my latest changes to the repo", "application": "???" } }, ] }, { "query": "tell Dad I'll see him next month", "actions": [ { "action": "SendMessage", "params": { "recipient": "Dad", "body": "I'll see you next month", "application": "???" } }, ] }, { "query": "Reply Sounds fun!", "actions": [ { "action": "SendMessage", "params": { "recipient": "???", "body": "Sounds fun!", "application": "???" } }, ] }, ] SEND_MESSAGE_DATASET_TEST = [ { "query": "message Liam Briggs and see if he wants to get together", "actions": [{'action': 'SendMessage', 'params': {'recipient': 'Liam Briggs', 'body': 'Do you want to get together?', 'application': '???'}}] }, { "query": "whatsapp Kabir how are you doing?", "actions": [{'action': 'SendMessage', 'params': {'recipient': 'Kabir', 'body': 'How are you doing?', 'application': 'WhatsApp'}}] }, { "query": "Can you ping Joe Boring and say thanks", "actions": [{'action': 'SendMessage', 'params': {'recipient': 'Joe Boring', 'body': 'Thanks', 'application': '???'}}] }, { "query": "msg Stew on Slack are you coming to Burning man?", "actions": [{'action': 'SendMessage', 'params': {'recipient': 'Stew', 'body': 'Are you coming to Burning Man?', 'application': 'Slack'}}] }, { "query": "text Colin on iMessage and see if he's still going to the store", "actions": [{'action': 'SendMessage', 'params': {'recipient': 'Colin', 'body': 'Are you still going to the store?', 'application': 'iMessage'}}] }, { "query": "This is something isn't it", "actions": [{'action': 'SendMessage', 'params': {'recipient': '???', 'body': "This is something isn't it", 'application': '???'}}] }, ] MESSAGING_DATASET_TRAIN = [] MESSAGING_DATASET_TRAIN.append(SEND_MESSAGE_DATASET_TRAIN)
[ 50, 10619, 62, 44, 1546, 4090, 8264, 62, 35, 1404, 1921, 2767, 62, 51, 3861, 1268, 796, 685, 198, 220, 220, 220, 1391, 198, 220, 220, 220, 220, 220, 220, 220, 366, 22766, 1298, 366, 8206, 1995, 314, 1842, 607, 1600, 198, 220, 220,...
1.802109
2,845
#!/usr/bin/env python ''' Use geomeTRIC library to optimize the molecular geometry. ''' from pyscf import gto, scf from pyscf.geomopt.geometric_solver import optimize mol = gto.M(atom='N 0 0 0; N 0 0 1.2', basis='ccpvdz') mf = scf.RHF(mol) # # geometry optimization for HF # mol_eq = optimize(mf) print(mol_eq.atom_coords()) # # geometry optimization for CASSCF # from pyscf import mcscf mf = scf.RHF(mol) mc = mcscf.CASSCF(mf, 4, 4) conv_params = { 'convergence_energy': 1e-4, # Eh 'convergence_grms': 3e-3, # Eh/Bohr 'convergence_gmax': 4.5e-3, # Eh/Bohr 'convergence_drms': 1.2e-2, # Angstrom 'convergence_dmax': 1.8e-2, # Angstrom } mol_eq = optimize(mc, **conv_params)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 7061, 6, 198, 11041, 4903, 462, 5446, 2149, 5888, 284, 27183, 262, 18955, 22939, 13, 198, 7061, 6, 198, 198, 6738, 279, 893, 12993, 1330, 308, 1462, 11, 629, 69, 198, 6738, 279,...
2.175385
325
# -*- coding: utf-8 -*- # # Copyright (C) 2010-2016 PPMessage. # Guijin Ding, dingguijin@gmail.com. # All rights reserved. # # core/utils/randomidenticon.py # import os import json import logging IDENTICON_PPMESSAGE_STORE = True _global_random_identicon_list = None if __name__ == "__main__": print(random_identicon("dingguijin@gmail.com"))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 34, 8, 3050, 12, 5304, 350, 5868, 7589, 13, 198, 2, 1962, 2926, 259, 46980, 11, 44852, 5162, 2926, 259, 31, 14816, 13, 785, 13, 198, 2, 1439...
2.554745
137
var = "Good" show() print("outside function var1 is ", var1) print("var is ",var)
[ 7785, 796, 366, 10248, 1, 201, 198, 201, 198, 12860, 3419, 201, 198, 4798, 7203, 43435, 2163, 1401, 16, 318, 33172, 1401, 16, 8, 201, 198, 4798, 7203, 7785, 318, 33172, 7785, 8, 201, 198, 220, 220, 220, 220, 201, 198 ]
2.292683
41
"""Module that implements control service.""" from multiprocessing import Process import asyncio import json import zmq import zmq.asyncio from npc_engine import services from npc_engine.server.metadata_manager import MetadataManager from jsonrpc import JSONRPCResponseManager, Dispatcher from loguru import logger class ServiceState: """Enum for the state of the service.""" STARTING = "starting" RUNNING = "running" STOPPED = "stopped" AWAITING = "awaiting" TIMEOUT = "timeout" ERROR = "error" def set_logger(logger_): """Set the logger for the service.""" global logger logger = logger_ def service_process(metadata: MetadataManager, service_id: str, logger) -> None: """Service subprocess function. Starts the service and runs it's loop. """ set_logger(logger) context = zmq.Context() service = services.BaseService.create( context, metadata.services[service_id].path, metadata.services[service_id].uri, service_id, ) service.loop() class ControlService: """Service that manages other services and routes requests.""" def __init__( self, zmq_context: zmq.asyncio.Context, metadata_manager: MetadataManager, ) -> None: """Initialize control service. Args: zmq_context: asyncio zmq context server_port: server port that will be passed to services for inter-communication """ self.server_port = metadata_manager.port self.metadata = metadata_manager self.control_dispatcher = Dispatcher() self.control_dispatcher.update( { "get_services_metadata": self.metadata.get_services_metadata, "get_service_metadata": self.metadata.get_metadata, "get_service_status": self.get_service_status, "start_service": self.start_service, "stop_service": self.stop_service, "restart_service": self.restart_service, "check_dependency": self.check_dependency, } ) self.zmq_context = zmq_context self.services = { service_id: { "process": None, "socket": None, "state": ServiceState.STOPPED, } for service_id in self.metadata.services.keys() } def __del__(self): """Stop all services.""" if hasattr(self, "services"): for service_id, service in self.services.items(): if service["state"] == ServiceState.RUNNING: try: self.stop_service(service_id) except Exception: pass async def handle_request(self, address: str, request: str) -> str: """Parse request string and route request to correct service. Args: address (str): address of the service (either model name or class name) request (str): jsonRPC string Returns: str: jsonRPC response """ request_dict = json.loads(request) service_id = self.metadata.resolve_service(address, request_dict["method"]) self.check_service(service_id) logger.info(f"Request from {address}\n Request: {request}") if service_id == "control": return JSONRPCResponseManager.handle(request, self.control_dispatcher).json else: if self.services[service_id]["state"] != ServiceState.RUNNING: raise ValueError(f"Service {service_id} is not running") else: socket = self.services[service_id]["socket"] await socket.send_string(request) response = await socket.recv_string() return response def check_service(self, service_id): """Check if the service process is running.""" if ( service_id != "control" and ( self.services[service_id]["state"] == ServiceState.RUNNING or self.services[service_id]["state"] == ServiceState.STARTING or self.services[service_id]["state"] == ServiceState.AWAITING ) and not self.services[service_id]["process"].is_alive() ): self.services[service_id]["state"] = ServiceState.ERROR raise ValueError(f"Error in service {service_id}. Process is not alive.") def get_service_status(self, service_id): """Get the status of the service.""" service_id = self.metadata.resolve_service(service_id, None) self.check_service(service_id) return self.services[service_id]["state"] def start_service(self, service_id): """Start the service.""" service_id = self.metadata.resolve_service(service_id, None) self.check_service(service_id) if self.services[service_id]["state"] == ServiceState.RUNNING: raise ValueError(f"Service {service_id} is already running") process = Process( target=service_process, args=(self.metadata, service_id, logger), daemon=True, ) process.start() self.services[service_id]["process"] = process self.services[service_id]["state"] = ServiceState.STARTING self.services[service_id]["socket"] = self.zmq_context.socket(zmq.REQ) self.services[service_id]["socket"].setsockopt(zmq.LINGER, 0) self.services[service_id]["socket"].setsockopt(zmq.RCVTIMEO, 10000) self.services[service_id]["socket"].connect( self.metadata.services[service_id].uri ) try: asyncio.create_task(self.confirm_state_coroutine(service_id)) except RuntimeError: logger.warning( "Create task to confirm service state failed." + " Probably asyncio loop is not running." + " Trying to execute it via asyncio.run()" ) asyncio.run(self.confirm_state_coroutine(service_id)) async def confirm_state_coroutine(self, service_id): """Confirm the state of the service.""" request = json.dumps({"jsonrpc": "2.0", "method": "status", "id": 1}) socket = self.services[service_id]["socket"] try: await socket.send_string(request) response = await socket.recv_string() except zmq.Again: self.services[service_id]["state"] = ServiceState.ERROR logger.warning(f"Error in service {service_id}. Process is not responding.") await asyncio.sleep(1) await self.confirm_state_coroutine(service_id) return resp_dict = json.loads(response) if resp_dict["result"] == ServiceState.RUNNING: self.services[service_id]["state"] = ServiceState.RUNNING elif resp_dict["result"] == ServiceState.STARTING: logger.info(f"Service {service_id} responds but still starting") await asyncio.sleep(1) await self.confirm_state_coroutine(service_id) else: logger.warning( f"Service {service_id} failed to start and returned incorrect state." ) self.services[service_id]["state"] = ServiceState.ERROR def stop_service(self, service_id): """Stop the service.""" service_id = self.metadata.resolve_service(service_id, None) self.check_service(service_id) if self.services[service_id]["state"] != ServiceState.RUNNING: raise ValueError(f"Service {service_id} is not running") self.services[service_id]["socket"].close() self.services[service_id]["socket"] = None self.services[service_id]["process"].terminate() self.services[service_id]["process"] = None self.services[service_id]["state"] = ServiceState.STOPPED def restart_service(self, service_id): """Restart the service.""" self.stop_service(service_id) self.start_service(service_id) def check_dependency(self, service_id, dependency): """Check if the service has the dependency.""" service_id = self.metadata.resolve_service(service_id, None) self.metadata.services[service_id].append(dependency) self.metadata.check_dependency_cycles()
[ 37811, 26796, 326, 23986, 1630, 2139, 526, 15931, 201, 198, 6738, 18540, 305, 919, 278, 1330, 10854, 201, 198, 11748, 30351, 952, 201, 198, 11748, 33918, 201, 198, 11748, 1976, 76, 80, 201, 198, 11748, 1976, 76, 80, 13, 292, 13361, 95...
2.211538
3,900
#!/usr/bin/env python """ Vagrant external inventory script. Automatically finds the IP of the booted vagrant vm(s), and returns it under the host group 'vagrant' Example Vagrant configuration using this script: config.vm.provision :ansible do |ansible| ansible.playbook = "./provision/your_playbook.yml" ansible.inventory_file = "./provision/inventory/vagrant.py" ansible.verbose = true end """ # Copyright (C) 2013 Mark Mandel <mark@compoundtheory.com> # 2015 Igor Khomyakov <homyakov@gmail.com> # # This program 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 3 of the License, or # (at your option) any later version. # # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. # # Thanks to the spacewalk.py inventory script for giving me the basic structure # of this. # import sys import os.path import subprocess import re from paramiko import SSHConfig from optparse import OptionParser from collections import defaultdict try: import json except Exception: import simplejson as json from ansible.module_utils._text import to_text from ansible.module_utils.six.moves import StringIO _group = 'vagrant' # a default group _ssh_to_ansible = [('user', 'ansible_ssh_user'), ('hostname', 'ansible_ssh_host'), ('identityfile', 'ansible_ssh_private_key_file'), ('port', 'ansible_ssh_port')] # Options # ------------------------------ parser = OptionParser(usage="%prog [options] --list | --host <machine>") parser.add_option('--list', default=False, dest="list", action="store_true", help="Produce a JSON consumable grouping of Vagrant servers for Ansible") parser.add_option('--host', default=None, dest="host", help="Generate additional host specific details for given host for Ansible") (options, args) = parser.parse_args() # # helper functions # # get all the ssh configs for all boxes in an array of dictionaries. # list all the running boxes # get the ssh config for a single box def get_a_ssh_config(box_name): """Gives back a map of all the machine's ssh configurations""" output = to_text(subprocess.check_output(["vagrant", "ssh-config", box_name]), errors='surrogate_or_strict') config = SSHConfig() config.parse(StringIO(output)) host_config = config.lookup(box_name) # man 5 ssh_config: # > It is possible to have multiple identity files ... # > all these identities will be tried in sequence. for id in host_config['identityfile']: if os.path.isfile(id): host_config['identityfile'] = id return dict((v, host_config[k]) for k, v in _ssh_to_ansible) # List out servers that vagrant has running # ------------------------------ if options.list: ssh_config = get_ssh_config() meta = defaultdict(dict) for host in ssh_config: meta['hostvars'][host] = ssh_config[host] print(json.dumps({_group: list(ssh_config.keys()), '_meta': meta})) sys.exit(0) # Get out the host details # ------------------------------ elif options.host: print(json.dumps(get_a_ssh_config(options.host))) sys.exit(0) # Print out help # ------------------------------ else: parser.print_help() sys.exit(0)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 53, 363, 5250, 7097, 13184, 4226, 13, 17406, 4142, 7228, 262, 6101, 286, 262, 48696, 14334, 5250, 45887, 7, 82, 828, 290, 198, 7783, 82, 340, 739, 262, 2583, 1448, 705, 2...
2.960159
1,255
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # Copyright (c) 2020 TsinghuaAI Authors. # # 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. # Many thanks for following projects. # https://github.com/TsinghuaAI/CPM-Generate # https://github.com/jm12138/CPM-Generate-Paddle import sys import argparse import numpy as np import paddle from paddlenlp.transformers import GPTModel, GPTForGreedyGeneration from paddlenlp.transformers import GPTChineseTokenizer, GPTTokenizer from paddlenlp.utils.log import logger MODEL_CLASSES = { "gpt-cn": (GPTForGreedyGeneration, GPTChineseTokenizer), "gpt": (GPTForGreedyGeneration, GPTTokenizer), } # prediction function # One shot example # dictation poetry if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] == "gpt-cn": demo = Demo("gpt-cn", "gpt-cpm-large-cn") demo.ask_question_cn("苹果的CEO是谁?") demo.dictation_poetry_cn("举杯邀明月,") else: demo = Demo("gpt", "gpt2-medium-en") demo.ask_question_en("Who is the CEO of Apple?")
[ 2, 15069, 357, 66, 8, 33448, 350, 37382, 47, 37382, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 15069, 357, 66, 8, 12131, 309, 12215, 33061, 20185, 46665, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 35...
2.807554
556
""" DotKnot: software for RNA pseudoknot prediction Copyright (C) 2010-2011 Jana Sperschneider This program 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. """ import functions import pk_tools def method(stem_dic_mwis, pk_recursive_dic, bulges_internal, multiloops, best_khps): """ Function: method() Purpose: Maximum weight independent set (MWIS) calculation using the set of secondary structure elements, pseudoknots and kissing hairpins. Hairpin loops may contain inner structure elements. Input: Dictionaries of structure elements. Return: Structure elements in the MWIS. """ crossing_structures, secondary_structures, mwis_dic, candidate_list = {}, {}, {}, [] for stem, values in stem_dic_mwis.items(): if values[3] < 0.0: element = (stem[0], stem[1], values[0], values[1], -1*round(values[3], 2), "hp") candidate_list.append(element) for pk_stem, pk_energy in pk_recursive_dic.items(): element = (pk_stem[0], pk_stem[1], pk_stem[4], pk_stem[7], -1*round(pk_energy[0], 2), "pk", pk_stem[2], pk_stem[3], pk_stem[4], pk_stem[5], pk_stem[6], pk_stem[7], pk_stem[8]) candidate_list.append(element) for stem, values in bulges_internal.items(): element = (stem[0], stem[1], values[0], values[1], -1*round(values[2], 2), "ib") candidate_list.append(element) for stem, values in multiloops.items(): element = (stem[0], stem[1], values[0], values[1], -1*round(values[2], 2), "ml") candidate_list.append(element) for stem, values in best_khps.items(): element = (stem[0], stem[1], values[1], 0.0, -1*round(values[1], 2), "khp") candidate_list.append(element) if candidate_list: candidate_list.sort() sorted_endpoint_list = functions.create_sorted_endpointlist(candidate_list) for endpoint in sorted_endpoint_list: # Scan sorted endpoints list if endpoint[1] == 'r': # If a right endpoint is scanned outer_interval = candidate_list[endpoint[3] - 1] if outer_interval[5] == 'hp': nested, only_hp_ib_ml = find_nested(outer_interval, candidate_list) # MWIS on the set of nested structure elements if nested and only_hp_ib_ml == False: endpoint_list_recursive = functions.create_sorted_endpointlist(nested) result = functions.MWIS(nested, endpoint_list_recursive) # Free energy sum energy = outer_interval[4] for element in result: energy = energy + element[4] # Store updated free energy for outer stem candidate_list[endpoint[3] - 1] = (outer_interval[0], outer_interval[1], outer_interval[2], outer_interval[3], energy, outer_interval[5]) stem = outer_interval[0], outer_interval[1], outer_interval[2] # Store inner structure elements in dictionary mwis_dic[stem] = result # Main MWIS calculation sorted_endpoint_list_recursive = functions.create_sorted_endpointlist(candidate_list) result = functions.MWIS(candidate_list, sorted_endpoint_list_recursive) # Free energy sum energy = sum([item[4] for item in result]) # Search for detected pseudoknots and kissing hairpins for element in result: if element[5] == 'khp' or element[5] == 'pk': crossing_structures[element] = element[4] if element[5] == 'hp' or element[5] == 'ib' or element[5] == 'ml': secondary_structures[element] = element[4] if element[5] == 'hp': # Hairpin loop can have nested elements crossing_structures, secondary_structures = print_recursive(element, mwis_dic, crossing_structures, secondary_structures) return mwis_dic, crossing_structures, secondary_structures def find_nested(interval, candidate_list): """ Function: find_nested() Purpose: Function for finding nested intervals, given an outer interval. Outer stem is a hairpin loop. Watch out for special case of inner nested pseudoknot. Input: Outer interval and set of candidate intervals. Return: Nested intervals and marker which indicates whether pseudoknots are in the interval set. """ only_hp_ib_ml = True result = [] interval_left = interval[0] + interval[2] interval_right = interval[1] - interval[2] for compare_interval in candidate_list: if compare_interval[0] >= interval_left: if compare_interval[1] <= interval_right: # Special case for nested pseudoknot # Add one base to each side as a safeguard # {{{.(((..[[[.)))....]]].}}} if compare_interval[5] == 'pk': if compare_interval[0] > interval_left: if compare_interval[1] < interval_right: result.append(compare_interval) only_hp_ib_ml = False else: result.append(compare_interval) if compare_interval[5] == 'khp': only_hp_ib_ml = False return result, only_hp_ib_ml def print_recursive(element, mwis_dic, crossing_structures, secondary_structures): """ Function: print_recursive() Purpose: Given the MWIS result, look for nested pseudoknots, kissing hairpins and secondary structures recursively. Store free energy information. Input: Outer structure and set of candidate structures. Return: Nested structures with free energies. """ structure = element[0], element[1], element[2] if structure in mwis_dic: stem_internal_list = mwis_dic[element[0], element[1], element[2]] for item in stem_internal_list: if item[5] == 'khp' or item[5] == 'pk': crossing_structures[item] = item[4] if item[5] == 'hp' or item[5] == 'ib' or item[5] == 'ml': secondary_structures[item] = item[4] if item[5] == 'hp': substructure = item[0], item[1], item[2] if substructure in mwis_dic: crossing_structures, secondary_structures = print_recursive(substructure, mwis_dic, crossing_structures, secondary_structures) return crossing_structures, secondary_structures def pk_khp_structures(seq, crossing_structures, best_khps, stem_dic, bulges_internal, multiloops, pk_recursive_dic, pk_dic_ib): """ Function: pk_khp_structures() Purpose: Obtain dot-bracket notation for set of pseudoknots, with kissing hairpins. Input: Dictionaries of structure elements. Return: Pseudoknots and kissing hairpins in dot-bracket notation. """ pseudoknot_list = [] for pk in crossing_structures: if pk[5] == 'khp': i, n = pk[0], pk[1] energy = pk[2] for khp, khp_value in best_khps.items(): if khp_value[0][0][0] == i and khp_value[0][4][1] == n and khp_value[1] == energy: kissing_hairpin = khp_value[0] value = khp_value[1:] i, j, stemlength1 = kissing_hairpin[0][0], kissing_hairpin[0][1], kissing_hairpin[1] k, l, stemlength2 = kissing_hairpin[2][0], kissing_hairpin[2][1], kissing_hairpin[3] m, n, stemlength3 = kissing_hairpin[4][0], kissing_hairpin[4][1], kissing_hairpin[5] # Find the recursive structure elements recursive_loop1 = value[1] recursive_loop2 = value[2] recursive_loop3 = value[3] recursive_loop4 = value[4] recursive_loop5 = value[5] l1 = kissing_hairpin[2][0] - (kissing_hairpin[0][0] + kissing_hairpin[1]) l2 = (kissing_hairpin[0][1] - kissing_hairpin[1]) - (kissing_hairpin[2][0] + kissing_hairpin[3]) + 1 l3 = kissing_hairpin[4][0] - (kissing_hairpin[0][1] + 1) l4 = (kissing_hairpin[2][1] - kissing_hairpin[3]) - (kissing_hairpin[4][0] + kissing_hairpin[5]) + 1 l5 = (kissing_hairpin[4][1] - kissing_hairpin[5]) - kissing_hairpin[2][1] pk_seq = seq[int(i-1):int(n)] pk_structure = ['(' for x in xrange(stemlength1)] pk_structure = pk_structure + ['.' for x in xrange(l1)] pk_structure = pk_structure + ['[' for x in xrange(stemlength2)] pk_structure = pk_structure + ['.' for x in xrange(l2)] pk_structure = pk_structure + [')' for x in xrange(stemlength1)] pk_structure = pk_structure + ['.' for x in xrange(l3)] pk_structure = pk_structure + ['(' for x in xrange(stemlength3)] pk_structure = pk_structure + ['.' for x in xrange(l4)] pk_structure = pk_structure + [']' for x in xrange(stemlength2)] pk_structure = pk_structure + ['.' for x in xrange(l5)] pk_structure = pk_structure + [')' for x in xrange(stemlength3)] # Now add recursive structure elements if recursive_loop1: pk_structure = pk_tools.add_recursive_elements(i, recursive_loop1, pk_structure, stem_dic, bulges_internal, multiloops) if recursive_loop2: pk_structure = pk_tools.add_recursive_elements(i, recursive_loop2, pk_structure, stem_dic, bulges_internal, multiloops) if recursive_loop3: pk_structure = pk_tools.add_recursive_elements(i, recursive_loop3, pk_structure, stem_dic, bulges_internal, multiloops) if recursive_loop4: pk_structure = pk_tools.add_recursive_elements(i, recursive_loop4, pk_structure, stem_dic, bulges_internal, multiloops) if recursive_loop5: pk_structure = pk_tools.add_recursive_elements(i, recursive_loop5, pk_structure, stem_dic, bulges_internal, multiloops) pk_structure = ''.join(pk_structure) pseudoknot = [pk[0], pk[1], -1*float(pk[4]), pk[5], pk_seq, pk_structure] pseudoknot_list.append(pseudoknot) if pk[5] == 'pk': i, j, stemlength1 = pk[6], pk[7], pk[8] k, l, stemlength2 = pk[9], pk[10], pk[11] marker = pk[12] key = i, l, i, j, stemlength1, k, l, stemlength2, marker energy = round(pk_recursive_dic[key][0],2) recursive_loop1 = pk_recursive_dic[key][1] recursive_loop2 = pk_recursive_dic[key][2] recursive_loop3 = pk_recursive_dic[key][3] looplength1 = k - (i + stemlength1) looplength2 = (j - stemlength1 + 1) - (k + stemlength2) looplength3 = (l - stemlength2) - j pk_seq = seq[int(i-1):int(l)] if marker == 'r': # Now assemble the core pseudoknot structure with regular stems pk_structure = ['(' for x in xrange(stemlength1)] pk_structure = pk_structure + ['.' for x in xrange(looplength1)] pk_structure = pk_structure + ['[' for x in xrange(stemlength2)] pk_structure = pk_structure + ['.' for x in xrange(looplength2)] pk_structure = pk_structure + [')' for x in xrange(stemlength1)] pk_structure = pk_structure + ['.' for x in xrange(looplength3)] pk_structure = pk_structure + [']' for x in xrange(stemlength2)] else: # Case 1: stem S1 is interrupted if marker == 'iS1': stem1 = i, j structure_stem1 = bulges_internal[stem1][1] # Delete dangling ends ':' structure_stem1 = structure_stem1.replace(':','') pk_structure = list(structure_stem1) start = k - i for x in xrange(stemlength2): pk_structure = pk_structure[0:start] + list('[') + pk_structure[start+1:] start = start + 1 pk_structure = pk_structure + ['.' for x in xrange(looplength3)] pk_structure = pk_structure + [']' for x in xrange(stemlength2)] # Case 2: stem S2 is interrupted, change brackets '(' to '[' and ')' to ']' if marker == 'iS2': stem2 = k, l structure_stem2 = bulges_internal[stem2][1] # Delete dangling ends ':' structure_stem2 = structure_stem2.replace(':','') structure_stem2 = structure_stem2.replace('(','[') structure_stem2 = structure_stem2.replace(')',']') pk_structure = list(structure_stem2) pk_structure = ['.' for x in xrange(looplength1)] + pk_structure pk_structure = ['(' for x in xrange(stemlength1)] + pk_structure end = j - i for x in xrange(stemlength1): pk_structure = pk_structure[0:end] + list(')') + pk_structure[end+1:] end = end - 1 # Now add recursive structure elements if recursive_loop1: pk_structure = pk_tools.add_recursive_elements(i, recursive_loop1, pk_structure, stem_dic, bulges_internal, multiloops) if recursive_loop2: pk_structure = pk_tools.add_recursive_elements(i, recursive_loop2, pk_structure, stem_dic, bulges_internal, multiloops) if recursive_loop3: pk_structure = pk_tools.add_recursive_elements(i, recursive_loop3, pk_structure, stem_dic, bulges_internal, multiloops) pk_structure = ''.join(pk_structure) pseudoknot = [pk[0], pk[1], -1*float(pk[4]), pk[5], pk_seq, pk_structure] pseudoknot_list.append(pseudoknot) pseudoknot_list.sort() return pseudoknot_list def assemble_global_structure(seq, secondary_structures, pseudoknot_list): """ Function: assemble_global_structure() Purpose: Assemble the global structure including pseudoknots. Input: List of predicted pseudoknots and secondary structures. Return: Global structure in dot-bracket notation. """ predicted_global_structure = ['.' for i in xrange(len(seq))] # Insert secondary structure elements if secondary_structures: for element, energy in sorted(secondary_structures.items()): # Insert detected hairpin loops if element[5] == 'hp': structure = ['.' for i in xrange(element[1] - element[0] + 1)] for i in xrange(element[2]): structure[i] = '(' structure[len(structure) - i - 1] = ')' predicted_global_structure[element[0]-1:element[1]] = structure # Insert detected bulge loop, internal loop and multiloop structures else: structure = element[3].replace(':','') predicted_global_structure[element[0]-1:element[1]] = list(structure) # Insert detected pseudoknots and kissing hairpins if pseudoknot_list: for pk in pseudoknot_list: predicted_global_structure[pk[0]-1:pk[1]] = list(pk[5]) predicted_global_structure = ''.join(predicted_global_structure) return predicted_global_structure
[ 37811, 201, 198, 220, 220, 220, 22875, 42, 1662, 25, 3788, 329, 25897, 25038, 482, 1662, 17724, 201, 198, 220, 220, 220, 15069, 357, 34, 8, 3050, 12, 9804, 449, 2271, 1338, 364, 354, 710, 1304, 197, 201, 198, 201, 198, 220, 220, 2...
1.930415
8,910
import re, os def do_get_light_config(value, TelegramResponder): """Light? - Gives you the possible light configurations""" for val in value.values(): if val.strip() == "Light?": if ( "433MHz_Transiever" in TelegramResponder.main.default_values_dict["settings"] ): TelegramResponder.answer += "All possible light configurations: \n\n" for light in TelegramResponder.main.default_values_dict["settings"][ "433MHz_Transiever" ]["Codes"].keys(): TelegramResponder.answer += "{}\n".format(light) else: TelegramResponder.answer += ( "No transiever defined. Cannot do what you asked." ) def do_send_RF_code(value, TelegramResponder): """Switch ConfigName <ON/OFF> - Turns light ON or OFF""" for val in value.values(): light = re.findall(r"Switch\b\s*(\w*)", val) parts = val.split() if light and len(parts) > 2: # Turn on or off if the command is correct if ( "433MHz_Transiever" in TelegramResponder.main.default_values_dict["settings"] ): if ( light[0] in TelegramResponder.main.default_values_dict["settings"][ "433MHz_Transiever" ]["Codes"].keys() ): onoff = 1 if parts[-1].upper() == "ON" else 0 path = os.path.normpath( TelegramResponder.main.default_values_dict["settings"][ "433MHz_Transiever" ]["path"] ) for switch in TelegramResponder.main.default_values_dict[ "settings" ]["433MHz_Transiever"]["Codes"][light[0]]: code = switch cmd = "{} {} {}".format(path, code, onoff) os.system(cmd) if onoff: old_light = TelegramResponder.current_light TelegramResponder.current_light = light[0] else: old_light = None # Because everything is off TelegramResponder.current_light = None # Switch the old one off, which are not included in the new one if old_light and TelegramResponder.settings.get( "Exclusive_Light_Switching", True ): path = os.path.normpath( TelegramResponder.main.default_values_dict["settings"][ "433MHz_Transiever" ]["path"] ) onoff = 0 for switch in TelegramResponder.main.default_values_dict[ "settings" ]["433MHz_Transiever"]["Codes"][old_light]: if ( switch not in TelegramResponder.main.default_values_dict[ "settings" ]["433MHz_Transiever"]["Codes"][ TelegramResponder.current_light ] ): code = switch cmd = "{} {} {}".format(path, code, onoff) os.system(cmd) TelegramResponder.answer += "Done and enjoy." else: TelegramResponder.answer += ( "This light configuration is not defined." ) else: TelegramResponder.answer += ( "No transiever defined. Cannot do what you asked." ) elif light and len(parts) == 2: # if no on or off is defined TelegramResponder.answer = { "CALLBACK": { "info": "Would you like to turn {} ON or OFF".format(light[0]), "keyboard": { "ON": "Switch {} ON".format(light[0]), "OFF": "Switch {} OFF".format(light[0]), }, "arrangement": ["ON", "OFF"], } } elif light and len(parts) == 1: # If just the switch command was send if ( "433MHz_Transiever" in TelegramResponder.main.default_values_dict["settings"] ): keyboard = {} arrangement = [] for light in TelegramResponder.main.default_values_dict["settings"][ "433MHz_Transiever" ]["Codes"]: keyboard[light] = "Switch {}".format(light) arrangement.append([light]) TelegramResponder.answer = { "CALLBACK": { "info": "Possible light configurations:", "keyboard": keyboard, "arrangement": arrangement, } } def send_info(value, TelegramResponder): """Info - Sends some infos to the user""" # create an exporter instance, as an argument give it # the item you wish to export for val in value.values(): # Todo: add the temperature and humidity response if re.findall(r"Info\b\s*", val): text = "Temperature and Humidity: \n\n"
[ 11748, 302, 11, 28686, 628, 198, 4299, 466, 62, 1136, 62, 2971, 62, 11250, 7, 8367, 11, 50203, 19309, 8623, 2599, 198, 220, 220, 220, 37227, 15047, 30, 532, 402, 1083, 345, 262, 1744, 1657, 25412, 37811, 198, 220, 220, 220, 329, 118...
1.758779
3,275
#------------------------------------------------------------------------------- # Name: Raspberry Pi Socket Client # Purpose: # # Author: Vaibhav # # Created: 20/08/2014 # Copyright: (c) Vaibhav 2014 # Licence: <your licence> #------------------------------------------------------------------------------- import socket import sys from datetime import datetime import time server_socket = None ADDRESS = "10.0.0.19" #ADDRESS = "192.168.137.2" #ADDRESS = "127.0.0.1" PORT = 2468 NUM_OF_TIMES = 1000 if __name__ == '__main__': main()
[ 2, 10097, 24305, 201, 198, 2, 6530, 25, 220, 220, 220, 220, 220, 220, 220, 24244, 13993, 47068, 20985, 201, 198, 2, 32039, 25, 201, 198, 2, 201, 198, 2, 6434, 25, 220, 220, 220, 220, 220, 17668, 571, 71, 615, 201, 198, 2, 201, ...
2.817308
208
import copy import getpass import numpy as np import pickle import time import shutil import subprocess import os import random import sys from FGBconstants import * import game_engine, game_graphics, telegram_bot, report channel_name = '@FaedoGuerraBotChannel' print('Username UZ: ', end = '') username = input() password = getpass.getpass() state0 = pickle.load(open(save_file, 'rb')) while 'random_state' not in state0: state0['random_state'] = random.getstate() state0['np_random_state'] = np.random.get_state() print('Simulazione in corso...') state = copy.deepcopy(state0) state['next_iteration'] = time.time() epic_battle = False game_engine.main_loop(state, 0, do_nothing, do_nothing, do_nothing, do_nothing, do_nothing, test_epic_battle) if state['iterations'] <= max_iterations and epic_battle: #if state['iterations'] <= max_iterations: print('La Grande Guerra del Faedo durerà %d turni' % state['iterations']) break print('La simulazione è durata %d turni, %s battaglie epiche' % (state['iterations'], 'con' if epic_battle else 'senza')) del state0['random_state'] del state0['np_random_state'] game_engine.main_loop(state0, 15 * 60, begin_func, end_func, save_func, prep_func, premain_func, main_func) #game_engine.main_loop(state0, 0 * 60, begin_func, end_func, save_func, prep_func, main_func)
[ 11748, 4866, 198, 11748, 651, 6603, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2298, 293, 198, 11748, 640, 198, 11748, 4423, 346, 198, 11748, 850, 14681, 198, 11748, 28686, 198, 11748, 4738, 198, 11748, 25064, 198, 198, 6738, 376, ...
2.714567
508
__author__ = 'ziyan.yin' __version__ = '1.0.2'
[ 834, 9800, 834, 796, 705, 17027, 4121, 13, 88, 259, 6, 198, 834, 9641, 834, 796, 705, 16, 13, 15, 13, 17, 6, 198 ]
1.958333
24
import numpy as np import os from bfieldtools import kicad_io from bfieldtools.utils import load_example_mesh from .test_mesh_conductor import _fake_mesh_conductor, _fake_streamfunction import pytest
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 6738, 275, 3245, 31391, 1330, 479, 291, 324, 62, 952, 198, 6738, 275, 3245, 31391, 13, 26791, 1330, 3440, 62, 20688, 62, 76, 5069, 198, 198, 6738, 764, 9288, 62, 76, 5069, 62, 1...
3.123077
65
"""Unsorted Table Map Implementation.""" from MapBase import MapBase class UnsortedTableMap(MapBase): """ Class that relies on storing key-value pairs in arbitrary order within a Python list. """ def __init__(self): """Initialize the unsorted list.""" self._table = [] def __getitem__(self, k): """ O(n) time complexity. :type key k :rtype value associated with key k """ for item in item._table: if k == item._key: return item._value # Item not found raise KeyError("Key Error: " + repr(k)) def __setitem__(self, k, v): """ Set value v to key k, overwriting existing value if present. O(n) time complexity. :type key k :type value v :rtype None """ for item in self._table: if k == item._key: item._value = v return # Add new Item class instance containing key, value pair. self._table.append(self._Item(k,v)) def __delitem__(self, k): """ Remove item associated with key k. O(n) time complexity. :type key k :error KeyError when key k not found. """ for j in range(len(self._table)): # key found in table. if k == self._table[j]._key: # Remove the item self._table.pop(j) return raise KeyError("Key Error: " + repr(k)) def __len__(self): """Get the size of the table.""" """ :rtype table size """ return len(self._table) def __repr__(self): """Print the table.""" return '\n'.join(str(item) for item in self._table) def __iter__(self): """Generate iteration of map's keys.""" for item in self._table: # yields the a map's key. yield item._key if __name__=="__main__": unsortedmap = UnsortedTableMap() unsortedmap[4] = 'hello' unsortedmap[5] = 'world' unsortedmap[8] = 'joe' print(len(unsortedmap)) print(unsortedmap) del unsortedmap[4] it = iter(unsortedmap) print(next(it)) print(next(it))
[ 37811, 3118, 82, 9741, 8655, 9347, 46333, 526, 15931, 198, 6738, 9347, 14881, 1330, 9347, 14881, 198, 198, 4871, 791, 82, 9741, 10962, 13912, 7, 13912, 14881, 2599, 198, 220, 37227, 198, 220, 5016, 326, 16507, 319, 23069, 1994, 12, 8367...
2.485643
801
# coding=utf8 import warnings import numpy as np class AbstractSVMKernel(object): ''' 核函数类的基类, 计算核函数与内积 ''' class LinearKernel(AbstractSVMKernel): ''' 线性核函数类 np.dot(xi.T, xj) ''' def __call__(self, xi, xj): ''' 线性核内积 np.dot(xi, xj.T) ''' return np.dot(xi, xj.T) class RBFKernel(AbstractSVMKernel): ''' RBF核函数类 exp(-gamma * L2norm(xi-xj)) ''' def __init__(self, **kernel_params): ''' RBF核参数 gamma: 默认值为 (1 / k), k 为类别数, 由Kernel类计算 缺省值 0.1 ''' self.gamma = kernel_params.get('gamma', 0.1) def __call__(self, xi, xj): ''' RBF核函数内积 np.exp(-gamma * L2norm(xi-xj)) 这里指定 axis=-1 为了兼容 xj 为训练数据矩阵和 xj 为向量2中情况 ''' return np.exp(-self.gamma * np.linalg.norm(xi - xj, ord=2, axis=-1)) class PolynomialKernal(AbstractSVMKernel): ''' 多项式核函数类 (gamma * np.dot(xi.T, xj) + r)**d ''' def __init__(self, **kernel_params): ''' 多项式核参数 gamma: 默认值 (1 / k), k 为类别数, 由Kernel类计算 缺省值 0.1 d: 多项式核的最高次数 默认值 3 缺省值 3 r: 相关系数coefficient 默认值 0 缺省值 0 ''' self.gamma = kernel_params.get('gamma', 0.1) self.d = kernel_params.get('d', 3) self.r = kernel_params.get('r', 0) def __call__(self, xi, xj): ''' 多项式核内积 (gamma * np.dot(xi.T, xj) + r)**d ''' return (self.gamma * np.dot(xi, xj.T) + self.r)**self.d class SigmoidKernel(AbstractSVMKernel): ''' Sigmoid核函数 注意: Sigmoid核采用的是tanh函数 tanh(gamma * np.dot(xi, xj.T) + r) ''' def __init__(self, **kernel_params): ''' Sigmoid核参数 gamma: 默认值 (1 / k), k 为类别数, 由Kernel类计算 缺省值 0.1 r: 相关系数coefficient 默认值 0 缺省值 0 ''' self.gamma = kernel_params.get('gamma', 0.1) self.r = kernel_params.get('r', 0) def __call__(self, xi, xj): ''' Sigmoid核内积 tanh(gamma * np.dot(xi.T, xj) + r) ''' return np.tanh(self.gamma * np.dot(xi, xj.T) + self.r) def kernel(kernel_name=None, **kernel_params): ''' 根据指定参数返回核函数实例 ''' name2kernel = { None: LinearKernel, 'linear': LinearKernel, 'rbf': RBFKernel, 'poly': PolynomialKernal, 'sigmoid':SigmoidKernel, } assert kernel_name is None or \ (kernel_name.lower() in name2kernel.keys()),\ f"invalid kernel: '{str(kernel_name)}'." + "\n" \ "The following kernels are supported:\n" + f"{list(name2kernel.keys())}" if ('gamma' not in kernel_params and kernel_name in ['rbf', 'poly', 'sigmoid']): if 'y' in kernel_params: kernel_params['gamma'] = 1 / len(set(kernel_params['y'])) kernel_params.pop('y') else: warnings.warn("No label or gamma found, using default value for gamma...") return name2kernel.get(kernel_name, LinearKernel)(**kernel_params)
[ 2, 19617, 28, 40477, 23, 201, 198, 11748, 14601, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 201, 198, 4871, 27741, 50, 15996, 42, 7948, 7, 15252, 2599, 201, 198, 220, 220, 220, 705, 7061, 201, 198, 220, 220, 220, 10545, 254,...
1.474989
2,219
from datetime import datetime from blog import db
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 4130, 1330, 20613, 628, 198 ]
3.785714
14
""" Module for managing the IRIS dataset """ import numpy as np from .Dataset import Dataset DATASET_SIZE = 15 class TwoByTwoLines(Dataset): """ This class manage the dataset , properties of the datasets are uniquely determined by the params dictionary It compares the parameters and complete them with the default one. It then return a unique id identifier """ default_params = { 'size': 2, 'pm_one': True } classification = False # true if implemented_params_keys = ['dataName'] # all the admitted keys @staticmethod def dataset_id(params): """ This method interprets the parameters and generate an id """ TwoByTwoLines.check_params_impl(params) id = '2by2' if params['size'] != 2: id += '-sz%d' % params['size'] if not params['pm_one']: id += '-pm%d' % int(params['pm_one']) return id ''' @property def output_size(self): return 10 if self._params['classes'] == () else len(self._params['classes']) ''' @property @property # Likelihood always returns the patterns as 0,1, not -1,1 @property @staticmethod
[ 37811, 198, 26796, 329, 11149, 262, 14826, 1797, 27039, 198, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 764, 27354, 292, 316, 1330, 16092, 292, 316, 198, 198, 35, 1404, 1921, 2767, 62, 33489, 796, 1315, 628, 198, ...
2.525667
487
import atexit from IPython.display import display from ipywidgets.widgets import * from traitlets import Unicode, List, Bool, Int, Dict from qcodes.widgets import display_auto
[ 11748, 379, 37023, 198, 6738, 6101, 7535, 13, 13812, 1330, 3359, 198, 6738, 20966, 88, 28029, 11407, 13, 28029, 11407, 1330, 1635, 198, 6738, 1291, 2578, 912, 1330, 34371, 11, 7343, 11, 347, 970, 11, 2558, 11, 360, 713, 198, 198, 6738...
3.396226
53
N = int(input()) lang = set(input().split()) one = set(lang) alll = set(lang) for i in range(N - 1): lang = set(input().split()) one |= lang alll &= lang print(alll) print(one)
[ 45, 796, 493, 7, 15414, 28955, 198, 17204, 796, 900, 7, 15414, 22446, 35312, 28955, 198, 505, 796, 900, 7, 17204, 8, 198, 282, 297, 796, 900, 7, 17204, 8, 198, 1640, 1312, 287, 2837, 7, 45, 532, 352, 2599, 198, 220, 220, 220, 42...
2.333333
81
# -*- coding: utf-8 -*- # Copyright© 1986-2018 Altair Engineering Inc. """Module with the pkr environment""" import yaml from builtins import object from .utils import HashableDict, ensure_definition_matches, get_pkr_path, merge ENV_FOLDER = 'env' class Environment(object): """Class for loading and holding pkr environment""" IMPORT_KEY = 'import' DEFAULT_TEMPLATE_DIR = 'templates/dockerfiles' def _load_env_file(self, path): """Load an environment with its dependencies recursively""" with path.open() as env_file: content = yaml.safe_load(env_file) if content is None: return {} for imp_name in content.get(self.IMPORT_KEY, ()): imp_path = self.path / (imp_name + '.yml') imp_data = self._load_env_file(imp_path) imp_data.pop(self.IMPORT_KEY, None) content = merge(content, imp_data) return content def get_meta(self, extra): """Ensure that all metadata are present""" default = self.env.get('default_meta') if not default: # This prevent an empty value in the YAML default = {} ret = default.copy() merge(extra, ret) required_values = ensure_definition_matches( definition=self.env.get('required_meta', []), defaults=ret, data=extra ) or {} merge(required_values, ret) # Feature ret['features'] = self.env.get('default_features', []) return ret @property def default_path(self): """Return the default path""" return self.pkr_path / ENV_FOLDER def _containers(self, template=False): """Method for fetching the containers dict as the schema might evolve. Args: - template: a bool specifying if templates should be returned """ containers = self.env['containers'] if template: return containers if not containers: return {} return {name: value for name, value in containers.items() if value and not value.get('template', False)} @property def context_dir(self): """Return the context folder name""" return self.env['context_dir'] @property def context_template_dir(self): """Return the template folder name""" return self.env.get('context_template_dir', self.DEFAULT_TEMPLATE_DIR) def get_container(self, name=None): """Return a compiled dictionary representing a container, or a list of all if name is not specified. Args: - name: the name of the container to retrieve """ if name is None: ret = {} for c_name, cont in self._containers().items(): if not cont.get('template', False): ret[c_name] = self.get_container(c_name) return ret container = self._containers(template=True)[name] or {} if 'parent' in container and container['parent'] is not None: parent = self.get_container(container['parent']) return merge(container, parent.copy()) return container def get_requires(self, containers=None): """Returns a list of required files for the provided containers. The result is returned as a list of dicts with 3 values: origin, src and dst. Args: - containers: a list of containers name """ if containers is None: containers = list(self._containers().keys()) requirements = {} # We first put them in a dict containing sets to avoid having doubles for name in containers: env = self.get_container(name) for key, value in env.get('requires', {}).items(): dst_set = requirements.get(key, set()) dst_set.add(HashableDict(value)) requirements[key] = dst_set # then we transform it to a list of dicts ret = [] for key, values in requirements.items(): for value in values: item = {'origin': key} item.update(value) ret.append(item) return ret
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 16224, 12113, 12, 7908, 12344, 958, 14044, 3457, 13, 198, 198, 37811, 26796, 351, 262, 279, 38584, 2858, 37811, 198, 198, 11748, 331, 43695, 198, 6738, 3170, 1...
2.34647
1,827
# TODO: write proper tests if __name__ == "__main__": test_reconstruction()
[ 2, 16926, 46, 25, 3551, 1774, 5254, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 628, 220, 220, 220, 1332, 62, 260, 9979, 2762, 3419, 198 ]
2.766667
30
from nose.tools import eq_ from pepdata.amino_acid_alphabet import ( canonical_amino_acids, canonical_amino_acid_letters, extended_amino_acids, extended_amino_acid_letters, )
[ 6738, 9686, 13, 31391, 1330, 37430, 62, 198, 6738, 279, 538, 7890, 13, 321, 2879, 62, 46309, 62, 17307, 8380, 1330, 357, 198, 220, 220, 220, 40091, 62, 321, 2879, 62, 330, 2340, 11, 198, 220, 220, 220, 40091, 62, 321, 2879, 62, 46...
2.546667
75
# -*- coding: utf-8 -*- """ tuesmon_ncurses.ui.views.projects ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ import functools import urwid from tuesmon_ncurses.ui.widgets import generic, projects from . import base from .backlog import ProjectBacklogSubView from .milestones import ProjectMilestoneSubView from .issues import ProjectIssuesSubView from .wiki import ProjectWikiSubView
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 83, 947, 2144, 62, 10782, 46998, 13, 9019, 13, 33571, 13, 42068, 198, 27156, 15116, 8728, 4907, 93, 198, 37811, 198, 198, 11748, 1257, 310, 10141, 198, ...
3.293103
116
MonoUpnpPackage ()
[ 198, 9069, 78, 4933, 37659, 27813, 7499, 198 ]
2.5
8
import ftplib
[ 11748, 10117, 489, 571, 198, 220, 220, 220, 220, 220, 220, 220, 220 ]
1.692308
13
# coding: UTF-8 from FreeCAD import Console, Placement, Rotation, Vector import Part import Sketcher from Legify.Common import *
[ 2, 19617, 25, 41002, 12, 23, 198, 198, 6738, 3232, 34, 2885, 1330, 24371, 11, 1345, 5592, 11, 371, 14221, 11, 20650, 198, 11748, 2142, 198, 11748, 3661, 316, 2044, 198, 6738, 3564, 1958, 13, 17227, 1330, 1635, 628 ]
3.358974
39
import time from poium.common import logging from poium.settings import Setting from poium.processing import processing, screenshots_name from poium.common.assert_des import insert_assert LOCATOR_LIST = [ "id", "name", "text", "nameContains", "label", "xpath", "labelContains", "className", "predicate", "classChain" ]
[ 11748, 640, 198, 6738, 745, 1505, 13, 11321, 1330, 18931, 198, 6738, 745, 1505, 13, 33692, 1330, 25700, 198, 6738, 745, 1505, 13, 36948, 1330, 7587, 11, 23322, 62, 3672, 198, 6738, 745, 1505, 13, 11321, 13, 30493, 62, 8906, 1330, 7550...
2.708955
134
import tensorflow as tf import numpy as np from zfit import ztypes from zfit_benchmark.timer import Timer import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import inspect from decimal import Decimal from scipy.interpolate import UnivariateSpline from tf_kde.benchmark import distributions as available_distributions from tf_kde.benchmark import methods as available_methods sns.set() sns.set_context("paper") plt.rc('axes', titlesize=8) plt.rc('axes', labelsize=6) plt.rc('xtick', labelsize=6) plt.rc('ytick', labelsize=6) plt.rc('legend', fontsize=6) plt.rc('figure', titlesize=8) colormap = plt.get_cmap('gist_rainbow') method_count = 0 method_colors = { 'actual': colormap(0) } for method in inspect.getmembers(available_methods, inspect.isclass): method_count += 1 method_index = 1 for method, cls in inspect.getmembers(available_methods, inspect.isclass): method_colors[method] = colormap(1.*method_index/method_count) method_index += 1
[ 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1976, 11147, 1330, 1976, 19199, 198, 6738, 1976, 11147, 62, 26968, 4102, 13, 45016, 1330, 5045, 263, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355,...
2.774373
359
if __name__ == '__main__': print(MyClass.__dict__['var3']) clzz = MyClass() clzz.my_method()
[ 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 3601, 7, 3666, 9487, 13, 834, 11600, 834, 17816, 7785, 18, 6, 12962, 628, 220, 220, 220, 537, 3019, 796, 2011, 9487, 3419, 198, 220, 220, 220, 537, ...
2.14
50
from __future__ import absolute_import from changes.api.base import APIView from changes.models.node import Node
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 6738, 2458, 13, 15042, 13, 8692, 1330, 3486, 3824, 769, 198, 6738, 2458, 13, 27530, 13, 17440, 1330, 19081, 628 ]
3.833333
30
import numpy as np from .single_vec_env import SingleVecEnv import gym.vector from gym.vector.utils import concatenate, iterate, create_empty_array from gym.spaces import Discrete @iterate.register(Discrete)
[ 11748, 299, 32152, 355, 45941, 198, 6738, 764, 29762, 62, 35138, 62, 24330, 1330, 14206, 53, 721, 4834, 85, 198, 11748, 11550, 13, 31364, 198, 6738, 11550, 13, 31364, 13, 26791, 1330, 1673, 36686, 378, 11, 11629, 378, 11, 2251, 62, 28...
3.212121
66
import os from collections import defaultdict full_names = { 'AR': 'Arabic', 'BG': 'Bulgarian', 'CH': 'Mandarin', 'CH_char': 'Mandarin', 'EN': 'English', 'WU': 'Cantonese', 'CR': 'Croatian', 'CZ': 'Czech', 'FR': 'French', 'FR_lexique': 'French', 'FR_prosodylab': 'French', 'GE': 'German', 'GE_prosodylab': 'German', 'HA': 'Hausa', 'JA': 'Japanese', 'KO': 'Korean', 'KO_jamo': 'Korean', 'RU': 'Russian', 'PO': 'Portuguese', 'PL': 'Polish', 'SP': 'Spanish', 'SA': 'Swahili', 'SW': 'Swedish', 'TA': 'Tamil', 'TH': 'Thai', 'TU': 'Turkish', 'VN': 'Vietnamese', 'UA': 'Ukrainian', } root_dir = r'E:\Data\dictionaries\raw' output_dir = r'E:\Data\dictionaries\cleaned' os.makedirs(output_dir, exist_ok=True) for code, land in full_names.items(): if code == 'AR': weird_char_set = ['<', '>', '.', '1', '2', '4', '5', '6', '8', '9', '0'] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'BG': continue weird_char_set = ['a', 'b', 'd', 'e', 'g', 'h', 'i', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's'] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'CH': continue weird_char_set = [] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'CH_char': continue weird_char_set = [] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'CR': continue weird_char_set = ["'"] + [str(x) for x in range(10)] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'CZ': continue weird_char_set = [')', '_', '2'] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'EN': continue weird_char_set = [] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'GE': continue weird_char_set = ['=', '%', '*', '<', ':', '$', '_', '!', '.', '~'] + [str(x) for x in range(10)] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'GE_prosodylab': continue weird_char_set = ['#'] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'FR': continue weird_char_set = [] weird_phone_set = [] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'FR_lexique': continue weird_char_set = ['.'] weird_phone_set = [] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'FR_prosodylab': continue weird_char_set = ['.'] weird_phone_set = [] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'CR': continue weird_char_set = ['#']+ [str(x) for x in range(10)] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'HA': continue weird_char_set = [] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'JA': continue weird_char_set = ['9', '〇', '×', 'A', 'F', 'N', 'T', '・', '%', '&', '(', '+', '0', '1', '2', '3', '4', '5', '7', '8', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y'] weird_phone_set = [] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'KO': continue weird_char_set = ['e', 'i', 'n', 'o', 's'] + [str(x) for x in range(10)] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'KO_jamo': continue weird_char_set = ['e', 'i', 'n', 'o', 's'] + [str(x) for x in range(10)] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'PL': continue weird_char_set = [] + [str(x) for x in range(10)] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'PO': continue weird_char_set = ['�', '$', '&', '+', '.', '/', ':', '<', '>', '_', '`', '}'] + [str(x) for x in range(10)] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'RU': continue weird_char_set = ['c', 'v'] + [str(x) for x in range(10)] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'SA': continue weird_char_set = [] + [str(x) for x in range(10)] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'SP': continue weird_char_set = ['<', '>', '^'] + [str(x) for x in range(10)] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'SW': continue weird_char_set = ['&', '>'] + [str(x) for x in range(10)] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'TH': continue weird_char_set = [',', '.', '<', '>', '"', '-'] + [str(x) for x in range(10)] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'TU': continue weird_char_set = ['%', '&', '+', '.', ';', '=', '̇'] + [str(x) for x in range(10)] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'UA': continue weird_char_set = ['a', 'b', 'e', 'f', 'g', 'i', 'k', 'l', 'n', 'o', 'p', 'r', 's', 'u', 'w', '–'] + [str(x) for x in range(10)] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'VN': continue weird_char_set = ['.'] + [str(x) for x in range(10)] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path) elif code == 'WU': continue weird_char_set = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'a', 'c', 'd', 'e', 'i', 'k', 'n', 'p', 'r', 's', 't', 'w', 'x'] + [str(x) for x in range(10)] weird_phone_set = ['+hGH'] dict_path = os.path.join(root_dir, '{}_dictionary.txt'.format(code)) new = load_file(dict_path) new_path = os.path.join(output_dir, '{}_cleaned.txt'.format(code)) save_dictionary(new, new_path)
[ 11748, 28686, 198, 6738, 17268, 1330, 4277, 11600, 198, 198, 12853, 62, 14933, 796, 1391, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 705, 1503, 10354, 705, 31602, 291, 3256, 198, 220, 220, 220, 2...
1.925908
6,141
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py,md # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.13.3 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + # Uncomment to run the notebook in Colab # # ! pip install -q "wax-ml[complete]@git+https://github.com/eserie/wax-ml.git" # # ! pip install -q --upgrade jax jaxlib==0.1.70+cuda111 -f https://storage.googleapis.com/jax-releases/jax_releases.html # - # %matplotlib inline import io import warnings from collections import defaultdict from pathlib import Path from typing import Any, Callable, NamedTuple, Optional, TypeVar import haiku as hk import jax import jax.numpy as jnp import matplotlib.pyplot as plt import numpy as np import numpy as onp import optax import pandas as pd import plotnine as gg import requests from sklearn.preprocessing import MinMaxScaler from tqdm.auto import tqdm from wax.accessors import register_wax_accessors from wax.compile import jit_init_apply from wax.encode import Encoder from wax.modules import Buffer, FillNanInf, Lag, RollingMean from wax.unroll import unroll print("jax backend {}".format(jax.lib.xla_bridge.get_backend().platform)) jax.devices() # # 🔭 Reconstructing the light curve of stars with LSTM 🔭 # # [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/eserie/wax-ml/blob/main/docs/notebooks/05_reconstructing_the_light_curve_of_stars.ipynb) # Let's take a walk through the stars... # # This notebook is based on the study done in # [this post by Christophe Pere](https://towardsdatascience.com/how-to-use-deep-learning-for-time-series-forecasting-3f8a399cf205) # and the notebook available on # [the authors's github](https://github.com/Christophe-pere/Time_series_RNN). # # We will repeat this study on starlight using the LSTM architecture to predict the observed light flux through time. # # Our LSTM implementation is based on this [notebook from Haiku's github repository](https://github.com/deepmind/dm-haiku/blob/master/examples/haiku_lstms.ipynb). # # We'll see how to use WAX-ML to ease the preparation of time series data stored in dataframes and having Nans # before calling a "standard" deep-learning workflow. # # ## Disclaimer # # Despite the fact that this code works with real data, the results presented here should not be considered as scientific knowledge insights, to the knowledge of the authors of WAX-ML, neither the results nor the data source have been reviewed by an astrophysics pair. # # The purpose of this notebook is only to demonstrate how WAX-ML can be used when applying a "standard" machine learning workflow, here LSTM, to analyze time series. # ## Download the data register_wax_accessors() # + tags=["parameters"] # Parameters STAR = "007609553" SEQ_LEN = 64 BATCH_SIZE = 8 TRAIN_SIZE = 2 ** 16 NUM_EPOCHS = 10 NUM_STARS = None RECORD_FREQ = 100 TOTAL_LEN = None TRAIN_DATE = "2016" CACHE_DIR = Path("./cached_data/") # - # %%time filename = CACHE_DIR / "kep_lightcurves.parquet" try: raw_dataframe = pd.read_parquet(open(filename, "rb")) print(f"data read from {filename}") except FileNotFoundError: # Downloading the csv file from Chrustioge Pere GitHub account download = requests.get( "https://raw.github.com/Christophe-pere/Time_series_RNN/master/kep_lightcurves.csv" ).content raw_dataframe = pd.read_csv(io.StringIO(download.decode("utf-8"))) # set date index raw_dataframe.index = pd.Index( pd.date_range("2009-03-07", periods=len(raw_dataframe.index), freq="h"), name="time", ) # save dataframe locally in CACHE_DIR CACHE_DIR.mkdir(exist_ok=True) raw_dataframe.to_parquet(filename) print(f"data saved in {filename}") # shortening of data to speed up the execution of the notebook in the CI if TOTAL_LEN: raw_dataframe = raw_dataframe.iloc[:TOTAL_LEN] # Let's visualize the description of this dataset: raw_dataframe.describe().T.to_xarray() stars = raw_dataframe.columns stars = sorted(list(set([i.split("_")[0] for i in stars]))) print(f"The number of stars available is: {len(stars)}") print(f"star identifiers: {stars}") dataframe = raw_dataframe[[i + "_rscl" for i in stars]].rename( columns=lambda c: c.replace("_rscl", "") ) dataframe.columns.names = ["star"] dataframe.shape if NUM_STARS: columns = dataframe.columns.tolist() columns.remove(STAR) dataframe = dataframe[[STAR] + columns[: NUM_STARS - 1]] # ## Rolling mean # We will smooth the data by applying a rolling mean with a window of 100 periods. # ### Count nan values # # But before since the dataset has some nan values, we will extract few statistics # about the density of nan values in windows of size 100. # # It will be the occasion to show a usage of the `wax.modules.Buffer` module with the `format_outputs=False` # option for the dataframe accessor `.wax.stream`. # Let's apply the `Buffer` module to the data: buffer, _ = dataframe.wax.stream(format_outputs=False).apply(lambda x: Buffer(100)(x)) assert isinstance(buffer, jnp.ndarray) # Equivalently, we can use wax `unroll` function. buffer = unroll(lambda x: Buffer(100)(x))(jax.device_put(dataframe.values)) # Let's describe the statistic of nans with pandas: count_nan = jnp.isnan(buffer).sum(axis=1) pd.DataFrame(onp.array(count_nan)).stack().describe().astype(int) # ### Computing the rolling mean # We will choose a `min_periods` of 5 in order to keep at leas 75% of the points. # %%time dataframe_mean, _ = dataframe.wax.stream().apply( lambda x: RollingMean(100, min_periods=5)(x) ) dataframe.iloc[:, :2].plot() # ## Forecasting with Machine Learning # # We need two forecast in this data, if you look with attention you'll see micro holes and big holes. T = TypeVar("T") gg.theme_set(gg.theme_bw()) warnings.filterwarnings("ignore") plt.rcParams["figure.figsize"] = 18, 8 fig, (ax, lax) = plt.subplots(ncols=2, gridspec_kw={"width_ratios": [4, 1]}) dataframe.plot(ax=ax, title="raw data") ax.legend(bbox_to_anchor=(0, 0, 1, 1), bbox_transform=lax.transAxes) lax.axis("off") plt.rcParams["figure.figsize"] = 18, 8 fig, (ax, lax) = plt.subplots(ncols=2, gridspec_kw={"width_ratios": [4, 1]}) dataframe_mean.plot(ax=ax, title="Smoothed data") ax.legend(bbox_to_anchor=(0, 0, 1, 1), bbox_transform=lax.transAxes) lax.axis("off") # - # ### Normalize data dataframe_mean.stack().hist(bins=100, log=True) # - scaler = min_max_scaler(dataframe_mean) dataframe_normed = scaler.encode(dataframe_mean) assert (scaler.decode(dataframe_normed) - dataframe_mean).stack().abs().max() < 1.0e-4 dataframe_normed.stack().hist(bins=100) # ### Prepare train / validation datasets # + # split_feature_target(dataframe) # - TRAIN_SIZE print(f"Look at star: {STAR}") train, valid = split_train_validation(dataframe_normed[[STAR]], TRAIN_SIZE, SEQ_LEN) train[0].shape, train[1].shape, valid[0].shape, valid[1].shape # TRAIN_SIZE, VALID_SIZE = len(train.x), len(valid.x) print( f"effective train_size = {len(train.x)}, " f"effective valid size= {len(valid.x)}" ) # Plot an observation/target pair. rng = jax.random.PRNGKey(42) batch_plot = jax.random.choice(rng, len(train[0])) df = pd.DataFrame( {"x": train.x[batch_plot, :, 0], "y": train.y[batch_plot, :, 0]} ).reset_index() df = pd.melt(df, id_vars=["index"], value_vars=["x", "y"]) plot = ( gg.ggplot(df) + gg.aes(x="index", y="value", color="variable") + gg.geom_line() + gg.scales.scale_y_log10() ) _ = plot.draw() # ### Dataset iterator class Dataset: """An iterator over a numpy array, revealing batch_size elements at a time.""" # + [markdown] colab_type="text" id="LZGw5Jdvjmqh" # ### Training an LSTM # # To train the LSTM, we define a Haiku function which unrolls the LSTM over the input sequence, generating predictions for all output values. The LSTM always starts with its initial state at the start of the sequence. # # The Haiku function is then transformed into a pure function through `hk.transform`, and is trained with Adam on an L2 prediction loss. # + colab={} colab_type="code" id="nacnTj5ejIK5" def unroll_net(seqs: jnp.ndarray): """Unrolls an LSTM over seqs, mapping each output to a scalar.""" # seqs is [T, B, F]. core = hk.LSTM(32) batch_size = seqs.shape[0] outs, state = hk.dynamic_unroll( core, seqs, core.initial_state(batch_size), time_major=False ) # We could include this Linear as part of the recurrent core! # However, it's more efficient on modern accelerators to run the linear once # over the entire sequence than once per sequence element. return hk.BatchApply(hk.Linear(1))(outs), state # + colab={} colab_type="code" id="nacnTj5ejIK5" model = jit_init_apply(hk.transform(unroll_net)) # + @jax.jit # + colab={} colab_type="code" id="nacnTj5ejIK5" def train_model( model_with_loss: Callable, train_ds: Dataset, valid_ds: Dataset, max_iterations: int = -1, rng=None, record_freq=100, ) -> hk.Params: """Initializes and trains a model on train_ds, returning the final params.""" opt = optax.adam(1e-3) model_with_loss = jit_init_apply(hk.transform(model_with_loss)) @jax.jit # Initialize state. records = defaultdict(list) train_state = init() with tqdm(total=max_iterations if max_iterations > 0 else None) as pbar: while True: try: x, y = next(train_ds) except StopIteration: return train_state, _format_results(records) train_state = update(train_state, x, y) if train_state.step % record_freq == 0: x, y = next(valid_ds) if rng is not None: (rng,) = jax.random.split(rng, 1) valid_loss = model_with_loss.apply(train_state.params, rng, x, y) records["step"].append(train_state.step) records["valid_loss"].append(valid_loss) records["train_loss"].append(train_state.loss) pbar.update() if max_iterations > 0 and train_state.step >= max_iterations: return train_state, _format_results(records) # + colab={} colab_type="code" id="AssgDctokbl5" # %%time train, valid = split_train_validation(dataframe_normed[[STAR]], TRAIN_SIZE, SEQ_LEN) train_ds = Dataset(train, BATCH_SIZE) valid_ds = Dataset(valid, BATCH_SIZE) train_state, records = train_model( model_with_loss, train_ds, valid_ds, len(train.x) // BATCH_SIZE * NUM_EPOCHS, rng=jax.random.PRNGKey(42), record_freq=RECORD_FREQ, ) # + # train_state.params # - # Plot losses losses = pd.DataFrame(records) df = pd.melt(losses, id_vars=["step"], value_vars=["train_loss", "valid_loss"]) plot = ( gg.ggplot(df) + gg.aes(x="step", y="value", color="variable") + gg.geom_line() + gg.scales.scale_y_log10() ) _ = plot.draw() # + [markdown] colab_type="text" id="yr7jrOL3ki-b" # ### Sampling # # The point of training models is so that they can make predictions! How can we generate predictions with the trained model? # # If we're allowed to feed in the ground truth, we can just run the original model's `apply` function. # + colab={} colab_type="code" id="f2qETEqXLT1N" # + colab={} colab_type="code" id="KOuK1egilGD0" # Grab a sample from the validation set. sample_x, sample_y = next(valid_ds) sample_x = sample_x[:1] # Shrink to batch-size 1. sample_y = sample_y[:1] # Generate a prediction, feeding in ground truth at each point as input. predicted, _ = model.apply(train_state.params, None, sample_x) plot = plot_samples(sample_y, predicted) plot.draw() del sample_x, predicted # - # ### Run autoregressively # + [markdown] colab_type="text" id="tDyGshz_lwrM" # If we can't feed in the ground truth (because we don't have it), we can also run the model autoregressively. # + colab={} colab_type="code" id="Cg8oQ75Ulvld" def autoregressive_predict( trained_params: hk.Params, context: jnp.ndarray, seq_len: int, pbar=False, ): """Given a context, autoregressively generate the rest of a sine wave.""" ar_outs = [] context = jax.device_put(context) times = onp.arange(seq_len - context.shape[1] + 1) if pbar: times = tqdm(times) for _ in times: full_context = jnp.concatenate([context] + ar_outs, axis=1) outs, _ = model.apply(trained_params, None, full_context) # Append the newest prediction to ar_outs. ar_outs.append(outs[:, -1:, :]) # Return the final full prediction. return outs # + colab={} colab_type="code" id="Cg8oQ75Ulvld" sample_x, sample_y = next(valid_ds) sample_x = sample_x[:1] # Shrink to batch-size 1. sample_y = sample_y[:1] # Shrink to batch-size 1. context_length = SEQ_LEN // 8 print(f"context_length = {context_length}") # Cut the batch-size 1 context from the start of the sequence. context = sample_x[:, :context_length] # + colab={} colab_type="code" id="Cg8oQ75Ulvld" # %%time # We can reuse params we got from training for inference - as long as the # declaration order is the same. predicted = autoregressive_predict(train_state.params, context, SEQ_LEN, pbar=True) # - sample_y.shape, predicted.shape # + colab={} colab_type="code" id="Cg8oQ75Ulvld" plot = plot_samples(sample_y, predicted) plot += gg.geom_vline(xintercept=context.shape[1], linetype="dashed") _ = plot.draw() # + [markdown] colab_type="text" id="qGkr2gf2oALo" # #### Sharing parameters with a different function. # # Unfortunately, this is a bit slow - we're doing O(N^2) computation for a sequence of length N. # # It'd be better if we could do the autoregressive sampling all at once - but we need to write a new Haiku function for that. # # We're in luck - if the Haiku module names match, the same parameters can be used for multiple Haiku functions. # # This can be achieved through a combination of two techniques: # # 1. If we manually give a unique name to a module, we can ensure that the parameters are directed to the right places. # 2. If modules are instantiated in the same order, they'll have the same names in different functions. # # Here, we rely on method #2 to create a fast autoregressive prediction. # + colab_type="text" id="qGkr2gf2oALo" @hk.transform def fast_autoregressive_predict_fn(context, seq_len): """Given a context, autoregressively generate the rest of a sine wave.""" core = hk.LSTM(32) dense = hk.Linear(1) state = core.initial_state(context.shape[0]) # Unroll over the context using `hk.dynamic_unroll`. # As before, we `hk.BatchApply` the Linear for efficiency. context_outs, state = hk.dynamic_unroll( core, context, state, time_major=False, ) context_outs = hk.BatchApply(dense)(context_outs) # Now, unroll one step at a time using the running recurrent state. ar_outs = [] x = context_outs[:, -1, :] times = range(seq_len - context.shape[1]) for _ in times: x, state = core(x, state) x = dense(x) ar_outs.append(x) ar_outs = jnp.stack(ar_outs) ar_outs = ar_outs.transpose(1, 0, 2) return jnp.concatenate([context_outs, ar_outs], axis=1) fast_autoregressive_predict = jax.jit( fast_autoregressive_predict_fn.apply, static_argnums=(3,) ) # + colab={} colab_type="code" id="WdKcHr6_n_ba" # %%time # Reuse the same context from the previous cell. predicted = fast_autoregressive_predict(train_state.params, None, context, SEQ_LEN) # + colab={} colab_type="code" id="WdKcHr6_n_ba" # The plots should be equivalent! plot = plot_samples(sample_y, predicted) plot += gg.geom_vline(xintercept=context.shape[1], linetype="dashed") _ = plot.draw() # - # # Sample trajectories # + colab={} colab_type="code" id="WdKcHr6_n_ba" sample_x, sample_y = next(valid_ds) sample_x = sample_x[:1] # Shrink to batch-size 1. sample_y = sample_y[:1] # Shrink to batch-size 1. context_length = SEQ_LEN // 8 print(f"context_length = {context_length}") # Cut the batch-size 1 context from the start of the sequence. context = sample_x[:, :context_length] # Reuse the same context from the previous cell. predicted = fast_autoregressive_predict(train_state.params, None, context, SEQ_LEN) # The plots should be equivalent! plot = plot_samples(sample_y, predicted) plot += gg.geom_vline(xintercept=context.shape[1], linetype="dashed") _ = plot.draw() # - # ## timeit # + colab={} colab_type="code" id="9S0tkPXGrU3a" # %timeit autoregressive_predict(train_state.params, context, SEQ_LEN) # %timeit fast_autoregressive_predict(train_state.params, None, context, SEQ_LEN) # - # ## Train all stars # ### Training # %%time train, valid = split_train_validation_date(dataframe_normed, TRAIN_DATE, SEQ_LEN) print(f"effective train size = {train[0].shape[1]}") train[0].shape, train[1].shape, valid[0].shape, valid[1].shape train_ds = Dataset(train, BATCH_SIZE) valid_ds = Dataset(valid, BATCH_SIZE) # del train, valid # Don't leak temporaries. # %%time train_state, records = train_model( model_with_loss, train_ds, valid_ds, len(train.x) // BATCH_SIZE * 1, jax.random.PRNGKey(42), record_freq=RECORD_FREQ, ) # Plot losses losses = pd.DataFrame(records) df = pd.melt(losses, id_vars=["step"], value_vars=["train_loss", "valid_loss"]) plot = ( gg.ggplot(df) + gg.aes(x="step", y="value", color="variable") + gg.geom_line() + gg.scales.scale_y_log10() ) _ = plot.draw() # ### Sampling # + # Grab a sample from the validation set. sample_x, sample_y = next(valid_ds) sample_x = sample_x[:1] # Shrink to batch-size 1. sample_y = sample_y[:1] # Shrink to batch-size 1. # Generate a prediction, feeding in ground truth at each point as input. predicted, _ = model.apply(train_state.params, None, sample_x) plot = plot_samples(sample_y, predicted) _ = plot.draw() # - # ### Run autoregressively # + # %%time sample_x, sample_y = next(valid_ds) sample_x = sample_x[:1] # Shrink to batch-size 1. sample_y = sample_y[:1] # Shrink to batch-size 1. context_length = SEQ_LEN // 8 # Cut the batch-size 1 context from the start of the sequence. context = sample_x[:, :context_length] # Reuse the same context from the previous cell. predicted = fast_autoregressive_predict(train_state.params, None, context, SEQ_LEN) # The plots should be equivalent! plot = plot_samples(sample_y, predicted) plot += gg.geom_vline(xintercept=len(context), linetype="dashed") _ = plot.draw()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 11420, 198, 2, 474, 929, 88, 353, 25, 198, 2, 220, 220, 474, 929, 88, 5239, 25, 198, 2, 220, 220, 220, 220, 17519, 25, 20966, 2047, 65, 11, 9078, 11, 9132, 19...
2.574682
7,244
# Generate a graph with: # Vertices V = {"a", "b", "c", "d", "e"} # Edges E = {"ab", "ac", "bd", "cd", "de"} # Create the dictionary with graph elements graph_elements = { "a" : ["b","c"], "b" : ["a", "d"], "c" : ["a", "d"], "d" : ["e"], "e" : ["d"] } g = graph(graph_elements) print(g.get_vertices()) # ['a', 'b', 'c', 'd', 'e'] print(g.find_edges()) # [{'b', 'a'}, {'a', 'c'}, {'b', 'd'}, {'c', 'd'}, {'e', 'd'}] g.add_node('f') g.add_edge({'a', 'f'}) print(g.find_edges())
[ 2, 2980, 378, 257, 4823, 351, 25, 198, 2, 24417, 1063, 198, 53, 796, 19779, 64, 1600, 366, 65, 1600, 366, 66, 1600, 366, 67, 1600, 366, 68, 20662, 198, 2, 1717, 3212, 198, 36, 796, 19779, 397, 1600, 366, 330, 1600, 366, 17457, 1...
1.755486
319
import discord from discord.ext import commands import scrimdb as db import interactions
[ 11748, 36446, 198, 6738, 36446, 13, 2302, 1330, 9729, 198, 11748, 32157, 9945, 355, 20613, 198, 11748, 12213, 628, 198 ]
4.55
20
import sys import argparse import os import cv2 import glob import numpy as np import torch from PIL import Image import gc from torch.profiler import profile, record_function, ProfilerActivity import time sys.path.append('core') from core.raft import RAFT from core.utils import flow_viz from core.utils.utils import InputPadder DEVICE = 'cuda' def make_dir_if_not_exist(path): """ Make a directory if the input path does not exist Args: path (str): path to check and eventually create """ if not os.path.exists(path): os.makedirs(path) # ToDo: function write_flo() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--model', help="restore checkpoint") parser.add_argument('--path', help="dataset for evaluation") parser.add_argument('--small', action='store_true', help='use small model') parser.add_argument('--mixed_precision', action='store_true', help='use mixed precision') parser.add_argument('--alternate_corr', action='store_true', help='use efficent correlation implementation') args = parser.parse_args() # with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof: # with record_function("model_inference"): # demo(args) # # print(prof.key_averages().table(row_limit=10)) demo(args)
[ 11748, 25064, 198, 198, 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 269, 85, 17, 198, 11748, 15095, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 308, 66, 198, 6738, 28034, 1...
2.885593
472
import logging import shutil import os.path from jinja2 import Environment, PackageLoader from . import utils import ostester env = Environment(loader=PackageLoader('ostester', 'templates'), trim_blocks=True, lstrip_blocks=True) env.filters['header_to_function_name'] = utils.header_to_function_name env.filters['function_test_case_name'] = utils.function_test_case_name env.globals['new_name'] = utils.new_name def render_main(tested_headers): """ Returns a string containing the entry point for the generated tests """ template = env.get_template('main.jinja2.c') return template.render(test_headers=tested_headers) def render_header_suite(test_header, hs_header, functions): """ Returns a string containing the entry point for the generated tests """ template = env.get_template('header_suite.jinja2.c') return template.render(test_header_name=test_header, header_suite_header_name=hs_header, functions=functions)
[ 11748, 18931, 198, 11748, 4423, 346, 198, 11748, 28686, 13, 6978, 198, 198, 6738, 474, 259, 6592, 17, 1330, 9344, 11, 15717, 17401, 198, 198, 6738, 764, 1330, 3384, 4487, 198, 11748, 23619, 7834, 198, 198, 24330, 796, 9344, 7, 29356, ...
2.607407
405
import numpy as np from extra_keras_metrics import (get_complete_binary_metrics, get_minimal_multiclass_metrics) from tensorflow.keras.layers import Dense from tensorflow.keras.models import Sequential def test_binary_model_run(): """Test that all metrics actually work when used with a Keras model.""" model = Sequential([ Dense(1, activation="sigmoid") ]) model.compile( optimizer="nadam", loss="binary_crossentropy", metrics=get_complete_binary_metrics() ) history = model.fit( np.random.uniform(size=(1000, 10)), np.random.randint(2, size=(1000, )), epochs=30, sample_weight=np.random.uniform(size=(1000, )), ) def test_multiclass_model_run(): """Test that all metrics actually work when used with a Keras model.""" model = Sequential([ Dense(5, activation="softmax") ]) model.compile( optimizer="nadam", loss="categorical_crossentropy", metrics=get_minimal_multiclass_metrics() ) model.fit( np.random.uniform(size=(10, 10)), np.random.randint(2, size=(10, 5)), )
[ 11748, 299, 32152, 355, 45941, 198, 6738, 3131, 62, 6122, 292, 62, 4164, 10466, 1330, 357, 1136, 62, 20751, 62, 39491, 62, 4164, 10466, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.282101
514
import datetime from Other.SharedResources import db, g_user
[ 11748, 4818, 8079, 201, 198, 6738, 3819, 13, 2484, 1144, 33236, 1330, 20613, 11, 308, 62, 7220, 201 ]
3.444444
18
__version__ = "1.0.1" from .dirty_mnist import *
[ 834, 9641, 834, 796, 366, 16, 13, 15, 13, 16, 1, 198, 198, 6738, 764, 49075, 62, 10295, 396, 1330, 1635, 628 ]
2.318182
22
import os import cv2 as cv import numpy as np if __name__ == "__main__": compute_finger('fingerprints/finger-0', 'fingerprints/clear.png', 'fingerprints/finger-0.npz')
[ 11748, 28686, 198, 198, 11748, 269, 85, 17, 355, 269, 85, 198, 11748, 299, 32152, 355, 45941, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 24061, 62, 35461, 10786, 35461, 17190, 14, 35461...
2.321429
84
import torch import torch.nn as nn
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 628 ]
3.272727
11
# Generated by Django 3.2.7 on 2021-09-17 02:10 import dashboard.models import django.core.validators from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 22, 319, 33448, 12, 2931, 12, 1558, 7816, 25, 940, 198, 198, 11748, 30415, 13, 27530, 198, 11748, 42625, 14208, 13, 7295, 13, 12102, 2024, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 60...
3.152174
46