content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
""" A Lake Winnipeg Basin Information Network (BIN) harvester for the SHARE project Example API request: http://130.179.67.140/api/3/action/package_search?q= (problematic) http://130.179.67.140/api/3/action/current_package_list_with_resources (currently using) It oddly returns 5 more datasets than all searchable ones on LWBIN data hub. Known issues: 1 -- Five datasets can be searched but cannot be accessed via LWBIN. Clicking on the searching result would result in linking to a redirected page like this: http://130.179.67.140/user/login?came_from=http://130.179.67.140/dataset/mpca-surface-water-data-access-interactive-map Within each dataset there are resouces that contain urls to source pages. For future work considering using resources urls as canonical urls. 2 -- Resouces properties contained in raw metadata of the datasets are not added to the normalized metadata at this point. 3 -- Single name contributors can be used as filters or an invalid query will be returned. Has nothing to do with scrapi but the frontend. """ from __future__ import unicode_literals import json import logging from dateutil.parser import parse from scrapi import requests from scrapi.base import JSONHarvester from scrapi.linter.document import RawDocument from scrapi.base.helpers import build_properties, datetime_formatter, parse_name logger = logging.getLogger(__name__) ORGANIZATIONS = ( "organization", "fund", "canada", "agriculture", "commitee", "international", "council", "office", "of", "observation", "institute", "lwbin", "cocorahs", "usgs", "nsidc" ) def is_organization(name): """Return a boolean to indicate if the name passed to the function is an organization """ words = name.split(' ') return any(word.strip(";").lower() in ORGANIZATIONS for word in words) def clean_authors(authors): """Cleam authors list. """ authors = authors.strip().replace('<span class="author-names">', '').replace('</span>', '') authors = authors.split(',') new_authors = [] for author in authors: if is_organization(author): new_authors.append(author) else: if ' and ' in author or ' <em>et al.</em>' in author: split_name = author.replace(' <em>et al.</em>', '').split(' and ') new_authors.extend(split_name) else: new_authors.append(author) return new_authors def process_contributors(authors, emails): """Process authors and add author emails If multiple authors and one email, put email in a new author """ emails = emails.split(',') authors = clean_authors(authors) contributor_list = [] append_emails = len(authors) == 1 and len(emails) == 1 and not emails[0] == u'' # append the email to the author only when 1 record is observed for i, author in enumerate(authors): if is_organization(author): contributor = { 'name': author } else: contributor = parse_name(author) if append_emails: contributor['email'] = emails[i] contributor_list.append(contributor) if not append_emails and emails[0] != u'': for email in emails: contributor = { 'name': '', 'email': email } contributor_list.append(contributor) return contributor_list def process_licenses(license_title, license_url, license_id): """Process licenses to comply with the normalized schema """ if not license_url: return [] else: license = { 'uri': license_url, 'description': "{} ({})".format(license_title, license_id) or "" } return [license] def construct_url(url, dataset_path, end_point): """ :return: a url that directs back to the page on LBWIN Data Hub instead of the source page. :param url: host url :param dataset_path: parent path of all datasets :param end_point: name of datasets """ return "/".join([url, dataset_path, end_point]) def process_object_uris(url, extras): """Extract doi from /extras, and return a list of object uris including /url and doi if it exists. """ doi = [] for d in extras: if d['key'] == "DOI" or d['key'] == "DOI:": doi.append(d['value']) if doi == []: return [url] else: return [url].extend(doi)
[ 37811, 198, 32, 6233, 23434, 32666, 6188, 7311, 357, 33, 1268, 8, 3971, 1158, 353, 329, 262, 6006, 12203, 1628, 198, 198, 16281, 7824, 2581, 25, 2638, 1378, 12952, 13, 21738, 13, 3134, 13, 15187, 14, 15042, 14, 18, 14, 2673, 14, 264...
2.710976
1,640
from dataclasses import dataclass from bindings.gmd.point_type import PointType __NAMESPACE__ = "http://www.opengis.net/gml"
[ 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 6738, 34111, 13, 70, 9132, 13, 4122, 62, 4906, 1330, 6252, 6030, 198, 198, 834, 45, 29559, 47, 11598, 834, 796, 366, 4023, 1378, 2503, 13, 404, 1516, 271, 13, 3262, 14, 70, 4029, ...
2.822222
45
# Generated by Django 2.2.8 on 2020-04-13 09:12 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 23, 319, 12131, 12, 3023, 12, 1485, 7769, 25, 1065, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.818182
44
# -*- coding: utf-8 -*- """Jacobian preconditioner. """ from root.config.main import * from scipy import sparse as spspa from tools.linear_algebra.preconditioners.base import Preconditioner
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 46751, 666, 3718, 623, 653, 263, 13, 198, 37811, 198, 6738, 6808, 13, 11250, 13, 12417, 1330, 1635, 198, 6738, 629, 541, 88, 1330, 29877, 355, 599, 2777, 64, 19...
3.015873
63
from django.contrib.sites.models import Site from django.db import models
[ 6738, 42625, 14208, 13, 3642, 822, 13, 49315, 13, 27530, 1330, 14413, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 628, 198 ]
3.454545
22
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== '''Analysis file.''' import sys import os.path import tensorflow as tf from absl import app from absl import flags from absl import gfile import cPickle as pickle import matplotlib matplotlib.use('TkAgg') from matplotlib import pylab import matplotlib.pyplot as plt import numpy as np, h5py import scipy.io as sio from scipy import ndimage import random import re # regular expression matching FLAGS = flags.FLAGS flags.DEFINE_string('folder_name', 'experiment4', 'folder where to store all the data') flags.DEFINE_string('save_location', '/home/bhaishahster/', 'where to store logs and outputs?'); flags.DEFINE_string('data_location', '/home/bhaishahster/data_breakdown/', 'where to take data from?') flags.DEFINE_integer('n_b_in_c', 10, 'number of batches in one chunk of data') flags.DEFINE_integer('np_randseed', 23, 'numpy RNG seed') flags.DEFINE_integer('randseed', 65, 'python RNG seed') flags.DEFINE_integer('ratio_SU', 2, 'ratio of subunits/cells') flags.DEFINE_string('model_id', 'poisson', 'which model to fit') FLAGS = flags.FLAGS if __name__ == '__main__': app.run()
[ 2, 15069, 2864, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 7330...
2.995098
612
from django.core.exceptions import PermissionDenied from django.shortcuts import get_object_or_404, redirect from django.template.response import TemplateResponse from django.urls import reverse from django.utils.translation import gettext as _ from wagtail.admin import messages from wagtail.admin.views.pages.utils import get_valid_next_url_from_request from wagtail.core import hooks from wagtail.core.models import Page, UserPagePermissionsProxy
[ 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 2448, 3411, 21306, 798, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 651, 62, 15252, 62, 273, 62, 26429, 11, 18941, 198, 6738, 42625, 14208, 13, 28243, 13, 26209, 1330, 37350, 310...
3.616
125
import logging import os.path as path from typing import List, Optional, Tuple from psychopy import core, visual from bcipy.acquisition.marker_writer import NullMarkerWriter, MarkerWriter from bcipy.helpers.task import SPACE_CHAR from bcipy.helpers.stimuli import resize_image from bcipy.helpers.system_utils import get_screen_resolution from bcipy.helpers.triggers import TriggerCallback, _calibration_trigger
[ 11748, 18931, 198, 11748, 28686, 13, 6978, 355, 3108, 198, 6738, 19720, 1330, 7343, 11, 32233, 11, 309, 29291, 198, 198, 6738, 3795, 11081, 1330, 4755, 11, 5874, 198, 198, 6738, 47125, 541, 88, 13, 43561, 10027, 13, 4102, 263, 62, 160...
3.421488
121
#!/usr/bin/env python import pymysql #Python3 db = pymysql.connect("localhost","sips","root","zaijian" ) cursor = db.cursor() cursor.execute("SELECT VERSION()") data = cursor.fetchone() print ("Database version : %s " % data) db.close()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 279, 4948, 893, 13976, 220, 1303, 37906, 18, 198, 220, 198, 9945, 796, 279, 4948, 893, 13976, 13, 8443, 7203, 36750, 2430, 82, 2419, 2430, 15763, 2430, 35142, 73, 666, 1, 1267, ...
2.659341
91
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from ._enums import * __all__ = [ 'AppAutoBranchCreationConfigArgs', 'AppBasicAuthConfigArgs', 'AppCustomRuleArgs', 'AppEnvironmentVariableArgs', 'AppTagArgs', 'BranchBasicAuthConfigArgs', 'BranchEnvironmentVariableArgs', 'BranchTagArgs', 'DomainSubDomainSettingArgs', ]
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 26144, 35986, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760, 644, 345, 389, 1804, 0, 17202, ...
3.17
200
# -*- coding: utf-8 -*- """ awsecommerceservice This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 220, 220, 220, 3253, 325, 785, 647, 728, 712, 501, 628, 220, 220, 220, 770, 2393, 373, 6338, 7560, 416, 3486, 3955, 1404, 2149, 410, 17, 13, 15, 357...
2.5
58
from __future__ import absolute_import from __future__ import print_function from __future__ import division import numpy as np import cPickle as pickle from keras import backend as K from keras.utils import np_utils from keras.preprocessing import sequence from random import shuffle import itertools batch_gen = BatchGen # for backward compatibility
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 31686, 293, 355, 2298, 293, 198, 198...
3.869565
92
from RegressaoLinear import RegressaoLinear planoCartesiano = { 0.5: 4.4, 2.8: 1.8, 4.2: 1.0, 6.7: 0.4, 8.3: 0.2 } regressaoLinear = RegressaoLinear(planoCartesiano) print(regressaoLinear.gerar_equacao())
[ 6738, 3310, 601, 5488, 14993, 451, 1330, 3310, 601, 5488, 14993, 451, 198, 198, 489, 5733, 43476, 274, 10115, 796, 1391, 198, 220, 657, 13, 20, 25, 604, 13, 19, 11, 198, 220, 362, 13, 23, 25, 352, 13, 23, 11, 198, 220, 604, 13, ...
1.990826
109
import dash from dash import html from dash import dcc import dash_bootstrap_components as dbc from dash.dependencies import Input, Output from .layout import * from .plot import * # from layout import * # from plot import * app = dash.Dash( __name__, external_stylesheets=[dbc.themes.BOOTSTRAP, "/css/button.css"] ) app.title = "Data Science Salaries" server = app.server app.layout = html.Div( [ dcc.Location(id="url", refresh=False), topbar, content, # sidebar, ] ) if __name__ == "__main__": app.run_server(debug=True)
[ 11748, 14470, 198, 6738, 14470, 1330, 27711, 198, 6738, 14470, 1330, 288, 535, 198, 11748, 14470, 62, 18769, 26418, 62, 5589, 3906, 355, 288, 15630, 198, 6738, 14470, 13, 45841, 3976, 1330, 23412, 11, 25235, 198, 198, 6738, 764, 39786, ...
2.586667
225
# Copyright 2018 MassOpenCloud. # # 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. __all__ = [ 'init', 'cleanup', 'set_defaults', 'add_extra_exmods', 'clear_extra_exmods', 'get_allowed_exmods', 'RequestContextSerializer', 'get_client', 'get_server', 'get_notifier', 'TRANSPORT_ALIASES', ] import functools from oslo_log import log as logging import oslo_messaging as messaging from oslo_serialization import jsonutils from oslo_service import periodic_task from oslo_utils import importutils from oslo_utils import timeutils import nova.conf import nova.context import nova.exception from nova.i18n import _ from nova import objects profiler = importutils.try_import("osprofiler.profiler") CONF = nova.conf.CONF LOG = logging.getLogger(__name__) TRANSPORT = None LEGACY_NOTIFIER = None NOTIFICATION_TRANSPORT = None NOTIFIER = None ALLOWED_EXMODS = [ nova.exception.__name__, ] EXTRA_EXMODS = [] # NOTE(markmc): The nova.openstack.common.rpc entries are for backwards compat # with Havana rpc_backend configuration values. The nova.rpc entries are for # compat with Essex values. TRANSPORT_ALIASES = { 'nova.openstack.common.rpc.impl_kombu': 'rabbit', 'nova.openstack.common.rpc.impl_qpid': 'qpid', 'nova.openstack.common.rpc.impl_zmq': 'zmq', 'nova.rpc.impl_kombu': 'rabbit', 'nova.rpc.impl_qpid': 'qpid', 'nova.rpc.impl_zmq': 'zmq', }
[ 2, 15069, 2864, 5674, 11505, 18839, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, 2393, 2845, 287, 11846, 35...
2.712692
717
# from queue import Queue def insert(tree, node): """""" if tree.root == None: tree.root = node else: temp = tree.root # while temp != None: if temp.data > node.data: if temp.node_left == None: temp.node_left = node return else: temp = temp.node_left else: if temp.node_right == None: temp.node_right = node return else: temp = temp.node_right def preorder(node): """""" if node != None: print(node.data, end='') preorder(node.node_left) preorder(node.node_right) def inorder(node): """""" if node != None: inorder(node.node_left) print(node.data, end='') inorder(node.node_right) def postorder(node): """""" if node != None: postorder(node.node_left) postorder(node.node_right) print(node.data, end='') def get_height(node): """k""" if node == None: return 0 max_left = get_height(node.node_left) max_right = get_height(node.node_right) max_value = max(max_left, max_right) return max_value+1 def get_node(node, k): """k""" if node == None: return if k == 1: if node.data !=None: print(node.data, end='') get_node(node.node_left, k-1) get_node(node.node_right, k-1) def get_max(node): """ """ if node != None: while node.node_right != None: node = node.node_right return node.data def get_min(node): """""" if node != None: while node.node_left != None: node = node.node_left return node.data def Mirror(node): """ ,nice """ if node == None: return if node.node_left == None and node.node_right == None: return temp = node.node_left node.node_left = node.node_right node.node_right = temp Mirror(node.node_left) Mirror(node.node_right) if __name__ == '__main__': tree = BinaryTree() arr_test = [6, 3, 8, 2, 5, 1, 7] for i in arr_test: insert(tree, Node(i)) # preorder(tree.root) # print() # inorder(tree.root) # print() # get_node(tree.root, 3) # print() # result = get_height(tree.root) # print(result) # max_value = get_max(tree.root) # print(max_value) # min_value = get_min(tree.root) # print(min_value) comorder(tree.root) Mirror(tree.root) print() comorder(tree.root)
[ 2, 220, 198, 6738, 16834, 1330, 4670, 518, 628, 220, 220, 220, 220, 198, 4299, 7550, 7, 21048, 11, 10139, 2599, 198, 220, 220, 220, 13538, 15931, 15931, 198, 220, 220, 220, 611, 5509, 13, 15763, 6624, 6045, 25, 198, 220, 220, 220, ...
1.966518
1,344
#emprstimos bancrios. pegue o valor da casa, o salario da pessoa e em quanto tempo ela quer pagar. #se as parcelas ficarem acima de 30% do salario, negue o imprestimo. casa = float(input('Informe o valor da casa: R$')) salario = float(input('informe seu salario: R$')) tempo = int(input('Em quanto tempo planeja pagar: ')) parcela = casa/(tempo*12)#para fazer a conta com base em anos, levando em conta as parcelas mensais. print('Para pagar um casa de R${:.2f} e em {}anos, suas parcelas ficariam de R${:.2f}'.format(casa, tempo, parcela)) if parcela >= (salario*30/100): print('Com seu salrio atual, no possvel efetuar esse emprstimo.') else: print('Emprstimo aprovado')
[ 2, 368, 1050, 42003, 418, 275, 1192, 380, 418, 13, 613, 18701, 267, 1188, 273, 12379, 6124, 64, 11, 267, 3664, 4982, 12379, 279, 408, 12162, 304, 795, 5554, 78, 28691, 1288, 64, 42517, 279, 32452, 13, 220, 201, 198, 2, 325, 355, 2...
2.404844
289
#Integer division #You have a shop selling buns for $2.40 each. A customer comes in with $15, and would like to buy as many buns as possible. #Complete the code to calculate how many buns the customer can afford. #Note: Your customer won't be happy if you try to sell them part of a bun. #Print only the result, any other text in the output will cause the checker to fail. bun_price = 2.40 money = 15 print( money // bun_price )
[ 2, 46541, 7297, 198, 198, 2, 1639, 423, 257, 6128, 6301, 275, 13271, 329, 720, 17, 13, 1821, 1123, 13, 220, 317, 6491, 2058, 287, 351, 720, 1314, 11, 290, 561, 588, 284, 2822, 355, 867, 275, 13271, 355, 1744, 13, 198, 2, 20988, ...
3.491935
124
# ******************************************************************************************* # ******************************************************************************************* # # Name : test_maths.py # Purpose : Create lots of variables/arrays and arithmetic/bitwise. # Date : 10th June 2019 # Author : Paul Robson (paul@robsons.org.uk) # # ******************************************************************************************* # ******************************************************************************************* import random from variables import * if __name__ == "__main__": print("Arithmetic/Bitwise test code.") operators = "+,-,*,/,&,|,^".split(",") eb = EntityBucket(-1,60,0,10,0) # bs = BasicSource() bs.append(eb.setupCode()) bs.append(eb.assignCode()) for i in range(0,900): ok = False while not ok: v1 = eb.pickOne() v2 = eb.pickOne() operator = operators[random.randint(0,len(operators)-1)] ok = True if abs(v1.getValue()*v2.getValue()) >= 32768*4096: ok = False if (operator == "/" or operator == "%") and v2.getValue() == 0: ok = False r = calculate(operator,v1.getValue(),v2.getValue()) bs.append("assert ({0}{1}{2}) = {3}".format(v1.getEither(),operator,v2.getEither(),r)) bs.append(eb.checkCode()) bs.save() # blk = BasicBlock(0x4000,0x8000) blk.setBoot("run",False) blk.loadProgram() blk.exportFile("temp/basic.bin")
[ 2, 41906, 17174, 8412, 4557, 8162, 198, 2, 41906, 17174, 8412, 4557, 8162, 198, 2, 198, 2, 197, 197, 5376, 1058, 220, 197, 197, 9288, 62, 11018, 82, 13, 9078, 198, 2, 197, 197, 30026, 3455, 1058, 197, 16447, 6041, 286, 9633, 14, 3...
2.954357
482
# unicode from collections import Counter import qa.regex_utils as regutil import re resource_path = "/media/tmxmall/a36811aa-0e87-4ba1-b14f-370134452449/data/medicine.txt" with open(resource_path, "r", encoding="utf8") as f: char_stream = f.read() char_dictionary = Counter(list(char_stream)) med_unicodes = regutil.expr_converter("[[%s]]" % "".join(char_dictionary.keys()).replace("\n", "") + "#[[\\u4e00-\\u9fff]]") format_med_unicodes = re.sub("(?<!-)(?=\\\\u)", "\n", med_unicodes) print(format_med_unicodes) lines = char_stream.split("\n") unknown_char = "[^\\u0020-\\u007e\\u4e00-\\u9fff]" regutil.uu_enum("\\u0020-\\u007e") regex_filter_line("[\\u0020-\\u007e]", lines) regex_filter_line("[\\u00a0-\\u00ff]", lines) regex_filter_line("[\\u0100-\\u01ff]", lines) regex_filter_line("[\\u0251]", lines) regex_filter_line("[\\u025b]", lines) regex_filter_line("[\\u0261]", lines) regex_filter_line("[\\u028a]", lines) regex_filter_line("[\\u02c6-\\u02cb]", lines) regex_filter_line("[\\u02d0]", lines) regex_filter_line("[\\u02d8-\\u02da]", lines) regex_filter_line("[\\u02dc]", lines) regex_filter_line("[\\u037a]", lines) regex_filter_line("[\\u037e]", lines) regex_filter_line("[\\u038a]", lines) regex_filter_line("[\\u038c]", lines) regex_filter_line("[\\u03cb]", lines) regex_filter_line("[\\u03d6]", lines) regex_filter_line("[\\u0384-\\u0385]", lines) regex_filter_line("[\\u0387-\\u0388]", lines) regex_filter_line("[\\u038e-\\u038f]", lines) regex_filter_line("[\\u0391-\\u03c9]", lines) regex_filter_line("[\\u0400-\\u04ff]", lines) regex_filter_line("[\\u0590-\\u05ff]", lines) regex_filter_line("[\\u0652]", lines) regex_filter_line("[\\u11bc]", lines) regex_filter_line("[\\u1868]", lines) regex_filter_line("[\\u1d31]", lines) regex_filter_line("[\\u1d52]", lines) regex_filter_line("[\\u1d5b]", lines) regex_filter_line("[\\u1ef7]", lines) regex_filter_line("[\\u2016-\\u206a]", lines) regex_filter_line("[\\u2070]", lines) regex_filter_line("[\\u2074-\\u2075]", lines) regex_filter_line("[\\u2077-\\u2078]", lines) regex_filter_line("[\\u2082-\\u2084]", lines) regex_filter_line("[\\u20ac]", lines) regex_filter_line("[\\u2103]", lines) regex_filter_line("[\\u2105]", lines) regex_filter_line("[\\u2109]", lines) regex_filter_line("[\\u2116]", lines) regex_filter_line("[\\u2122]", lines) regex_filter_line("[\\u212b]", lines) regex_filter_line("[\\u2160-\\u216b]", lines) regex_filter_line("[\\u2170-\\u2179]", lines) regex_filter_line("[\\u21d2]", lines) regex_filter_line("[\\u2190-\\u2193]", lines) regex_filter_line("[\\u2206]", lines) regex_filter_line("[\\u2208]", lines) regex_filter_line("[\\u2211-\\u2212]", lines) regex_filter_line("[\\u2217-\\u221a]", lines) regex_filter_line("[\\u221d-\\u2220]", lines) regex_filter_line("[\\u2223]", lines) regex_filter_line("[\\u2225]", lines) regex_filter_line("[\\u2227-\\u222b]", lines) regex_filter_line("[\\u222e]", lines) regex_filter_line("[\\u2234]", lines) regex_filter_line("[\\u2237]", lines) regex_filter_line("[\\u223c-\\u223d]", lines) regex_filter_line("[\\u2245]", lines) regex_filter_line("[\\u224c]", lines) regex_filter_line("[\\u2252]", lines) regex_filter_line("[\\u2260-\\u2261]", lines) regex_filter_line("[\\u2264-\\u2267]", lines) regex_filter_line("[\\u226f]", lines) regex_filter_line("[\\u2295]", lines) regex_filter_line("[\\u2299]", lines) regex_filter_line("[\\u22a5]", lines) regex_filter_line("[\\u22bf]", lines) regex_filter_line("[\\u2312]", lines) regex_filter_line("[\\u2395]", lines) regex_filter_line("[\\u2460-\\u2473]", lines) regex_filter_line("[\\u2474-\\u2487]", lines) regex_filter_line("[\\u2488-\\u249b]", lines) regex_filter_line("[\\u2500-\\u257f]", lines) regex_filter_line("[\\u25a0-\\u25a1]", lines) regex_filter_line("[\\u25b2-\\u25b4]", lines) regex_filter_line("[\\u25c6-\\u25c7]", lines) regex_filter_line("[\\u25ca-\\u25cb]", lines) regex_filter_line("[\\u25ce-\\u25cf]", lines) regex_filter_line("[\\u2605-\\u2606]", lines) regex_filter_line("[\\u2609]", lines) regex_filter_line("[\\u2610]", lines) regex_filter_line("[\\u2640]", lines) regex_filter_line("[\\u2642]", lines) regex_filter_line("[\\u2666]", lines) regex_filter_line("[\\u266a-\\u266b]", lines) regex_filter_line("[\\u2714]", lines) regex_filter_line("[\\u2717]", lines) regex_filter_line("[\\u274f]", lines) regex_filter_line("[\\u2751]", lines) regex_filter_line("[\\u279f]", lines) regex_filter_line("[\\u27a2]", lines) regex_filter_line("[\\u27a5]", lines) regex_filter_line("[\\u2a7d]", lines) regex_filter_line("[\\u2fd4]", lines) regex_filter_line("[\\u3001-\\u301e]", lines) regex_filter_line("[\\u3022-\\u3025]", lines) regex_filter_line("[\\u3105-\\u3107]", lines) regex_filter_line("[\\u310a]", lines) regex_filter_line("[\\u3111]", lines) regex_filter_line("[\\u3113]", lines) regex_filter_line("[\\u3116-\\u3117]", lines) regex_filter_line("[\\u311a-\\u311b]", lines) regex_filter_line("[\\u3122]", lines) regex_filter_line("[\\u3125]", lines) regex_filter_line("[\\u3127-\\u3128]", lines) regex_filter_line("[\\u3220-\\u3229]", lines) regex_filter_line("[\\u32a3]", lines) regex_filter_line("[\\u338e-\\u338f]", lines) regex_filter_line("[\\u339c-\\u339d]", lines) regex_filter_line("[\\u33a1]", lines) regex_filter_line("[\\u33a5]", lines) regex_filter_line("[\\u33d5]", lines) regex_filter_line("[\\u33d1-\\u33d2]", lines) regex_filter_line("[\\u359e]", lines) regex_filter_line("[\\u39d1]", lines) regex_filter_line("[\\u41f2]", lines) regex_filter_line("[\\u4341]", lines) regex_filter_line("[\\u4d13]", lines) regex_filter_line("[\\u4d15]", lines) regex_filter_line("[\\u4e00-\\u9fff]", lines) regex_filter_line("[\\uacf3]", lines) regex_filter_line("[\\ucd38]", lines) regex_filter_line("[\\ue20c-\\ue2ff]", lines) regex_filter_line("[\\uf900-\\ufaff]", lines) regex_filter_line("[\\ufb03]", lines) regex_filter_line("[\\ufe30-\\ufe31]", lines) regex_filter_line("[\\ufe33]", lines) regex_filter_line("[\\ufe38]", lines) regex_filter_line("[\\ufe3c-\\ufe3d]", lines) regex_filter_line("[\\ufe3f-\\ufe41]", lines) regex_filter_line("[\\ufe4d-\\ufe4e]", lines) regex_filter_line("[\\ufe55-\\ufe57]", lines) regex_filter_line("[\\ufe59-\\ufe5c]", lines) regex_filter_line("[\\ufe5f]", lines) regex_filter_line("[\\ufe63]", lines) regex_filter_line("[\\ufe65-\\ufe66]", lines) regex_filter_line("[\\ufe6a-\\ufe6b]", lines) regex_filter_line("[\\ufeff]", lines) regex_filter_line("[\\uff01]", lines) regex_filter_line("[\\uff08-\\uff09]", lines) regex_filter_line("[\\uff0c]", lines) regex_filter_line("[\\uff1a]", lines) regex_filter_line("[\\uff1f]", lines) regex_filter_line("[\\uff61]", lines) regex_filter_line("[\\uff63]", lines) regex_filter_line("[\\uff65]", lines) regex_filter_line("[\\uff6c]", lines) regex_filter_line("[\\uff72]", lines) regex_filter_line("[\\uff86]", lines) regex_filter_line("[\\uff89]", lines) regex_filter_line("[\\uffe0-\\uffe1]", lines) regex_filter_line("[\\uffe3]", lines) regex_filter_line("[\\uffe5]", lines) regex_filter_line("[\\uffed]", lines) regex_filter_line("[\\ufffc]", lines) """ [\u0020-\u007e] 13056272 \\u0020-\\u007e Latin [\u00a0-\u00ff] 258619 \\u00a0-\\u00ff Latin ++ [\u0100-\u01ff] 353 \\u0100-\\u01ff Latin ++ [\u0251] 302 \\u0251 [\u025b] 2 \\u025b [\u0261] 25 \\u0261 [\u028a] 1 \\u028a [\u02c6-\u02cb] 870 \\u02c6-\\u02cb [\u02d0] 1 \\u02d0 [\u02d8-\u02da] 25 \\u02d8-\\u02da [\u02dc] 10 \\u02dc [\u037a] 1 \\u037a [\u037e] 4 \\u037e [\u038a] 3 \\u038a [\u038c] 1 \\u038c [\u03cb] 3 \\u03cb [\u03d6] 2 \\u03d6 [\u0384-\u0385] 8 \\u0384-\\u0385 [\u0387-\u0388] 2 \\u0387-\\u0388 [\u038e-\u038f] 2 \\u038e-\\u038f [\u0391-\u03c9] 567276 \\u0391-\\u03c9 [\u0400-\u04ff] 2058 \\u0400-\\u04ff [\u0590-\u05ff] 34 \\u0590-\\u05ff [\u0652] 1 \\u0652 [\u11bc] 3 \\u11bc [\u1868] 1 \\u1868 [\u1d31] 1 \\u1d31 [\u1d52] 1 \\u1d52 [\u1d5b] 1 \\u1d5b [\u1ef7] 1 \\u1ef7 Latin ++ [\u2016-\u206a] 323353 \\u2016-\\u206a punc++ [\u2070] 4 \\u2070 [\u2074-\u2075] 9 \\u2074-\\u2075 [\u2077-\u2078] 11 \\u2077-\\u2078 [\u2082-\u2084] 13 \\u2082-\\u2084 [\u20ac] 58 \\u20ac [\u2103] 132218 \\u2103 [\u2105] 64 \\u2105 [\u2109] 45 \\u2109 [\u2116] 559 \\u2116 [\u2122] 348 \\u2122 [\u212b] 5 \\u212b [\u2160-\u216b] 235239 \\u2160-\\u216b [\u2170-\u2179] 1557 \\u2170-\\u2179 [\u21d2] 3 \\u21d2 [\u2190-\u2193] 15107 \\u2190-\\u2193 [\u2206] 5 \\u2206 [\u2208] 281 \\u2208 [\u2211-\u2212] 839 \\u2211-\\u2212 [\u2217-\u221a] 75 \\u2217-\\u221a [\u221d-\u2220] 861 \\u221d-\\u2220 [\u2223] 1 \\u2223 [\u2225] 80 \\u2225 [\u2227-\u222b] 226 \\u2227-\\u222b [\u222e] 8 \\u222e [\u2234] 46 \\u2234 [\u2237] 333 \\u2237 [\u223c-\u223d] 29 \\u223c-\\u223d [\u2245] 1 \\u2245 [\u224c] 33 \\u224c [\u2252] 4 \\u2252 [\u2260-\u2261] 555 \\u2260-\\u2261 [\u2264-\u2267] 31397 \\u2264-\\u2267 [\u226f] 3 \\u226f [\u2295] 4 \\u2295 [\u2299] 17 \\u2299 [\u22a5] 41 \\u22a5 [\u22bf] 116 \\u22bf [\u2312] 5 \\u2312 [\u2395] 4 \\u2395 [\u2460-\u2473] 48470 \\u2460-\\u2473 [\u2474-\u2487] 1267 \\u2474-\\u2487 [\u2488-\u249b] 107 \\u2488-\\u249b [\u2500-\u257f] 566 \\u2500-\\u257f [\u25a0-\u25a1] 1052 \\u25a0-\\u25a1 [\u25b2-\u25b4] 3695 \\u25b2-\\u25b4 [\u25c6-\u25c7] 205 \\u25c6-\\u25c7 [\u25ca-\u25cb] 339 \\u25ca-\\u25cb [\u25ce-\u25cf] 767 \\u25ce-\\u25cf [\u2605-\u2606] 196 \\u2605-\\u2606 [\u2609] 3 \\u2609 [\u2610] 35 \\u2610 [\u2640] 1017 \\u2640 [\u2642] 1108 \\u2642 [\u2666] 2 \\u2666 [\u266a-\u266b] 9 \\u266a-\\u266b [\u2714] 4 \\u2714 [\u2717] 1 \\u2717 [\u274f] 1 \\u274f [\u2751] 2 \\u2751 [\u279f] 1 \\u279f [\u27a2] 6 \\u27a2 [\u27a5] 1 \\u27a5 [\u2a7d] 3 \\u2a7d [\u2fd4] 2 \\u2fd4 CJK++ [\u3001-\u301e] 7028921 \\u3001-\\u301e CJK punc [\u3022-\u3025] 8 \\u3022-\\u3025 [\u3105-\u3107] 8 \\u3105-\\u3107 [\u310a] 1 \\u310a [\u3111] 1 \\u3111 [\u3113] 2 \\u3113 [\u3116-\u3117] 6 \\u3116-\\u3117 [\u311a-\u311b] 2 \\u311a-\\u311b [\u3122] 1 \\u3122 [\u3125] 1 \\u3125 [\u3127-\u3128] 11 \\u3127-\\u3128 [\u3220-\u3229] 312 \\u3220-\\u3229 [\u32a3] 6 \\u32a3 [\u338e-\u338f] 125 \\u338e-\\u338f [\u339c-\u339d] 75 \\u339c-\\u339d [\u33a1] 59 \\u33a1 [\u33a5] 1 \\u33a5 [\u33d5] 24 \\u33d5 [\u33d1-\u33d2] 9 \\u33d1-\\u33d2 [\u359e] 6 \\u359e [\u39d1] 3 \\u39d1 [\u41f2] 13 \\u41f2 [\u4341] 2 \\u4341 [\u4d13] 2 \\u4d13 [\u4d15] 1 \\u4d15 [\u4e00-\u9fff] 13056199 \\u4e00-\\u9fff CJK [\uacf3] 2 \\uacf3 ++ [\ucd38] 1 \\ucd38 ++ [\ue20c-\ue2ff] 1305 \\ue20c-\\ue2ff ??? [\uf900-\ufaff] 136 \\uf900-\\ufaff CJK ++ [\ufb03] 1 \\ufb03 [\ufe30-\ufe31] 941 \\ufe30-\\ufe31 [\ufe33] 2 \\ufe33 [\ufe38] 4 \\ufe38 [\ufe3c-\ufe3d] 33 \\ufe3c-\\ufe3d [\ufe3f-\ufe41] 19 \\ufe3f-\\ufe41 [\ufe4d-\ufe4e] 7 \\ufe4d-\\ufe4e [\ufe55-\ufe57] 102 \\ufe55-\\ufe57 [\ufe59-\ufe5c] 185 \\ufe59-\\ufe5c [\ufe5f] 10 \\ufe5f [\ufe63] 70 \\ufe63 [\ufe65-\ufe66] 551 \\ufe65-\\ufe66 [\ufe6a-\ufe6b] 233 \\ufe6a-\\ufe6b [\ufeff] 4 \\ufeff arabic ++ # FE70-FEFF [\uff01] 886 \\uff01 [\uff08-\uff09] 622070 \\uff08-\\uff09 [\uff0c] 3445520 \\uff0c [\uff1a] 471609 \\uff1a [\uff1f] 9822 \\uff1f [\uff61] 2 \\uff61 [\uff63] 1 \\uff63 [\uff65] 8 \\uff65 [\uff6c] 2 \\uff6c [\uff72] 1 \\uff72 [\uff86] 1 \\uff86 [\uff89] 1 \\uff89 [\uffe0-\uffe1] 160 \\uffe0-\\uffe1 [\uffe3] 7143 \\uffe3 [\uffe5] 57 \\uffe5 [\uffed] 9 \\uffed [\ufffc] 1 \\ufffc """ """ \\u0020-\\u007e Latin \\u00a0-\\u00ff Latin ++ \\u0100-\\u01ff Latin ++ \\u0251 \\u025b \\u0261 \\u028a \\u02c6-\\u02cb \\u02d0 \\u02d8-\\u02da \\u02dc \\u037a \\u037e \\u038a \\u038c \\u03cb \\u03d6 \\u0384-\\u0385 \\u0387-\\u0388 \\u038e-\\u038f \\u0391-\\u03c9 \\u0400-\\u04ff \\u0590-\\u05ff \\u0652 \\u11bc \\u1868 \\u1d31 \\u1d52 \\u1d5b \\u1ef7 Latin ++ \\u2016-\\u206a punc++ \\u2070 \\u2074-\\u2075 \\u2077-\\u2078 \\u2082-\\u2084 \\u20ac \\u2103 \\u2105 \\u2109 \\u2116 \\u2122 \\u212b \\u2160-\\u216b \\u2170-\\u2179 \\u21d2 \\u2190-\\u2193 \\u2206 \\u2208 \\u2211-\\u2212 \\u2217-\\u221a \\u221d-\\u2220 \\u2223 \\u2225 \\u2227-\\u222b \\u222e \\u2234 \\u2237 \\u223c-\\u223d \\u2245 \\u224c \\u2252 \\u2260-\\u2261 \\u2264-\\u2267 \\u226f \\u2295 \\u2299 \\u22a5 \\u22bf \\u2312 \\u2395 \\u2460-\\u2473 \\u2474-\\u2487 \\u2488-\\u249b \\u2500-\\u257f \\u25a0-\\u25a1 \\u25b2-\\u25b4 \\u25c6-\\u25c7 \\u25ca-\\u25cb \\u25ce-\\u25cf \\u2605-\\u2606 \\u2609 \\u2610 \\u2640 \\u2642 \\u2666 \\u266a-\\u266b \\u2714 \\u2717 \\u274f \\u2751 \\u279f \\u27a2 \\u27a5 \\u2a7d \\u2fd4 CJK++ \\u3001-\\u301e CJK punc \\u3022-\\u3025 \\u3105-\\u3107 \\u310a \\u3111 \\u3113 \\u3116-\\u3117 \\u311a-\\u311b \\u3122 \\u3125 \\u3127-\\u3128 \\u3220-\\u3229 \\u32a3 \\u338e-\\u338f \\u339c-\\u339d \\u33a1 \\u33a5 \\u33d5 \\u33d1-\\u33d2 \\u359e \\u39d1 \\u41f2 \\u4341 \\u4d13 \\u4d15 \\u4e00-\\u9fff CJK \\uacf3 ++ \\ucd38 ++ \\ue20c-\\ue2ff ??? \\uf900-\\ufaff CJK ++ \\ufb03 \\ufe30-\\ufe31 \\ufe33 \\ufe38 \\ufe3c-\\ufe3d \\ufe3f-\\ufe41 \\ufe4d-\\ufe4e \\ufe55-\\ufe57 \\ufe59-\\ufe5c \\ufe5f \\ufe63 \\ufe65-\\ufe66 \\ufe6a-\\ufe6b \\ufeff arabic ++ # FE70-FEFF \\uff01 \\uff08-\\uff09 \\uff0c \\uff1a \\uff1f \\uff61 \\uff63 \\uff65 \\uff6c \\uff72 \\uff86 \\uff89 \\uffe0-\\uffe1 \\uffe3 \\uffe5 \\uffed \\ufffc """
[ 2, 28000, 1098, 198, 6738, 17268, 1330, 15034, 198, 11748, 10662, 64, 13, 260, 25636, 62, 26791, 355, 842, 22602, 198, 11748, 302, 198, 198, 31092, 62, 6978, 796, 12813, 11431, 14, 17209, 87, 76, 439, 14, 64, 27412, 1157, 7252, 12, ...
1.502941
12,242
from largest_product.py import largest_product import pytest def test_product_returns(): """test if return is a single product """ assert largest_product.largest([[2, 2]]) is 4 def test_returns_largest(): """ test if return is the largest of longer array """ assert largest_product.largest([[1, 3], [6, 10], [4, 5]]) is 60 def test_empty_list(): """ test if returns msg if empty list """ assert largest_product.largest([]) == 'empty arr used' def test_check_if_syb_has_only_1_el(): """test for one value""" arr = [3] val = 0 assert largest_product.node_inside(arr, val) == 3
[ 6738, 4387, 62, 11167, 13, 9078, 1330, 4387, 62, 11167, 198, 11748, 12972, 9288, 628, 198, 4299, 1332, 62, 11167, 62, 7783, 82, 33529, 198, 220, 220, 37227, 9288, 611, 1441, 318, 257, 2060, 1720, 37227, 198, 220, 220, 220, 6818, 4387,...
2.893023
215
# Copyright 2020 DeepMind Technologies Limited. 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. # ============================================================================== """Transformer model components.""" from typing import Optional import haiku as hk import jax import jax.numpy as jnp import numpy as np def layer_norm(x: jnp.ndarray, name: Optional[str] = None) -> jnp.ndarray: """Apply a unique LayerNorm to x with default settings.""" return hk.LayerNorm(axis=-1, create_scale=True, create_offset=True, name=name)(x)
[ 2, 15069, 12131, 10766, 28478, 21852, 15302, 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, 35...
3.244957
347
#!/usr/bin/env python import boto3 import cv2 import numpy import os import base64 import gspread from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from httplib2 import Http from time import localtime, strftime, time, sleep from oauth2client.service_account import ServiceAccountCredentials from apiclient import discovery, errors from apiclient.discovery import build from oauth2client import client from oauth2client import tools from oauth2client import file def compare_faces( bucket, key, bucket_target, key_target, threshold=80, region='us-east-1'): ''' Require for face comparision ''' rekognition = boto3.client('rekognition', region) response = rekognition.compare_faces( SourceImage={ 'S3Object': { 'Bucket': bucket, 'Name': key, } }, TargetImage={ 'S3Object': { 'Bucket': bucket_target, 'Name': key_target, } }, SimilarityThreshold=threshold, ) return response['SourceImageFace'], response['FaceMatches'] def upload_log(text): ''' Upload the Alert time to the google drive sheet ''' scope = ['https://spreadsheets.google.com/feeds'] credentials = ServiceAccountCredentials.from_json_keyfile_name( 'ProjectLog-41cafcffcf13.json', scope) gc = gspread.authorize(credentials) wks = gc.open('ISeeU_Log').sheet1 wks.append_row([text]) def send(service, user_id, message): ''' Send the mime email package ''' try: message = ( service.users().messages().send( userId=user_id, body=message).execute()) print('Message Id: %s' % message['id']) return message except errors.HttpError as error: print('An error occurred: %s' % error) def create_email(sender, to, subject, message_text, pic): ''' Create the email Included information: Sender, Receiver, Subject, Text, Attached Image ''' message = MIMEMultipart() message['to'] = to message['from'] = sender message['Subject'] = subject msg = MIMEText(message_text) message.attach(msg) fp = open(pic, 'rb') msg = MIMEImage(fp.read(), _subtype='jpeg') fp.close() imagename = os.path.basename(pic) msg.add_header('Content-Disposition', 'attachment', filename=imagename) message.attach(msg) return {'raw': base64.urlsafe_b64encode(message.as_string())} def authenticate(): ''' Using oauth2 to get the credentials. It will give all permission related to gmail. client_secret.json is the secret key you get from google. Reference: Gmail API python quickstart ''' SCOPES = 'https://mail.google.com' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = discovery.build('gmail', 'v1', http=creds.authorize(Http())) return service def stranger_detected(pic): ''' Recore the date time and make them as the code for the user the trigger alarm ''' nowtime = strftime("%Y-%m-%d %H:%M:%S", localtime()) trigcode = strftime("%d%H%M%S", localtime()) # Upload log to Google drive text = 'Stranger show up at ' + nowtime upload_log(text) # Information of email # pic = 'guldan.jpg' # Attached Image sender = "wenganq11@gmail.com" to = "wengq@bu.edu" # User email address subject = "Alert from ISeeU!" text = text + '\nReply ' + trigcode + ' to trigger the alarm.' # Sending email to user service = authenticate() message = create_email(sender, to, subject, text, pic) send(service, 'me', message) return service, subject, trigcode if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 275, 2069, 18, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 198, 11748, 28686, 198, 11748, 2779, 2414, 198, 11748, 308, 43639, 198, 6738, 3053, 13, 76, 524, 13, 8692, ...
2.45526
1,654
# -*- coding: utf-8 -*- """Implicitly reference attributes of an object.""" from ast import Name, Assign, Load, Call, Lambda, With, Str, arg, \ Attribute, Subscript, Store, Del from macropy.core.quotes import macros, q, u, name, ast_literal from macropy.core.hquotes import macros, hq from macropy.core.walkers import Walker from .util import wrapwith, AutorefMarker from .letdoutil import isdo, islet, ExpandedDoView, ExpandedLetView from ..dynassign import dyn from ..lazyutil import force1, mark_lazy # with autoref(o): # with autoref(scipy.loadmat("mydata.mat")): # evaluate once, assign to a gensym # with autoref(scipy.loadmat("mydata.mat")) as o: # evaluate once, assign to given name # # We need something like:: # # with autoref(o): # x # --> (o.x if hasattr(o, "x") else x) # x.a # --> (o.x.a if hasattr(o, "x") else x.a) # x[s] # --> (o.x[s] if hasattr(o, "x") else x[s]) # o # --> o # with autoref(p): # x # --> (p.x if hasattr(p, "x") else (o.x if hasattr(o, "x") else x)) # x.a # --> (p.x.a if hasattr(p, "x") else (o.x.a if hasattr(o, "x") else x.a)) # x[s] # --> (p.x[s] if hasattr(p, "x") else (o.x[s] if hasattr(o, "x") else x[s])) # o # --> (p.o if hasattr(p, "o") else o) # o.x # --> (p.o.x if hasattr(p, "o") else o.x) # o[s] # --> (p.o[s] if hasattr(p, "o") else o[s]) # # One possible clean-ish implementation is:: # # with AutorefMarker("o"): # no-op at runtime # x # --> (lambda _ar271: _ar271[1] if _ar271[0] else x)(_autoref_resolve((o, "x"))) # x.a # --> ((lambda _ar271: _ar271[1] if _ar271[0] else x)(_autoref_resolve((o, "x")))).a # x[s] # --> ((lambda _ar271: _ar271[1] if _ar271[0] else x)(_autoref_resolve((o, "x"))))[s] # o # --> o (can only occur if an asname is supplied) # with AutorefMarker("p"): # x # --> (lambda _ar314: _ar314[1] if _ar314[0] else x)(_autoref_resolve((p, o, "x"))) # x.a # --> ((lambda _ar314: _ar314[1] if _ar314[0] else x)(_autoref_resolve((p, o, "x"))).a # x[s] # --> ((lambda _ar314: _ar314[1] if _ar314[0] else x)(_autoref_resolve((p, o, "x")))[s] # # when the inner autoref expands, it doesn't know about the outer one, so we will get this: # o # --> (lambda _ar314: _ar314[1] if _ar314[0] else o)(_autoref_resolve((p, "o"))) # o.x # --> ((lambda _ar314: _ar314[1] if _ar314[0] else o)(_autoref_resolve((p, "o")))).x # o[s] # --> ((lambda _ar314: _ar314[1] if _ar314[0] else o)(_autoref_resolve((p, "o"))))[s] # # the outer autoref needs the marker to know to skip this (instead of looking up o.p): # p # --> p # # The lambda is needed, because the lexical-variable lookup for ``x`` must occur at the use site, # and it can only be performed by Python itself. We could modify ``_autoref_resolve`` to take # ``locals()`` and ``globals()`` as arguments and look also in the ``builtins`` module, # but that way we get no access to the enclosing scopes (the "E" in LEGB). # # Recall the blocks expand from inside out. # # We must leave an AST marker in place of the each autoref block, so that any outer autoref block (when it expands) # understands that within that block, any read access to the name "p" is to be left alone. # # In ``_autoref_resolve``, we use a single args parameter to avoid dealing with ``*args`` # when analyzing the Call node, thus avoiding much special-case code for the AST differences # between Python 3.4 and 3.5+. # # In reality, we also capture-and-assign the autoref'd expr into a gensym'd variable (instead of referring # to ``o`` and ``p`` directly), so that arbitrary expressions can be autoref'd without giving them # a name in user code.
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 29710, 3628, 306, 4941, 12608, 286, 281, 2134, 526, 15931, 198, 198, 6738, 6468, 1330, 6530, 11, 2195, 570, 11, 8778, 11, 4889, 11, 21114, 6814, 11, 2080, 11, 4...
2.294328
1,675
"""Handle exceptions generated from 'user' code""" import sys import traceback
[ 37811, 37508, 13269, 7560, 422, 705, 7220, 6, 2438, 37811, 198, 198, 11748, 25064, 198, 11748, 12854, 1891, 628, 628, 628, 628, 628, 628 ]
3.791667
24
# GUI used for quickly plotting BOSS spectra. Also allows overplotting of best-fit template as # determined by redmonster pipeline. Sort of a redmonster version of plotspec.pro, though currently # with less bells and whistles. # # Tim Hutchinson, University of Utah, April 2014 # Signifcantly updated by TH, October 2014 # # thutchinson@utah.edu from os import environ from os.path import join, exists try: from tkinter import * except ImportError: from Tkinter import * import numpy as n import matplotlib matplotlib.use('Agg') from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, \ NavigationToolbar2TkAgg from matplotlib.figure import Figure from astropy.io import fits from astropy.convolution import convolve, Box1DKernel import seaborn as sns sns.set_style('whitegrid') from redmonster.physics.misc import poly_array app = PlotFit()
[ 2, 25757, 973, 329, 2952, 29353, 347, 18420, 5444, 430, 13, 220, 4418, 3578, 625, 29487, 889, 286, 1266, 12, 11147, 11055, 355, 198, 2, 5295, 416, 2266, 39050, 11523, 13, 220, 33947, 286, 257, 2266, 39050, 2196, 286, 21528, 43106, 13,...
3.30916
262
# An algorithm to reconstruct the queue. # Suppose you have a random list of people standing in a queue. # Each person is described by a pair of integers (h,k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h.
[ 2, 1052, 11862, 284, 31081, 262, 16834, 13, 198, 2, 39200, 345, 423, 257, 4738, 1351, 286, 661, 5055, 287, 257, 16834, 13, 198, 2, 5501, 1048, 318, 3417, 416, 257, 5166, 286, 37014, 357, 71, 11, 74, 828, 810, 289, 318, 262, 6001, ...
4.183099
71
from django.db import models from django.utils.translation import gettext_lazy as _
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 651, 5239, 62, 75, 12582, 355, 4808 ]
3.608696
23
# -*- coding: utf-8 -*- """ This is part of HashBruteStation software Docs EN: http://hack4sec.pro/wiki/index.php/Hash_Brute_Station_en Docs RU: http://hack4sec.pro/wiki/index.php/Hash_Brute_Station License: MIT Copyright (c) Anton Kuzmin <http://anton-kuzmin.ru> (ru) <http://anton-kuzmin.pro> (en) Integration tests for HashlistsByAlgLoaderThread """ import sys import os import time import pytest sys.path.append('../../') from libs.common import file_get_contents, md5 from classes.HashlistsByAlgLoaderThread import HashlistsByAlgLoaderThread from CommonUnit import CommonUnit
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 1212, 318, 636, 286, 21059, 9414, 1133, 12367, 3788, 198, 23579, 82, 12964, 25, 2638, 1378, 31153, 19, 2363, 13, 1676, 14, 15466, 14, 9630, 13, 10121, 14, ...
2.8867
203
# statements that used at the start of defenition or in statements without columns defenition_statements = { "DROP": "DROP", "CREATE": "CREATE", "TABLE": "TABLE", "DATABASE": "DATABASE", "SCHEMA": "SCHEMA", "ALTER": "ALTER", "TYPE": "TYPE", "DOMAIN": "DOMAIN", "REPLACE": "REPLACE", "OR": "OR", "CLUSTERED": "CLUSTERED", "SEQUENCE": "SEQUENCE", "TABLESPACE": "TABLESPACE", } common_statements = { "INDEX": "INDEX", "REFERENCES": "REFERENCES", "KEY": "KEY", "ADD": "ADD", "AS": "AS", "CLONE": "CLONE", "DEFERRABLE": "DEFERRABLE", "INITIALLY": "INITIALLY", "IF": "IF", "NOT": "NOT", "EXISTS": "EXISTS", "ON": "ON", "FOR": "FOR", "ENCRYPT": "ENCRYPT", "SALT": "SALT", "NO": "NO", "USING": "USING", # bigquery "OPTIONS": "OPTIONS", } columns_defenition = { "DELETE": "DELETE", "UPDATE": "UPDATE", "NULL": "NULL", "ARRAY": "ARRAY", ",": "COMMA", "DEFAULT": "DEFAULT", "COLLATE": "COLLATE", "ENFORCED": "ENFORCED", "ENCODE": "ENCODE", "GENERATED": "GENERATED", "COMMENT": "COMMENT", } first_liners = { "LIKE": "LIKE", "CONSTRAINT": "CONSTRAINT", "FOREIGN": "FOREIGN", "PRIMARY": "PRIMARY", "UNIQUE": "UNIQUE", "CHECK": "CHECK", "WITH": "WITH", } common_statements.update(first_liners) defenition_statements.update(common_statements) after_columns_tokens = { "PARTITIONED": "PARTITIONED", "PARTITION": "PARTITION", "BY": "BY", # hql "INTO": "INTO", "STORED": "STORED", "LOCATION": "LOCATION", "ROW": "ROW", "FORMAT": "FORMAT", "TERMINATED": "TERMINATED", "COLLECTION": "COLLECTION", "ITEMS": "ITEMS", "MAP": "MAP", "KEYS": "KEYS", "SERDE": "SERDE", "CLUSTER": "CLUSTER", "SERDEPROPERTIES": "SERDEPROPERTIES", "TBLPROPERTIES": "TBLPROPERTIES", "SKEWED": "SKEWED", # oracle "STORAGE": "STORAGE", "TABLESPACE": "TABLESPACE", # mssql "TEXTIMAGE_ON": "TEXTIMAGE_ON", } sequence_reserved = { "INCREMENT": "INCREMENT", "START": "START", "MINVALUE": "MINVALUE", "MAXVALUE": "MAXVALUE", "CACHE": "CACHE", "NO": "NO", } tokens = tuple( set( ["ID", "DOT", "STRING", "DQ_STRING", "LP", "RP", "LT", "RT", "COMMAT"] + list(defenition_statements.values()) + list(common_statements.values()) + list(columns_defenition.values()) + list(sequence_reserved.values()) + list(after_columns_tokens.values()) ) ) symbol_tokens = { ")": "RP", "(": "LP", } symbol_tokens_no_check = {"<": "LT", ">": "RT"}
[ 2, 6299, 326, 973, 379, 262, 923, 286, 825, 268, 653, 393, 287, 6299, 1231, 15180, 198, 4299, 268, 653, 62, 14269, 3196, 796, 1391, 198, 220, 220, 220, 366, 7707, 3185, 1298, 366, 7707, 3185, 1600, 198, 220, 220, 220, 366, 43387, ...
1.998498
1,332
from __future__ import absolute_import, division, print_function import json import logging import os import time import importlib import multiprocessing import cv2 import fire import logzero from logzero import logger import numpy as np from rmexp import config, cvutils, dbutils, gabriel_pb2, client from rmexp.schema import models logzero.formatter(logging.Formatter( fmt='%(asctime)s.%(msecs)03d - %(levelname)s: %(message)s', datefmt='%H:%M:%S')) logzero.loglevel(logging.DEBUG) def work_loop(job_queue, app, busy_wait=None): """[summary] Arguments: job_queue {[type]} -- [description] app {[type]} -- [description] Keyword Arguments: busy_wait {float} -- if not None, busy spin seconds instead of running actual app (default: {None}) """ handler = importlib.import_module(app).Handler() while True: get_ts = time.time() msg = job_queue.get()[0] get_wait = time.time() - get_ts if get_wait > 2e-3: logger.warn("[pid {}] took {} ms to get a new request. Maybe waiting".format( os.getpid(), int(1000 * get_wait))) arrival_ts = time.time() gabriel_msg = gabriel_pb2.Message() gabriel_msg.ParseFromString(msg) encoded_im, ts = gabriel_msg.data, gabriel_msg.timestamp logger.debug("[pid {}] about to process frame {}".format( os.getpid(), gabriel_msg.index)) cts = time.clock() if not busy_wait: # do real work encoded_im_np = np.frombuffer(encoded_im, dtype=np.uint8) img = cv2.imdecode(encoded_im_np, cv2.CV_LOAD_IMAGE_UNCHANGED) result = handler.process(img) else: # busy wait fixed time tic = time.time() while True: if time.time() - tic > busy_wait: break result = 'busy wait {}'.format(busy_wait) finished_ts = time.time() time_lapse = (finished_ts - ts) * 1000 cpu_proc_ms = round((time.clock() - cts) * 1000) if gabriel_msg.reply: reply = gabriel_pb2.Message() reply.data = str(result) reply.timestamp = gabriel_msg.timestamp reply.index = gabriel_msg.index reply.finished_ts = finished_ts reply.arrival_ts = arrival_ts reply.cpu_proc_ms = cpu_proc_ms job_queue.put([reply.SerializeToString(), ]) logger.debug('[pid {}] takes {} ms (cpu: {} ms) for frame {}: {}.'.format( os.getpid(), (time.time() - ts) * 1000, cpu_proc_ms, gabriel_msg.index, result)) def batch_process(video_uri, app, experiment_name, trace=None, store_result=False, store_latency=False, store_profile=False, **kwargs): """Batch process a video. Able to store both the result and the frame processing latency. Arguments: video_uri {string} -- Video URI app {string} -- Applicaiton name experiment_name {string} -- Experiment name Keyword Arguments: trace {string} -- Trace id store_result {bool} -- Whether to store result into database store_result {bool} -- [description] (default: {False}) store_latency {bool} -- [description] (default: {False}) cpu {string} -- No of CPUs used. Used to populate profile database memory {string} -- No of memory used. Used to populate profile database num_worker {int} -- No of simultaneous workers. Used to populate profile database """ if trace is None: trace = os.path.basename(os.path.dirname(video_uri)) app = importlib.import_module(app) app_handler = app.Handler() vc = client.VideoClient( app.__name__, video_uri, None, loop=False, random_start=False) idx = 1 with dbutils.session_scope() as session: for img in vc.get_frame_generator(): cpu_time_ts = time.clock() result, time_lapse = process_and_time(img, app_handler) logger.debug("[pid: {}] processing frame {} from {}. {} ms".format(os.getpid(), idx, video_uri, int(time_lapse))) logger.debug(result) store( (experiment_name, trace, idx, result, time_lapse), session, store_result, store_latency, store_profile, **kwargs ) idx += 1 if __name__ == "__main__": fire.Fire()
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 198, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 640, 198, 11748, 1330, 8019, 198, 11748, 18540, 305, 919, 278, 198, 198, 11748, 269,...
2.138026
2,188
from .base import JsonRequest
[ 6738, 764, 8692, 1330, 449, 1559, 18453, 628, 198 ]
3.555556
9
if __name__ == "__main__": kmp('abcbabca', 'abcbabcabcbabcbabcbabcabcbabcbabca') kmp('abab', 'ababcabababc')
[ 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 479, 3149, 10786, 397, 21101, 397, 6888, 3256, 705, 397, 21101, 39305, 397, 21101, 397, 21101, 397, 21101, 39305, 397, 21101, 397, 21101, 397, 6888, ...
1.983333
60
# -*- coding: utf-8 -*- import os import json from os.path import dirname from argparse import ArgumentParser from clastic.render import AshesRenderFactory from common import DEBUG, DEBUG_LIST_ID, SENDKEY from web import (comma_int, ISSUE_TEMPLATES_PATH) from bake import (Issue, bake_latest_issue, render_index, SUPPORTED_LANGS) _CUR_PATH = dirname(os.path.abspath(__file__)) LIST_ID_MAP = json.load(open(os.path.join(_CUR_PATH, 'secrets.json'))).get('list_ids') if __name__ == '__main__': issue_ashes_env = AshesRenderFactory(ISSUE_TEMPLATES_PATH, filters={'ci': comma_int}).env parser = get_argparser() args = parser.parse_args() debug = args.debug if args.bake_all: for lang in SUPPORTED_LANGS: bake_latest_issue(issue_ashes_env, lang=lang, include_dev=debug) if args.lang in SUPPORTED_LANGS: lang = args.lang print bake_latest_issue(issue_ashes_env, lang=lang, include_dev=debug) print send_issue(lang, debug)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 198, 11748, 33918, 198, 6738, 28686, 13, 6978, 1330, 26672, 3672, 198, 6738, 1822, 29572, 1330, 45751, 46677, 198, 6738, 537, 3477, 13, 13287, 1330, 341...
2.210421
499
import random import sys # usage: python3 words_gen.py > list.txt N = int(sys.argv[1]) # how many words should be in the resulting list with open("scripts/words.txt", "r") as f: words = f.readlines() for i in range(N): print(words[random.randint(0, 466550 - 1)].rstrip())
[ 11748, 4738, 198, 11748, 25064, 198, 198, 2, 8748, 25, 21015, 18, 2456, 62, 5235, 13, 9078, 1875, 1351, 13, 14116, 198, 198, 45, 796, 493, 7, 17597, 13, 853, 85, 58, 16, 12962, 1303, 703, 867, 2456, 815, 307, 287, 262, 7186, 1351,...
2.607143
112
import unittest from modules.Input import * if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 6738, 13103, 13, 20560, 1330, 1635, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 198 ]
2.638889
36
#!/usr/bin/env python3 ############################################################################### # # # RMG - Reaction Mechanism Generator # # # # Copyright (c) 2002-2020 Prof. William H. Green (whgreen@mit.edu), # # Prof. Richard H. West (r.west@neu.edu) and the RMG Team (rmg_dev@mit.edu) # # # # 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. # # # ############################################################################### """ This script contains unit tests of the :mod:`rmgpy.kinetics.chebyshev` module. """ import unittest import numpy as np from rmgpy.exceptions import KineticsError from rmgpy.kinetics.chebyshev import Chebyshev ################################################################################ ################################################################################ if __name__ == '__main__': unittest.main(testRunner=unittest.TextTestRunner(verbosity=2))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 29113, 29113, 7804, 4242, 21017, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.262051
1,141
""" ----------------------------------------------------------------------------- This source file is part of VPET - Virtual Production Editing Tools http://vpet.research.animationsinstitut.de/ http://github.com/FilmakademieRnd/VPET Copyright (c) 2021 Filmakademie Baden-Wuerttemberg, Animationsinstitut R&D Lab This project has been initiated in the scope of the EU funded project Dreamspace under grant agreement no 610005 in the years 2014, 2015 and 2016. http://dreamspaceproject.eu/ Post Dreamspace the project has been further developed on behalf of the research and development activities of Animationsinstitut. The VPET component Blender Scene Distribution is intended for research and development purposes only. Commercial use of any kind is not permitted. There is no support by Filmakademie. Since the Blender Scene Distribution is available for free, Filmakademie shall only be liable for intent and gross negligence; warranty is limited to malice. Scene DistributiorUSD may under no circumstances be used for racist, sexual or any illegal purposes. In all non-commercial productions, scientific publications, prototypical non-commercial software tools, etc. using the Blender Scene Distribution Filmakademie has to be named as follows: VPET-Virtual Production Editing Tool by Filmakademie Baden-Wrttemberg, Animationsinstitut (http://research.animationsinstitut.de). In case a company or individual would like to use the Blender Scene Distribution in a commercial surrounding or for commercial purposes, software based on these components or any part thereof, the company/individual will have to contact Filmakademie (research<at>filmakademie.de). ----------------------------------------------------------------------------- """ bl_info = { "name" : "VPET Blender", "author" : "Tonio Freitag", "description" : "", "blender" : (2, 92, 2), "version" : (0, 5, 0), "location" : "VIEW3D", "warning" : "", "category" : "Animationsinstitut" } from typing import Set import bpy from .bl_op import DoDistribute from .bl_op import StopDistribute from .bl_op import SetupScene from .bl_op import InstallZMQ from .bl_panel import VPET_PT_Panel from .tools import initialize from .settings import VpetData from .settings import VpetProperties # imported classes to register classes = (DoDistribute, StopDistribute, SetupScene, VPET_PT_Panel, VpetProperties, InstallZMQ) ## Register classes and VpetSettings # ## Unregister for removal of Addon #
[ 37811, 198, 10097, 32501, 198, 1212, 2723, 2393, 318, 636, 286, 23342, 2767, 532, 15595, 19174, 39883, 20003, 198, 4023, 1378, 85, 6449, 13, 34033, 13, 11227, 602, 8625, 270, 315, 13, 2934, 14, 198, 4023, 1378, 12567, 13, 785, 14, 397...
3.759819
662
# Unlike the other datasets, CIFAR-10 uses ResNet and suffers from # a variety of problems, including exploding gradients import torch import torch.nn as nn from tqdm.notebook import tnrange, tqdm # For loading model sanely import os.path import sys # This here actually adds the path sys.path.append("../../") import models.resnet as resnet # Define the `device` PyTorch will be running on, please hope it is CUDA device = "cuda" if torch.cuda.is_available() else "cpu" print("Notebook will use PyTorch Device: " + device.upper()) # Helps adjust learning rate for better results # This method creates a new model and also trains it
[ 2, 12101, 262, 584, 40522, 11, 327, 5064, 1503, 12, 940, 3544, 1874, 7934, 290, 21046, 422, 198, 2, 257, 4996, 286, 2761, 11, 1390, 30990, 3915, 2334, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 6738, 256, 80...
3.454054
185
#!/usr/bin/env python3 # coding=utf-8 import copy from pathlib import Path from typing import ( Any, Generator, Iterable, List, MutableMapping, Optional, ) import toml from romt import error def get_package(self, package_name: str, target: str) -> Package: details = self._dict["pkg"][package_name]["target"][target] return Package(package_name, target, details) def gen_packages(self) -> Generator[Package, None, None]: """Generate Package for all (name, target) in manifest.""" for name, package_dict in self._dict["pkg"].items(): for target in package_dict["target"].keys(): yield self.get_package(name, target)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 19617, 28, 40477, 12, 23, 198, 198, 11748, 4866, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 357, 198, 220, 220, 220, 4377, 11, 198, 220, 220, 220, 35986, 11, ...
2.59058
276
from googlevoice import Voice voice = Voice() voice.login() for message in voice.sms().messages: #if not message.isRead: print(message.id, message.phoneNumber, message.messageText) #message.mark(1)
[ 6738, 23645, 38888, 1330, 15282, 198, 198, 38888, 796, 15282, 3419, 198, 38888, 13, 38235, 3419, 198, 198, 1640, 3275, 287, 3809, 13, 82, 907, 22446, 37348, 1095, 25, 198, 220, 220, 220, 1303, 361, 407, 3275, 13, 271, 5569, 25, 198, ...
2.90411
73
# coding: utf-8 from tornado.web import RequestHandler from libra.handlers.base import authenticated
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 6738, 33718, 13, 12384, 1330, 19390, 25060, 198, 6738, 9195, 430, 13, 4993, 8116, 13, 8692, 1330, 44529, 628 ]
3.777778
27
import click from plextraktsync.commands.login import ensure_login from plextraktsync.factory import factory from plextraktsync.walker import WalkConfig, Walker
[ 11748, 3904, 198, 198, 6738, 3339, 742, 17716, 912, 13361, 13, 9503, 1746, 13, 38235, 1330, 4155, 62, 38235, 198, 6738, 3339, 742, 17716, 912, 13361, 13, 69, 9548, 1330, 8860, 198, 6738, 3339, 742, 17716, 912, 13361, 13, 20783, 1330, ...
3.543478
46
import os import numpy as np from montepython.likelihood_class import Likelihood import montepython.io_mp as io_mp import warnings import ccl_tools as tools import pyccl as ccl
[ 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 40689, 538, 7535, 13, 2339, 11935, 62, 4871, 1330, 4525, 11935, 198, 11748, 40689, 538, 7535, 13, 952, 62, 3149, 355, 33245, 62, 3149, 198, 11748, 14601, 198, 11748, 269, 565,...
3.254545
55
from eth_utils import ( to_bytes, ) from eth_utils.toolz import ( identity, ) import pytest from web3._utils.module_testing.emitter_contract import ( CONTRACT_EMITTER_ABI, CONTRACT_EMITTER_CODE, ) from web3._utils.module_testing.math_contract import ( MATH_ABI, MATH_BYTECODE, ) from web3._utils.module_testing.revert_contract import ( _REVERT_CONTRACT_ABI, REVERT_CONTRACT_BYTECODE, )
[ 6738, 4555, 62, 26791, 1330, 357, 198, 220, 220, 220, 284, 62, 33661, 11, 198, 8, 198, 6738, 4555, 62, 26791, 13, 25981, 89, 1330, 357, 198, 220, 220, 220, 5369, 11, 198, 8, 198, 11748, 12972, 9288, 198, 6738, 3992, 18, 13557, 267...
2.370787
178
from __future__ import division import itertools import json import math import os import random import shutil import subprocess import sys durationA = str(5) durationB = str(4) durationC = str(1) if __name__ == "__main__": main()
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 198, 11748, 340, 861, 10141, 198, 11748, 33918, 198, 11748, 10688, 198, 11748, 28686, 198, 11748, 4738, 198, 11748, 4423, 346, 198, 11748, 850, 14681, 198, 11748, 25064, 198, 198, 32257, 32, 796, ...
3.025316
79
### # Copyright 2015-2020, Institute for Systems Biology # # 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 __future__ import print_function from builtins import str from builtins import object import os import re import datetime from os.path import join, dirname, exists import sys import dotenv from socket import gethostname, gethostbyname SECURE_LOCAL_PATH = os.environ.get('SECURE_LOCAL_PATH', '') if not exists(join(dirname(__file__), '../{}.env'.format(SECURE_LOCAL_PATH))): print("[ERROR] Couldn't open .env file expected at {}!".format( join(dirname(__file__), '../{}.env'.format(SECURE_LOCAL_PATH))) ) print("[ERROR] Exiting settings.py load - check your Pycharm settings and secure_path.env file.") exit(1) dotenv.read_dotenv(join(dirname(__file__), '../{}.env'.format(SECURE_LOCAL_PATH))) APP_ENGINE_FLEX = 'aef-' APP_ENGINE = 'Google App Engine/' BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) + os.sep SHARED_SOURCE_DIRECTORIES = [ 'IDC-Common' ] # Add the shared Django application subdirectory to the Python module search path for directory_name in SHARED_SOURCE_DIRECTORIES: sys.path.append(os.path.join(BASE_DIR, directory_name)) DEBUG = (os.environ.get('DEBUG', 'False') == 'True') CONNECTION_IS_LOCAL = (os.environ.get('DATABASE_HOST', '127.0.0.1') == 'localhost') IS_CIRCLE = (os.environ.get('CI', None) is not None) DEBUG_TOOLBAR = ((os.environ.get('DEBUG_TOOLBAR', 'False') == 'True') and CONNECTION_IS_LOCAL) IMG_QUOTA = os.environ.get('IMG_QUOTA', '137') print("[STATUS] DEBUG mode is {}".format(str(DEBUG)), file=sys.stdout) RESTRICT_ACCESS = (os.environ.get('RESTRICT_ACCESS', 'True') == 'True') RESTRICTED_ACCESS_GROUPS = os.environ.get('RESTRICTED_ACCESS_GROUPS', '').split(',') if RESTRICT_ACCESS: print("[STATUS] Access to the site is restricted to members of the {} group(s).".format(", ".join(RESTRICTED_ACCESS_GROUPS)), file=sys.stdout) else: print("[STATUS] Access to the site is NOT restricted!", file=sys.stdout) # Theoretically Nginx allows us to use '*' for ALLOWED_HOSTS but... ALLOWED_HOSTS = list(set(os.environ.get('ALLOWED_HOST', 'localhost').split(',') + ['localhost', '127.0.0.1', '[::1]', gethostname(), gethostbyname(gethostname()),])) #ALLOWED_HOSTS = ['*'] SSL_DIR = os.path.abspath(os.path.dirname(__file__))+os.sep ADMINS = () MANAGERS = ADMINS GCLOUD_PROJECT_ID = os.environ.get('GCLOUD_PROJECT_ID', '') GCLOUD_PROJECT_NUMBER = os.environ.get('GCLOUD_PROJECT_NUMBER', '') BIGQUERY_PROJECT_ID = os.environ.get('BIGQUERY_PROJECT_ID', GCLOUD_PROJECT_ID) BIGQUERY_DATA_PROJECT_ID = os.environ.get('BIGQUERY_DATA_PROJECT_ID', GCLOUD_PROJECT_ID) # Deployment module CRON_MODULE = os.environ.get('CRON_MODULE') # Log Names WEBAPP_LOGIN_LOG_NAME = os.environ.get('WEBAPP_LOGIN_LOG_NAME', 'local_dev_logging') BASE_URL = os.environ.get('BASE_URL', 'https://idc-dev.appspot.com') BASE_API_URL = os.environ.get('BASE_API_URL', 'https://api-dot-idc-dev.appspot.com') API_HOST = os.environ.get('API_HOST', 'api-dot-idc-dev.appspot.com') # Compute services - Should not be necessary in webapp PAIRWISE_SERVICE_URL = os.environ.get('PAIRWISE_SERVICE_URL', None) # Data Buckets GCLOUD_BUCKET = os.environ.get('GOOGLE_STORAGE_BUCKET') # BigQuery cohort storage settings BIGQUERY_COHORT_DATASET_ID = os.environ.get('BIGQUERY_COHORT_DATASET_ID', 'cohort_dataset') BIGQUERY_COHORT_TABLE_ID = os.environ.get('BIGQUERY_COHORT_TABLE_ID', 'developer_cohorts') BIGQUERY_IDC_TABLE_ID = os.environ.get('BIGQUERY_IDC_TABLE_ID', '') MAX_BQ_INSERT = int(os.environ.get('MAX_BQ_INSERT', '500')) USER_DATA_ON = bool(os.environ.get('USER_DATA_ON', 'False') == 'True') database_config = { 'default': { 'ENGINE': os.environ.get('DATABASE_ENGINE', 'django.db.backends.mysql'), 'HOST': os.environ.get('DATABASE_HOST', '127.0.0.1'), 'NAME': os.environ.get('DATABASE_NAME', 'dev'), 'USER': os.environ.get('DATABASE_USER', 'django-user'), 'PASSWORD': os.environ.get('DATABASE_PASSWORD') } } # On the build system, we need to use build-system specific database information if os.environ.get('CI', None) is not None: database_config = { 'default': { 'ENGINE': os.environ.get('DATABASE_ENGINE', 'django.db.backends.mysql'), 'HOST': os.environ.get('DATABASE_HOST_BUILD', '127.0.0.1'), 'NAME': os.environ.get('DATABASE_NAME_BUILD', ''), 'PORT': 3306, 'USER': os.environ.get('DATABASE_USER_BUILD'), 'PASSWORD': os.environ.get('MYSQL_ROOT_PASSWORD_BUILD') } } DATABASES = database_config DB_SOCKET = database_config['default']['HOST'] if 'cloudsql' in database_config['default']['HOST'] else None IS_DEV = (os.environ.get('IS_DEV', 'False') == 'True') IS_APP_ENGINE_FLEX = os.getenv('GAE_INSTANCE', '').startswith(APP_ENGINE_FLEX) IS_APP_ENGINE = os.getenv('SERVER_SOFTWARE', '').startswith(APP_ENGINE) VERSION = "{}.{}".format("local-dev", datetime.datetime.now().strftime('%Y%m%d%H%M')) if exists(join(dirname(__file__), '../version.env')): dotenv.read_dotenv(join(dirname(__file__), '../version.env')) else: if IS_DEV: import git repo = git.Repo(path="/home/vagrant/www/",search_parent_directories=True) VERSION = "{}.{}.{}".format("local-dev", datetime.datetime.now().strftime('%Y%m%d%H%M'), str(repo.head.object.hexsha)[-6:]) APP_VERSION = os.environ.get("APP_VERSION", VERSION) DEV_TIER = bool(DEBUG or re.search(r'^dev\.',APP_VERSION)) # If this is a GAE-Flex deployment, we don't need to specify SSL; the proxy will take # care of that for us if 'DB_SSL_CERT' in os.environ and not IS_APP_ENGINE_FLEX: DATABASES['default']['OPTIONS'] = { 'ssl': { 'ca': os.environ.get('DB_SSL_CA'), 'cert': os.environ.get('DB_SSL_CERT'), 'key': os.environ.get('DB_SSL_KEY') } } # Default to localhost for the site ID SITE_ID = 2 if IS_APP_ENGINE_FLEX or IS_APP_ENGINE: print("[STATUS] AppEngine Flex detected.", file=sys.stdout) SITE_ID = 3 # Set cohort table here if BIGQUERY_COHORT_TABLE_ID is None: raise Exception("Developer-specific cohort table ID is not set.") BQ_MAX_ATTEMPTS = int(os.environ.get('BQ_MAX_ATTEMPTS', '10')) API_USER = os.environ.get('API_USER', 'api_user') API_AUTH_KEY = os.environ.get('API_AUTH_KEY', 'Token') # TODO Remove duplicate class. # # This class is retained here, as it is required by bq_data_access/v1. # bq_data_access/v2 uses the class from the bq_data_access/bigquery_cohorts module. USE_CLOUD_STORAGE = bool(os.environ.get('USE_CLOUD_STORAGE', 'False') == 'True') SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') CSRF_COOKIE_SECURE = bool(os.environ.get('CSRF_COOKIE_SECURE', 'True') == 'True') SESSION_COOKIE_SECURE = bool(os.environ.get('SESSION_COOKIE_SECURE', 'True') == 'True') SECURE_SSL_REDIRECT = bool(os.environ.get('SECURE_SSL_REDIRECT', 'True') == 'True') SECURE_REDIRECT_EXEMPT = [] if SECURE_SSL_REDIRECT: # Exempt the health check so it can go through SECURE_REDIRECT_EXEMPT = [r'^_ah/(vm_)?health$', ] # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Los_Angeles' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_FOLDER = os.environ.get('MEDIA_FOLDER', 'uploads/') MEDIA_ROOT = os.path.join(os.path.dirname(__file__), '..', '..', MEDIA_FOLDER) MEDIA_ROOT = os.path.normpath(MEDIA_ROOT) # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = 'static_collex' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = os.environ.get('STATIC_URL', '/static/') GCS_STORAGE_URI = os.environ.get('GCS_STORAGE_URI', 'https://storage.googleapis.com/') # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. os.path.join(BASE_DIR, 'static'), ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', '') SECURE_HSTS_INCLUDE_SUBDOMAINS = (os.environ.get('SECURE_HSTS_INCLUDE_SUBDOMAINS','True') == 'True') SECURE_HSTS_PRELOAD = (os.environ.get('SECURE_HSTS_PRELOAD','True') == 'True') SECURE_HSTS_SECONDS = int(os.environ.get('SECURE_HSTS_SECONDS','3600')) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'idc.checkreqsize_middleware.CheckReqSize', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'adminrestrict.middleware.AdminPagesRestrictMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'idc.team_only_middleware.TeamOnly', # Uncomment the next line for simple clickjacking protection: 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'offline.middleware.OfflineMiddleware', ] ROOT_URLCONF = 'idc.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'idc.wsgi.application' INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'anymail', 'idc', 'data_upload', 'sharing', 'cohorts', 'idc_collections', 'offline', 'adminrestrict' ) ############################# # django-session-security # ############################# INSTALLED_APPS += ('session_security',) SESSION_SECURITY_WARN_AFTER = int(os.environ.get('SESSION_SECURITY_WARN_AFTER','540')) SESSION_SECURITY_EXPIRE_AFTER = int(os.environ.get('SESSION_SECURITY_EXPIRE_AFTER','600')) SESSION_EXPIRE_AT_BROWSER_CLOSE = True MIDDLEWARE.append( # for django-session-security -- must go *after* AuthenticationMiddleware 'session_security.middleware.SessionSecurityMiddleware', ) ############################### # End django-session-security # ############################### TEST_RUNNER = 'django.test.runner.DiscoverRunner' # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue' }, }, 'formatters': { 'verbose': { 'format': '[%(levelname)s] @%(asctime)s in %(module)s/%(process)d/%(thread)d - %(message)s' }, 'simple': { 'format': '[%(levelname)s] @%(asctime)s in %(module)s: %(message)s' }, }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'console_dev': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, 'console_prod': { 'level': 'DEBUG', 'filters': ['require_debug_false'], 'class': 'logging.StreamHandler', 'formatter': 'simple', }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'main_logger': { 'handlers': ['console_dev', 'console_prod'], 'level': 'DEBUG', 'propagate': True, }, 'allauth': { 'handlers': ['console_dev', 'console_prod'], 'level': 'DEBUG', 'propagate': True, }, 'google_helpers': { 'handlers': ['console_dev', 'console_prod'], 'level': 'DEBUG', 'propagate': True, }, 'data_upload': { 'handlers': ['console_dev', 'console_prod'], 'level': 'DEBUG', 'propagate': True, }, }, } # Force allauth to only use https ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https' # ...but not if this is a local dev build if IS_DEV: ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'http' ########################## # Start django-allauth # ########################## LOGIN_REDIRECT_URL = '/extended_login/' INSTALLED_APPS += ( 'accounts', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'rest_framework.authtoken' ) # Template Engine Settings TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # add any necessary template paths here 'DIRS': [ os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'templates', 'accounts'), ], 'APP_DIRS': True, 'OPTIONS': { # add any context processors here 'context_processors': ( 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.tz', 'finalware.context_processors.contextify', 'idc.context_processor.additional_context', ), # add any loaders here; if using the defaults, we can comment it out # 'loaders': ( # 'django.template.loaders.filesystem.Loader', # 'django.template.loaders.app_directories.Loader' # ), 'debug': DEBUG, }, }, ] AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` "django.contrib.auth.backends.ModelBackend", # `allauth` specific authentication methods, such as login by e-mail "allauth.account.auth_backends.AuthenticationBackend", ) SOCIALACCOUNT_PROVIDERS = \ { 'google': { 'SCOPE': ['profile', 'email'], 'AUTH_PARAMS': { 'access_type': 'online' } } } ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = bool(os.environ.get('ACCOUNT_USERNAME_REQUIRED', 'False') == 'True') ACCOUNT_EMAIL_VERIFICATION = os.environ.get('ACCOUNT_EMAIL_VERIFICATION', 'mandatory').lower() ACCOUNT_EMAIL_SUBJECT_PREFIX = "[Imaging Data Commons] " ACCOUNTS_PASSWORD_EXPIRATION = os.environ.get('ACCOUNTS_PASSWORD_EXPIRATION',120) # Max password age in days ACCOUNTS_PASSWORD_HISTORY = os.environ.get('ACCOUNTS_PASSWORD_HISTORY', 5) # Max password history kept ACCOUNTS_ALLOWANCES = list(set(os.environ.get('ACCOUNTS_ALLOWANCES','').split(','))) ########################## # End django-allauth # ########################## ########################## # Django local auth # ########################## AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 16, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'idc.validators.PasswordComplexityValidator', 'OPTIONS': { 'min_length': 16, 'special_char_list': '!@#$%^&*+:;?' } }, { 'NAME': 'idc.validators.PasswordReuseValidator' } ] ######################################### # MailGun Email Settings for requests # ######################################### # # These settings allow use of MailGun as a simple API call EMAIL_SERVICE_API_URL = os.environ.get('EMAIL_SERVICE_API_URL', '') EMAIL_SERVICE_API_KEY = os.environ.get('EMAIL_SERVICE_API_KEY', '') NOTIFICATION_EMAIL_FROM_ADDRESS = os.environ.get('NOTIFICATOON_EMAIL_FROM_ADDRESS', 'info@canceridc.dev') ######################### # django-anymail # ######################### # # Anymail lets us use the Django mail system with mailgun (eg. in local account email verification) ANYMAIL = { "MAILGUN_API_KEY": EMAIL_SERVICE_API_KEY, "MAILGUN_SENDER_DOMAIN": 'mg.canceridc.dev', # your Mailgun domain, if needed } EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend" DEFAULT_FROM_EMAIL = NOTIFICATION_EMAIL_FROM_ADDRESS SERVER_EMAIL = "info@canceridc.dev" GOOGLE_APPLICATION_CREDENTIALS = join(dirname(__file__), '../{}{}'.format(SECURE_LOCAL_PATH,os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''))) OAUTH2_CLIENT_ID = os.environ.get('OAUTH2_CLIENT_ID', '') OAUTH2_CLIENT_SECRET = os.environ.get('OAUTH2_CLIENT_SECRET', '') if not exists(GOOGLE_APPLICATION_CREDENTIALS): print("[ERROR] Google application credentials file wasn't found! Provided path: {}".format(GOOGLE_APPLICATION_CREDENTIALS)) exit(1) ################################# # For NIH/eRA Commons login # ################################# GOOGLE_GROUP_ADMIN = os.environ.get('GOOGLE_GROUP_ADMIN', '') SUPERADMIN_FOR_REPORTS = os.environ.get('SUPERADMIN_FOR_REPORTS', '') ############################## # Start django-finalware # ############################## # # This should only be done on a local system which is running against its own VM, or during CircleCI testing. # Deployed systems will already have a site superuser so this would simply overwrite that user. # NEVER ENABLE this in production! # if (IS_DEV and CONNECTION_IS_LOCAL) or IS_CIRCLE: INSTALLED_APPS += ( 'finalware',) SITE_SUPERUSER_USERNAME = os.environ.get('SUPERUSER_USERNAME', '') SITE_SUPERUSER_EMAIL = '' SITE_SUPERUSER_PASSWORD = os.environ.get('SUPERUSER_PASSWORD') # ############################ # End django-finalware # ############################ CONN_MAX_AGE = 60 ############################ # CUSTOM TEMPLATE CONTEXT ############################ ############################ # METRICS SETTINGS ############################ SITE_GOOGLE_ANALYTICS = bool(os.environ.get('SITE_GOOGLE_ANALYTICS_TRACKING_ID', None) is not None) SITE_GOOGLE_ANALYTICS_TRACKING_ID = os.environ.get('SITE_GOOGLE_ANALYTICS_TRACKING_ID', '') ############################################################## # MAXes to prevent size-limited events from causing errors ############################################################## # Google App Engine has a response size limit of 32M. ~65k entries from the cohort_filelist view will # equal just under the 32M limit. If each individual listing is ever lengthened or shortened this # number should be adjusted MAX_FILE_LIST_REQUEST = 65000 MAX_BQ_RECORD_RESULT = int(os.environ.get('MAX_BQ_RECORD_RESULT', '5000')) # Rough max file size to allow for eg. barcode list upload, to prevent triggering RequestDataTooBig FILE_SIZE_UPLOAD_MAX = 1950000 ################################# # DICOM Viewer settings ################################# DICOM_VIEWER = os.environ.get('DICOM_VIEWER', None) ################################# # SOLR settings ################################# SOLR_URI = os.environ.get('SOLR_URI', '') SOLR_LOGIN = os.environ.get('SOLR_LOGIN', '') SOLR_PASSWORD = os.environ.get('SOLR_PASSWORD', '') SOLR_CERT = join(dirname(dirname(__file__)), "{}{}".format(SECURE_LOCAL_PATH, os.environ.get('SOLR_CERT', ''))) DEFAULT_FETCH_COUNT = os.environ.get('DEFAULT_FETCH_COUNT', 10) # Explicitly check for known problems in descrpitions and names provided by users BLACKLIST_RE = r'((?i)<script>|(?i)</script>|!\[\]|!!\[\]|\[\]\[\".*\"\]|(?i)<iframe>|(?i)</iframe>)' if DEBUG and DEBUG_TOOLBAR: INSTALLED_APPS += ('debug_toolbar',) MIDDLEWARE.append('debug_toolbar.middleware.DebugToolbarMiddleware',) DEBUG_TOOLBAR_PANELS = [ 'debug_toolbar.panels.versions.VersionsPanel', 'debug_toolbar.panels.timer.TimerPanel', 'debug_toolbar.panels.settings.SettingsPanel', 'debug_toolbar.panels.headers.HeadersPanel', 'debug_toolbar.panels.request.RequestPanel', 'debug_toolbar.panels.sql.SQLPanel', 'debug_toolbar.panels.staticfiles.StaticFilesPanel', 'debug_toolbar.panels.templates.TemplatesPanel', 'debug_toolbar.panels.cache.CachePanel', 'debug_toolbar.panels.signals.SignalsPanel', 'debug_toolbar.panels.logging.LoggingPanel', 'debug_toolbar.panels.redirects.RedirectsPanel', ] SHOW_TOOLBAR_CALLBACK = True INTERNAL_IPS = (os.environ.get('INTERNAL_IP', ''),) ################## # OHIF_SETTINGS ################## # # default is to add trailing '/' to urls ie /callback becomes /callback/. Ohif does not like /callback/ ! APPEND_SLASH = False DICOM_STORE_PATH=os.environ.get('DICOM_STORE_PATH','') # Log the version of our app print("[STATUS] Application Version is {}".format(APP_VERSION))
[ 21017, 198, 2, 15069, 1853, 12, 42334, 11, 5136, 329, 11998, 24698, 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, ...
2.391449
9,940
# Created by yingwen at 2019-03-16 from multiprocessing import Process from malib.agents.agent_factory import * from malib.environments import DifferentialGame from malib.logger.utils import set_logger from malib.samplers.sampler import MASampler from malib.trainers import MATrainer from malib.utils.random import set_seed if __name__ == "__main__": main()
[ 2, 15622, 416, 331, 278, 21006, 379, 13130, 12, 3070, 12, 1433, 198, 6738, 18540, 305, 919, 278, 1330, 10854, 198, 198, 6738, 6428, 571, 13, 49638, 13, 25781, 62, 69, 9548, 1330, 1635, 198, 6738, 6428, 571, 13, 268, 12103, 1330, 206...
3.118644
118
import decimal from django import template register = template.Library()
[ 11748, 32465, 198, 198, 6738, 42625, 14208, 1330, 11055, 198, 198, 30238, 796, 11055, 13, 23377, 3419, 628, 628, 198 ]
3.95
20
""" pylabnet measurement and service classes for Swabian Instruments TimeTagger which implements qudi's SlowCounter interface. This file contains pylabnet wrapper and service classes to allow qudi to access Swabian Instruments TT through pylabnet network as SlowCounter. Steps: - instantiate TimeTagger - instantiate pylabnet-SlowCtrWrap (pass ref to TimeTagger as tagger) - instantiate pylabnet-SlowCtrService and assign module to the created wrapper - start pylabnet-server for SlowCtrService - in qudi, instantiate SlowCtrClient as one of the hardware modules """ from pylabnet.network.core.service_base import ServiceBase import TimeTagger as TT import time import copy import pickle
[ 37811, 279, 2645, 397, 3262, 15558, 290, 2139, 6097, 329, 2451, 397, 666, 43953, 3862, 51, 7928, 198, 4758, 23986, 627, 10989, 338, 19054, 31694, 7071, 13, 198, 198, 1212, 2393, 4909, 279, 2645, 397, 3262, 29908, 290, 2139, 6097, 284, ...
3.647368
190
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Must still be recoded with some cleaner code. """ # imports. from dev0s.classes.config import * from dev0s.classes import utils from dev0s.classes.defaults.color import color, symbol from dev0s.classes import console from dev0s.classes.defaults.exceptions import Exceptions # pip. from datetime import datetime, timezone import shutil, math from PIL import Image as _Image_ """ Notes. All default files & formats must exact the same as the default dict, bool, list etc in the native sense. There are lots additionals though. But a dict and Dictionary should be able to be used universally as if the user would not know the difference (which could very quickly in some instances). """ # the format classes. # the string object class. # return raw data. def raw(self): return self.str # # the boolean object class. # return raw data. def raw(self): return self.bool # # the integer object class. # the date object class. # the files class. # # the directory object class. # # the image object class. # suport eq. def __eq__(self, var): if var.__class__.__name__ in ["NoneType"]: return False else: return str(var) == str(self) def __ne__(self, var): if var.__class__.__name__ in ["NoneType"]: return True else: return str(var) != str(self) # repr. # # # the zip object class. # # # the bytes object class. # return raw data. def raw(self): return self.bytes # # # # # some default classes. # some default objects. # shortcuts. FilePath = Formats.FilePath String = Formats.String Boolean = Formats.Boolean Integer = Formats.Integer Date = Formats.Date File = Files.File Directory = Files.Directory Zip = Files.Zip Image = Files.Image Bytes = Files.Bytes Dictionary = Files.Dictionary Array = Files.Array Speed = Classes.Speed Generate = Objects.Generate Interval = Objects.Interval # initialized objects. gfp = Formats.FilePath("") # is required (do not remove). gd = gdate = Formats.Date() #
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 34320, 991, 307, 664, 9043, 351, 617, 21723, 2438, 13, 198, 37811, 198, 198, 2, 17944, 13, 198, 6738,...
2.90085
706
import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * main()
[ 11748, 12972, 6057, 198, 6738, 12972, 6057, 13, 17946, 874, 1330, 1635, 198, 198, 6738, 30672, 13, 8763, 1330, 1635, 198, 6738, 30672, 13, 8763, 52, 1330, 1635, 198, 6738, 30672, 13, 8763, 3843, 1330, 1635, 198, 198, 12417, 3419 ]
3.125
40
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # [START translate_v3_batch_translate_text_with_glossary_and_model] from google.cloud import translate def batch_translate_text_with_glossary_and_model( input_uri="gs://YOUR_BUCKET_ID/path/to/your/file.txt", output_uri="gs://YOUR_BUCKET_ID/path/to/save/results/", project_id="YOUR_PROJECT_ID", model_id="YOUR_MODEL_ID", glossary_id="YOUR_GLOSSARY_ID", ): """ Batch translate text with Glossary and Translation model """ client = translate.TranslationServiceClient() # Supported language codes: https://cloud.google.com/translate/docs/languages location = "us-central1" target_language_codes = ["ja"] gcs_source = {"input_uri": input_uri} # Optional. Can be "text/plain" or "text/html". mime_type = "text/plain" input_configs_element = {"gcs_source": gcs_source, "mime_type": mime_type} input_configs = [input_configs_element] gcs_destination = {"output_uri_prefix": output_uri} output_config = {"gcs_destination": gcs_destination} parent = f"projects/{project_id}/locations/{location}" model_path = "projects/{}/locations/{}/models/{}".format( project_id, "us-central1", model_id ) models = {"ja": model_path} glossary_path = client.glossary_path( project_id, "us-central1", glossary_id # The location of the glossary ) glossary_config = translate.TranslateTextGlossaryConfig(glossary=glossary_path) glossaries = {"ja": glossary_config} # target lang as key operation = client.batch_translate_text( request={ "parent": parent, "source_language_code": "en", "target_language_codes": target_language_codes, "input_configs": input_configs, "output_config": output_config, "models": models, "glossaries": glossaries, } ) print("Waiting for operation to complete...") response = operation.result() # Display the translation for each input text provided print("Total Characters: {}".format(response.total_characters)) print("Translated Characters: {}".format(response.translated_characters)) # [END translate_v3_batch_translate_text_with_glossary_and_model]
[ 2, 15069, 13130, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 733...
2.736533
1,021
#!/usr/bin/env python import roslib; roslib.load_manifest('smach_ros') import rospy import rostest import unittest from actionlib import * from actionlib.msg import * from smach import * from smach_ros import * from smach_msgs.msg import * # Static goals g1 = TestGoal(1) # This goal should succeed g2 = TestGoal(2) # This goal should abort g3 = TestGoal(3) # This goal should be rejected ### Custom tate classe ### Test harness def main(): rospy.init_node('concurrence_test',log_level=rospy.DEBUG) rostest.rosrun('smach', 'concurrence_test', TestStateMachine) if __name__=="__main__": main();
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 686, 6649, 571, 26, 686, 6649, 571, 13, 2220, 62, 805, 8409, 10786, 5796, 620, 62, 4951, 11537, 198, 11748, 686, 2777, 88, 198, 11748, 686, 301, 395, 198, 198, 11748, 555...
2.737778
225
from django.db import models # Create your models here. ########################################################################## # ##########################################################################
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 198, 2, 13610, 534, 4981, 994, 13, 198, 29113, 29113, 7804, 2235, 198, 2, 198, 198, 29113, 29113, 7804, 2235 ]
7.464286
28
import argparse import torch if __name__ == '__main__': get_args()
[ 11748, 1822, 29572, 198, 11748, 28034, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 651, 62, 22046, 3419 ]
2.769231
26
from .backbone_nas import * from .adelaide_ea import * from .sr_ea import * from .esr_ea import * from .darts_cnn import * from .cars import * from .fis import * from .auto_lane import * from .mfkd import *
[ 6738, 764, 1891, 15992, 62, 24716, 1330, 1635, 198, 6738, 764, 6959, 64, 485, 62, 18213, 1330, 1635, 198, 6738, 764, 27891, 62, 18213, 1330, 1635, 198, 6738, 764, 274, 81, 62, 18213, 1330, 1635, 198, 6738, 764, 67, 5889, 62, 66, 204...
2.723684
76
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 9 12:27:15 2021 @author: kuba """ import copy import numpy as np w = {"H0": {"H0":0.2,"H1": 0.2, "P0": 0.5, "P1": 0.1}, "H1": {"H0":0.2,"H1": 0.2, "P0": 0.1, "P1": 0.5}, "P0": {"H0":0.3,"H1": 0.3, "P0": 0.2, "P1": 0.2}, "P1": {"H0":0.3,"H1": 0.3, "P0": 0.2, "P1": 0.2} } if __name__ == "__main__": c1 = Card(1) c2 = Card(2) c3 = Card(3) c4 = Card(4) c5 = Card(5) cards1 = [c5, c1] cards2 = [c2, c4] table = [0] deck = 1 parent = None player = 2 state = State(player,cards1,cards2,table,deck, parent) initial_belief_states = [state] solver = Solver(2) actions = [(Actions.Play, "P"), (Actions.Hint, "H")] terminal = solver.forward2(initial_belief_states, actions) """ print("Some tests to see the Actions funtioning:") print("0.Initial state with cards: player1: (1,2), player2: (3,4)") state1 = State(1,[Card(1),Card(2)],[Card(4),Card(5)],[0],1,None) print("") print("1.Making a Hint of the 2nd player right card:") state2 = Actions.Hint(state1,1) #check that the card is now "known" and that the player becomes "2" print("Is the card known? {}. What player turn is it after the action? {}.".format(state2[0].cards2[1].known,state2[0].player)) print("") print("2. Playing the correct card from player 1's left (the 1):") state2b = Actions.Play(state1,0) print("New size of deck: {}. New card on the left for player 1: {}. New table: {}. Amount of new states created: {}".format(state2b[0].deck,state2b[0].cards1[0].number,state2b[0].table,len(state2b))) print(state2[0].depth) state3 = Actions.Hint(state2[0],1) print(state3[0].depth) state4 = Actions.Hint(state3[0],1) print(state4[0].depth) """
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 30030, 1526, 220, 860, 1105, 25, 1983, 25, 1314, 33448, 198, 198, 31, 9800, 25, 479, 2201...
2.08443
912
# course: ICS3U1 2019 # exercise: Culminating Activity # date: 2019-12-06 # student number: 340926187 # name: Brandon Ly # description: Two players (Mr Chun & Mr Pileggi) running around the school # collecting food for the food drive. # sprite classes import pygame import random import math import os from settings import *
[ 2, 220, 220, 220, 220, 220, 220, 220, 220, 1781, 25, 314, 7902, 18, 52, 16, 13130, 198, 2, 220, 220, 220, 220, 220, 220, 5517, 25, 32559, 1084, 803, 24641, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 3128, 25, 13...
2.56
150
from typing import Optional, List from pydantic import BaseModel
[ 6738, 19720, 1330, 32233, 11, 7343, 198, 6738, 279, 5173, 5109, 1330, 7308, 17633, 628, 198 ]
4.1875
16
from abc import ABCMeta, abstractmethod from collections import OrderedDict from math import inf from typing import Iterator, Any, List, Dict, Type, Optional EPSILON = 1e-4
[ 6738, 450, 66, 1330, 9738, 48526, 11, 12531, 24396, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 6738, 10688, 1330, 1167, 198, 6738, 19720, 1330, 40806, 1352, 11, 4377, 11, 7343, 11, 360, 713, 11, 5994, 11, 32233, 198, 198, 36, ...
3.285714
56
input = """154, 159 172, 84 235, 204 181, 122 161, 337 305, 104 128, 298 176, 328 146, 71 210, 87 341, 195 50, 96 225, 151 86, 171 239, 68 79, 50 191, 284 200, 122 282, 240 224, 282 327, 74 158, 289 331, 244 154, 327 317, 110 272, 179 173, 175 187, 104 44, 194 202, 332 249, 197 244, 225 52, 127 299, 198 123, 198 349, 75 233, 72 284, 130 119, 150 172, 355 147, 314 58, 335 341, 348 236, 115 185, 270 173, 145 46, 288 214, 127 158, 293 237, 311""" from collections import namedtuple Point = namedtuple("Point", ["id", "x", "y"]) points = set() for id, line in enumerate(input.splitlines()): words = line.split(",") x, y = [int(a) for a in words] points.add(Point(id, x, y)) # get bounds a_point = next(iter(points)) left_bound = a_point.x right_bound = a_point.x up_bound = a_point.y down_bound = a_point.y for p in points: if p.x < left_bound: left_bound = p.x if p.x > right_bound: right_bound = p.x if p.y < up_bound: up_bound = p.y if p.y > down_bound: down_bound = p.y # Find closest points within the bounds # Anything outside the bounds is uninteresting as it just leads off into infinite space grid = [ [0] * (right_bound - left_bound + 1) for i in range(down_bound - up_bound + 1) ] for y in range(up_bound, down_bound + 1): for x in range(left_bound, right_bound + 1): closest_points = find_closest(Point(id=None, x=x, y=y), points) if len(closest_points) > 1: grid[y-up_bound][x-left_bound] = -1 elif len(closest_points) == 0: print("wtf") exit(1) else: grid[y - up_bound][x - left_bound] = closest_points.pop() # We have our grid, we can remove any point ids that lie on the edge as they # will continue off to infinity candidate_ids = {p.id for p in points} for y in [0, down_bound - up_bound]: for x in [0, right_bound - left_bound]: if grid[y][x] in candidate_ids: candidate_ids.remove(grid[y][x]) # we have our contenders # now find which has the smallest finite space ids_to_count = {} for y in range(0, down_bound - up_bound + 1): for x in range(0, right_bound - left_bound + 1): if grid[y][x] in candidate_ids: if grid[y][x] not in ids_to_count: ids_to_count[grid[y][x]] = 0 ids_to_count[grid[y][x]] += 1 print(max(ids_to_count.values()))
[ 15414, 796, 37227, 21526, 11, 26422, 198, 23628, 11, 9508, 198, 22370, 11, 26956, 198, 27057, 11, 19409, 198, 25948, 11, 42294, 198, 22515, 11, 14436, 198, 12762, 11, 37576, 198, 24096, 11, 39093, 198, 20964, 11, 9166, 198, 21536, 11, ...
2.249297
1,067
import os from Backupy import Backupy
[ 11748, 28686, 198, 6738, 35071, 88, 1330, 35071, 88, 628 ]
3.9
10
#!/usr/bin/python # -*- coding: utf-8 -*- # import logging logger = logging.getLogger(__name__) import multiprocessing as mp import tweetf0rm.handler from tweetf0rm.redis_helper import CrawlerQueue #MAX_QUEUE_SIZE = 32767
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 11748, 18931, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 198, 198, 11748, 18540,...
2.473118
93
# Copyright (c) 2018 Cloudify Platform Ltd. 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. """ EC2.DhcpOptions ~~~~~~~~~~~~~~ AWS EC2 DhcpOptions interface """ # Boto from botocore.exceptions import ClientError # Cloudify from cloudify_aws.common import decorators, utils from cloudify_aws.ec2 import EC2Base from cloudify_aws.common.constants import EXTERNAL_RESOURCE_ID RESOURCE_TYPE = 'EC2 Dhcp Options' DHCPOPTIONS = 'DhcpOptions' DHCPOPTIONS_ID = 'DhcpOptionsId' DHCPOPTIONS_IDS = 'DhcpOptionsIds' VPC_ID = 'VpcId' VPC_TYPE = 'cloudify.nodes.aws.ec2.Vpc' VPC_TYPE_DEPRECATED = 'cloudify.aws.nodes.Vpc'
[ 2, 15069, 357, 66, 8, 2864, 10130, 1958, 19193, 12052, 13, 1439, 2489, 10395, 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, 1...
3.039683
378
# Copyright 2010 New Relic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: from urllib2 import urlopen # Py2.X except ImportError: from urllib.request import urlopen # Py3.X import sqlite3 as db from newrelic.api.time_trace import record_exception from newrelic.api.transaction import (add_custom_parameter, get_browser_timing_header, get_browser_timing_footer, record_custom_event) from newrelic.api.wsgi_application import wsgi_application _custom_parameters = { 'user' : 'user-name', 'account' : 'account-name', 'product' : 'product-name', 'bytes' : b'bytes-value', 'string' : 'string-value', 'unicode' : u'unicode-value', 'integer' : 1, 'float' : 1.0, 'invalid-utf8' : b'\xe2', 'multibyte-utf8' : b'\xe2\x88\x9a', 'multibyte-unicode' : b'\xe2\x88\x9a'.decode('utf-8'), 'list' : [], 'tuple' : (), 'dict' : {}, } _err_param = { 'err-param' : 'value' } def user_attributes_added(): """Expected values when the custom parameters in this file are added as user attributes """ user_attributes = _custom_parameters.copy() user_attributes['list'] = '[]' user_attributes['tuple'] = '()' user_attributes['dict'] = '{}' return user_attributes
[ 2, 15069, 3050, 968, 43437, 11, 3457, 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, 13, 198, 2, ...
2.539528
721
from spydrnet.ir import Port, Instance, InnerPin from spydrnet_tmr.transformation.util import add_suffix_to_name IN = Port.Direction.IN OUT = Port.Direction.OUT INOUT = Port.Direction.INOUT def apply_nmr(ports_and_instances_to_replicate, degree, name_suffix='NMR', rename_original=True): """ Replicate the selected ports and instances to the n-th degree. :param ports_and_instances_to_replicate: :param degree: number of total copies :param name_suffix: string to append to each replicated element (e.g. 'TMR' or 'DWC') :param rename_original: rename orginal domain :type rename_original: bool :return: A map from an original element to its replicas """ nmr_agent = NMR.from_originals_degree_suffix_and_rename(ports_and_instances_to_replicate, degree, name_suffix, rename_original) replicas = nmr_agent.apply() return replicas
[ 6738, 599, 5173, 81, 3262, 13, 343, 1330, 4347, 11, 2262, 590, 11, 24877, 28348, 198, 6738, 599, 5173, 81, 3262, 62, 17209, 81, 13, 7645, 1161, 13, 22602, 1330, 751, 62, 37333, 844, 62, 1462, 62, 3672, 198, 1268, 796, 4347, 13, 35...
2.558583
367
import os import numpy as np import sys import logging LOG_PATH = os.environ['log'] spark_home = os.environ['SPARK_HOME'] sys.path.insert(0, os.path.join(spark_home, 'python')) sys.path.insert(0, os.path.join(spark_home, 'python/lib/py4j-0.10.4-src.zip')) from pyspark.sql import SparkSession spark = SparkSession.builder.appName("test") \ .getOrCreate() logger = logging.getLogger(__name__) logger.addHandler(logging.FileHandler(LOG_PATH)) if __name__ == '__main__': logging.basicConfig(format='[%(levelname)s] %(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO) main(sys.argv[1:])
[ 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 25064, 198, 11748, 18931, 198, 198, 25294, 62, 34219, 796, 28686, 13, 268, 2268, 17816, 6404, 20520, 198, 2777, 668, 62, 11195, 796, 28686, 13, 268, 2268, 17816, 4303, 14175, ...
2.315018
273
# Copyright 2016-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. from __future__ import absolute_import, division, print_function, unicode_literals import shlex import tests.utils
[ 2, 15069, 1584, 12, 25579, 11, 3203, 11, 3457, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 347, 10305, 12, 7635, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287, 262, 6808, 8619,...
3.942308
104
import openpnm as op import scipy as sp import pytest if __name__ == '__main__': t = SubdomainTest() self = t t.setup_class() for item in t.__dir__(): if item.startswith('test'): print('running test: '+item) t.__getattribute__(item)()
[ 11748, 1280, 79, 21533, 355, 1034, 198, 11748, 629, 541, 88, 355, 599, 198, 11748, 12972, 9288, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 628, 220, 220, 220, 256, 796, 3834, 27830, 14402, 3419, 198, 220,...
2.174242
132
import pandas as pd from shapely.geometry import Point import geopandas as gpd import math import osmnx import requests from io import BytesIO from zipfile import ZipFile def read_poi_csv(input_file, col_id='id', col_name='name', col_lon='lon', col_lat='lat', col_kwds='kwds', col_sep=';', kwds_sep=',', source_crs='EPSG:4326', target_crs='EPSG:4326', keep_other_cols=False): """Creates a POI GeoDataFrame from an input CSV file. Args: input_file (string): Path to the input csv file. col_id (string): Name of the column containing the POI id (default: `id`). col_name (string): Name of the column containing the POI name (default: `name`). col_lon (string): Name of the column containing the POI longitude (default: `lon`). col_lat (string): Name of the column containing the POI latitude (default: `lat`). col_kwds (string): Name of the column containing the POI keywords (default: `kwds`). col_sep (string): Column delimiter (default: `;`). kwds_sep (string): Keywords delimiter (default: `,`). source_crs (string): Coordinate Reference System of input data (default: `EPSG:4326`). target_crs (string): Coordinate Reference System of the GeoDataFrame to be created (default: `EPSG:4326`). keep_other_cols (bool): Whether to keep the rest of the columns in the csv file (default: `False`). Returns: A POI GeoDataFrame with columns `id`, `name` and `kwds`. """ pois = pd.read_csv(input_file, delimiter=col_sep, error_bad_lines=False) init_poi_size = pois.index.size columns = list(pois) subset_cols = [] # Columns to Check for N/A, Nulls if keep_other_cols: subset_cols.extend(columns) else: subset_cols = [col_id, col_lon, col_lat] if col_name in columns: subset_cols.append(col_name) if col_kwds in columns: subset_cols.append(col_kwds) # Geometry Column(Uncleaned) pois['geometry'] = pois.apply(lambda row: lon_lat_to_point(row, col_lon, col_lat), axis=1) subset_cols.append('geometry') # Drop Columns Not in subset Columns. drop_columns = set(columns) - set(subset_cols) pois.drop(drop_columns, inplace=True, axis=1) # Drop all N/A, Null rows from DataFrame. pois.dropna(inplace=True) if init_poi_size - pois.index.size > 0: print("Skipped", (init_poi_size - pois.index.size), "rows due to errors.") if col_kwds in columns: pois[col_kwds] = pois[col_kwds].map(lambda s: s.split(kwds_sep)) source_crs = {'init': source_crs} target_crs = {'init': target_crs} pois = gpd.GeoDataFrame(pois, crs=source_crs, geometry=pois['geometry']).to_crs(target_crs).drop(columns=[col_lon, col_lat]) print('Loaded ' + str(len(pois.index)) + ' POIs.') return pois def import_osmnx(bound, target_crs='EPSG:4326'): """Creates a POI GeoDataFrame from POIs retrieved by OSMNX (https://github.com/gboeing/osmnx). Args: bound (polygon): A polygon to be used as filter. target_crs (string): Coordinate Reference System of the GeoDataFrame to be created (default: `EPSG:4326`). Returns: A POI GeoDataFrame with columns `id`, `name` and `kwds`. """ # retrieve pois pois = osmnx.pois.pois_from_polygon(bound) if len(pois.index) > 0: # filter pois pois = pois[pois.amenity.notnull()] pois_filter = pois.element_type == 'node' pois = pois[pois_filter] # restructure gdf subset_cols = ['osmid', 'amenity', 'name', 'geometry'] columns = list(pois) drop_columns = set(columns) - set(subset_cols) pois.drop(drop_columns, inplace=True, axis=1) pois = pois.reset_index(drop=True) pois = pois.rename(columns={'osmid': 'id', 'amenity': 'kwds'}) pois['kwds'] = pois['kwds'].map(lambda s: [s]) if target_crs != 'EPSG:4326': target_crs = {'init': target_crs} pois = pois.to_crs(target_crs) print('Loaded ' + str(len(pois.index)) + ' POIs.') return pois def import_osmwrangle(osmwrangle_file, target_crs='EPSG:4326', bound=None): """Creates a POI GeoDataFrame from a file produced by OSMWrangle (https://github.com/SLIPO-EU/OSMWrangle). Args: osmwrangle_file (string): Path or URL to the input csv file. target_crs (string): Coordinate Reference System of the GeoDataFrame to be created (default: `EPSG:4326`). bound (polygon): A polygon to be used as filter. Returns: A POI GeoDataFrame with columns `id`, `name` and `kwds`. """ col_sep = '|' col_id = 'ID' col_lon = 'LON' col_lat = 'LAT' col_name = 'NAME' col_cat = 'CATEGORY' col_subcat = 'SUBCATEGORY' source_crs = {'init': 'EPSG:4326'} # Load the file if osmwrangle_file.startswith('http') and osmwrangle_file.endswith('.zip'): response = requests.get(osmwrangle_file) zip_file = ZipFile(BytesIO(response.content)) with zip_file.open(zip_file.namelist()[0]) as csvfile: pois = pd.read_csv(csvfile, delimiter=col_sep, error_bad_lines=False) else: pois = pd.read_csv(osmwrangle_file, delimiter=col_sep, error_bad_lines=False) init_poi_size = pois.index.size columns = list(pois) subset_cols = [col_id, col_name, 'kwds', col_lon, col_lat] # Geometry Column(Uncleaned) pois['geometry'] = pois.apply(lambda row: lon_lat_to_point(row, col_lon, col_lat), axis=1) subset_cols.append('geometry') pois['kwds'] = pois[col_cat] + ',' + pois[col_subcat] pois['kwds'] = pois['kwds'].map(lambda s: s.split(',')) # Drop Columns Not in subset Columns. drop_columns = set(columns) - set(subset_cols) pois.drop(drop_columns, inplace=True, axis=1) # Drop all N/A, Null rows from DataFrame. pois.dropna(inplace=True) if init_poi_size - pois.index.size > 0: print("Skipped", (init_poi_size - pois.index.size), "rows due to errors.") pois = pois.rename(columns={col_id: 'id', col_name: 'name'}) pois = gpd.GeoDataFrame(pois, crs=source_crs, geometry=pois['geometry']).drop(columns=[col_lon, col_lat]) # Check whether location filter should be applied if bound is not None: spatial_filter = pois.geometry.intersects(bound) pois = pois[spatial_filter] if target_crs != 'EPSG:4326': target_crs = {'init': target_crs} pois = pois.to_crs(target_crs) print('Loaded ' + str(len(pois.index)) + ' POIs.') return pois def retrieve_osm_loc(name, buffer_dist=0): """Retrieves a polygon from an OSM location. Args: name (string): Name of the location to be resolved. buffer_dist (numeric): Buffer distance in meters. Returns: A polygon. """ geom = osmnx.core.gdf_from_place(name, buffer_dist=buffer_dist) if len(geom.index) > 0: geom = geom.iloc[0].geometry else: geom = None return geom def to_geojson(gdf, output_file): """Exports a GeoDataFrame to a GeoJSON file. Args: gdf (GeoDataFrame): The GeoDataFrame object to be exported. output_file (string): Path to the output file. """ gdf.to_file(output_file, driver='GeoJSON')
[ 11748, 19798, 292, 355, 279, 67, 198, 6738, 5485, 306, 13, 469, 15748, 1330, 6252, 198, 11748, 30324, 392, 292, 355, 27809, 67, 198, 11748, 10688, 198, 11748, 267, 5796, 77, 87, 198, 11748, 7007, 198, 6738, 33245, 1330, 2750, 4879, 93...
2.252282
3,286
import re import random from collections import defaultdict import src.settings as var from src.utilities import * from src import debuglog, errlog, plog from src.decorators import cmd, event_listener from src.messages import messages from src.events import Event KILLS = {} # type: Dict[str, List[str]] # vim: set sw=4 expandtab:
[ 11748, 302, 198, 11748, 4738, 198, 6738, 17268, 1330, 4277, 11600, 198, 198, 11748, 12351, 13, 33692, 355, 1401, 198, 6738, 12351, 13, 315, 2410, 1330, 1635, 198, 6738, 12351, 1330, 14257, 6404, 11, 11454, 6404, 11, 458, 519, 198, 6738,...
3.34
100
# -*- coding: utf-8 -*- """ Created on Fri Feb 28 13:52:20 2020 @author: midas """ import os import glob import pandas as pd import numpy as np all_filenames=['Data/Train.csv', 'Data/Test.csv'] combined_csv = pd.concat([pd.read_csv(f) for f in all_filenames ]) combined_csv.to_csv( "combined_csv.csv", index=False, encoding='utf-8-sig') from tqdm import tqdm_notebook,tqdm from sklearn import preprocessing train_data=pd.read_csv("Data/Train.csv") test_data=pd.read_csv("Data/Test.csv") train_wo_g=[] train_w_g=[] test_wo_g=[] test_w_g=[] combined_csv for index,row in tqdm(combined_csv.iterrows()): try: index_to_start=int(row['start_pos']) except: continue tuple1= [row['raw'][index_to_start:],row['title'],row['gender']] tuple2= [row['bio'][index_to_start:],row['title'],row['gender']] train_w_g.append(tuple1) train_wo_g.append(tuple2) TrainTestWithGen = pd.DataFrame(train_w_g, columns =['Text', 'title', 'gender']) TrainTestWithoutGen= pd.DataFrame(train_wo_g, columns =['Text', 'title', 'gender']) # Cleaning the texts import re import nltk nltk.download('stopwords') from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer corpus = [] for i in range(0, 74595): review = re.sub('[^a-zA-Z]', ' ', TrainTestWithGen['Text'][i]) review = review.lower() review = review.split() ps = PorterStemmer() review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))] review = ' '.join(review) corpus.append(review) # Creating the Bag of Words model from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(max_features = 30000) X = cv.fit_transform(corpus).toarray() X_all=pd.DataFrame(X) X_all['title']=TrainTestWithGen['title'] X_all['gender']=TrainTestWithGen['gender'] X_Train=X_all[:53754] X_Test=X_all[53754:] X_Train.to_csv('Train_With_Gen.csv') X_Test.to_csv('Test_With_Gen.csv') #Without Gender corpus2 = [] for i in range(0, len(TrainTestWithGen)): review = re.sub('[^a-zA-Z]', ' ', TrainTestWithGen['Text'][i]) review = review.lower() review = review.split() ps = PorterStemmer() review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))] review = ' '.join(review) corpus2.append(review) # Creating the Bag of Words model from sklearn.feature_extraction.text import CountVectorizer cv2 = CountVectorizer(max_features = 30000) X2 = cv2.fit_transform(corpus2).toarray() X_all2=pd.DataFrame(X2) X_all2['title']=TrainTestWithoutGen['title'] X_all2['gender']=TrainTestWithoutGen['gender'] X_Train2=X_all2[:53754] X_Test2=X_all2[53754:] X_Train2.to_csv('Train_WithOut_Gen.csv') X_Test2.to_csv('Test_WithOut_Gen.csv')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 41972, 319, 19480, 3158, 2579, 1511, 25, 4309, 25, 1238, 12131, 201, 198, 201, 198, 31, 9800, 25, 3095, 292, 201, 198, 37811, 201, 198, 201, 198,...
2.284127
1,260
""" Module for the jupyter extension """ import sys import datetime import os import contextlib from pprint import pprint from pathlib import Path from jupytext.contentsmanager import TextFileContentsManager from ploomber.sources.notebooksource import (_cleanup_rendered_nb, inject_cell) from ploomber.spec.dagspec import DAGSpec from ploomber.exceptions import DAGSpecInitializationError from ploomber.cli import parsers from ploomber.jupyter.dag import JupyterDAGManager def resolve_path(parent, path): """ Functions functions resolves paths to make the {source} -> {task} mapping work even then `jupyter notebook` is initialized from a subdirectory of pipeline.yaml """ try: # FIXME: remove :linenumber return Path(parent, path).relative_to(Path('.').resolve()).as_posix().strip() except ValueError: return None def _load_jupyter_server_extension(app): """ This function is called to configure the new content manager, there are a lot of quirks that jupytext maintainers had to solve to make it work so we base our implementation on theirs: https://github.com/mwouts/jupytext/blob/bc1b15935e096c280b6630f45e65c331f04f7d9c/jupytext/__init__.py#L19 """ if isinstance(app.contents_manager_class, PloomberContentsManager): app.log.info("[Ploomber] NotebookApp.contents_manager_class " "is a subclass of PloomberContentsManager already - OK") return # The server extension call is too late! # The contents manager was set at NotebookApp.init_configurables # Let's change the contents manager class app.log.info('[Ploomber] setting content manager ' 'to PloomberContentsManager') app.contents_manager_class = PloomberContentsManager try: # And re-run selected init steps from: # https://github.com/jupyter/notebook/blob/ # 132f27306522b32fa667a6b208034cb7a04025c9/notebook/notebookapp.py#L1634-L1638 app.contents_manager = app.contents_manager_class(parent=app, log=app.log) app.session_manager.contents_manager = app.contents_manager app.web_app.settings["contents_manager"] = app.contents_manager except Exception: error = """[Ploomber] An error occured. Please deactivate the server extension with "jupyter serverextension disable ploomber" and configure the contents manager manually by adding c.NotebookApp.contents_manager_class = "ploomber.jupyter.PloomberContentsManager" to your .jupyter/jupyter_notebook_config.py file. """ # noqa app.log.error(error) raise
[ 37811, 198, 26796, 329, 262, 474, 929, 88, 353, 7552, 198, 37811, 198, 11748, 25064, 198, 11748, 4818, 8079, 198, 11748, 28686, 198, 11748, 4732, 8019, 198, 6738, 279, 4798, 1330, 279, 4798, 198, 6738, 3108, 8019, 1330, 10644, 198, 198,...
2.588065
1,039
#!/usr/bin/env python """ __author__ = Shannon T. Buckley, 10/8/16 Python 2.7.x """ import json import urllib2 import datetime import argparse VERSION = '0.2.1' if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 834, 9800, 834, 796, 28108, 309, 13, 41493, 11, 838, 14, 23, 14, 1433, 198, 37906, 362, 13, 22, 13, 87, 198, 37811, 198, 198, 11748, 33918, 198, 11748, 2956, 297, 571, ...
2.470588
85
""" Tests to plot satellite data """ import os import plotly.graph_objects as go from nowcasting_dataset.data_sources.fake.batch import satellite_fake from nowcasting_dataset.geospatial import osgb_to_lat_lon from nowcasting_utils.visualization.data_sources.plot_satellite import ( make_animation_all_channels, make_animation_one_channels, make_traces_one_channel, make_traces_one_channel_one_time, ) from nowcasting_utils.visualization.utils import make_buttons def test_make_traces_one_channel_one_time(configuration): """Test 'make_traces_one_channel_one_time' functions""" satellite = satellite_fake(configuration=configuration) example_index = 1 trace = make_traces_one_channel_one_time( satellite=satellite, example_index=example_index, channel_index=0, time_index=1 ) fig = go.Figure(trace) x = satellite.x[example_index].mean() y = satellite.y[example_index].mean() lat, lon = osgb_to_lat_lon(x=x, y=y) fig.update_layout( mapbox_style="carto-positron", mapbox_zoom=7, mapbox_center={"lat": lat, "lon": lon} ) if "CI" not in os.environ.keys(): fig.show(renderer="browser") def test_make_traces_one_channel(configuration): """Test 'make_traces_one_channel' functions""" satellite = satellite_fake(configuration=configuration) example_index = 1 traces = make_traces_one_channel( satellite=satellite, example_index=example_index, channel_index=0 ) x = satellite.x[example_index].mean() y = satellite.y[example_index].mean() lat, lon = osgb_to_lat_lon(x=x, y=y) frames = [] for i, trace in enumerate(traces[1:]): frames.append(go.Frame(data=trace, name=f"frame{i+1}")) fig = go.Figure( data=traces[0], layout=go.Layout( title="Start Title", ), frames=frames, ) fig.update_layout(updatemenus=[make_buttons()]) fig.update_layout( mapbox_style="carto-positron", mapbox_zoom=7, mapbox_center={"lat": lat, "lon": lon} ) if "CI" not in os.environ.keys(): fig.show(renderer="browser") def test_make_animation_one_channels(configuration): """Test 'make_animation_one_channels' functions""" satellite = satellite_fake(configuration=configuration) fig = make_animation_one_channels(satellite=satellite, example_index=1, channel_index=0) if "CI" not in os.environ.keys(): fig.show(renderer="browser") def test_make_animation_all_channesl(configuration): """Test 'make_animation_all_channels' functions""" satellite = satellite_fake(configuration=configuration) fig = make_animation_all_channels(satellite=satellite, example_index=0) if "CI" not in os.environ.keys(): fig.show(renderer="browser")
[ 37811, 30307, 284, 7110, 11210, 1366, 37227, 198, 11748, 28686, 198, 198, 11748, 7110, 306, 13, 34960, 62, 48205, 355, 467, 198, 6738, 783, 19913, 62, 19608, 292, 316, 13, 7890, 62, 82, 2203, 13, 30706, 13, 43501, 1330, 11210, 62, 307...
2.531278
1,103
""" owtf.__main__ ~~~~~~~~~~~~~ A __main__ method for OWTF so that internal services can be called as Python modules. """ import sys from owtf.core import main if __name__ == "__main__": main()
[ 37811, 198, 322, 27110, 13, 834, 12417, 834, 198, 15116, 8728, 93, 198, 32, 11593, 12417, 834, 2446, 329, 47210, 10234, 523, 326, 5387, 2594, 460, 307, 1444, 355, 11361, 13103, 13, 198, 37811, 198, 11748, 25064, 198, 198, 6738, 12334, ...
3.076923
65
from enum import IntEnum from typing import Type, TypeVar import logging T = TypeVar("T")
[ 6738, 33829, 1330, 2558, 4834, 388, 198, 6738, 19720, 1330, 5994, 11, 5994, 19852, 198, 11748, 18931, 628, 198, 51, 796, 5994, 19852, 7203, 51, 4943, 628, 198 ]
3.357143
28
# -*- coding: utf-8 -*- # json import json # get, apialert_found .
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 2, 33918, 220, 220, 220, 220, 201, 198, 11748, 33918, 201, 198, 201, 198, 2, 651, 11, 220, 220, 220, 2471, 498, 861, 62, 9275, 220, 220, 220, 220, 220, 764, 2...
1.770833
48
import shutil from pathlib import Path from tempfile import mkdtemp import pytest from click.testing import CliRunner import ape # NOTE: Ensure that we don't use local paths for these ape.config.DATA_FOLDER = Path(mkdtemp()).resolve() ape.config.PROJECT_FOLDER = Path(mkdtemp()).resolve()
[ 11748, 4423, 346, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 20218, 7753, 1330, 33480, 67, 29510, 198, 198, 11748, 12972, 9288, 198, 6738, 3904, 13, 33407, 1330, 1012, 72, 49493, 198, 198, 11748, 43835, 198, 198, 2, 24550, 25, 48987...
3.04
100
# # prime number generator # This program gets two number as input # and prints # Prime numbers in the range # Actual number of primes in the range # and Estimation based on formula # n # pi(n)= ------- # log(n) # pi(n)=number of primes less than n # from math import * if __name__=='__main__': s = input('Enter Start: ') e = input('Enter End: ') s|=1 #if s%2==0:s+=1 # ODDS only list = [x for x in range(s,e,2) if isPrime(x)] print list,'\n',len(list),'\n',int(ceil(e/log(e)-s/log(s))) #prints list of primes , length of list , estimate using the formula
[ 2, 198, 2, 6994, 1271, 17301, 198, 2, 770, 1430, 3011, 734, 1271, 355, 5128, 198, 2, 290, 20842, 198, 2, 220, 220, 220, 220, 220, 220, 5537, 3146, 287, 262, 2837, 198, 2, 220, 220, 220, 220, 220, 220, 33520, 1271, 286, 778, 999,...
2.077844
334
A=int(input("dame int")) B=int(input("dame int")) if(A>B): print("A es mayor") else: print("B es mayor")
[ 32, 28, 600, 7, 15414, 7203, 67, 480, 493, 48774, 198, 33, 28, 600, 7, 15414, 7203, 67, 480, 493, 48774, 198, 361, 7, 32, 29, 33, 2599, 198, 220, 220, 220, 3601, 7203, 32, 1658, 9591, 4943, 198, 17772, 25, 198, 220, 220, 220, ...
2.070175
57
#pylint: disable=logging-fstring-interpolation #Standart library imports import shutil import os import time from typing import Tuple from pathlib import Path import re from shutil import copyfile import wget # Local imports from selenium_driver_updater.util.logger import logger from selenium_driver_updater.util.exceptions import DriverVersionInvalidException from selenium_driver_updater.driver_base import DriverBase
[ 2, 79, 2645, 600, 25, 15560, 28, 6404, 2667, 12, 69, 8841, 12, 3849, 16104, 341, 198, 2, 15480, 433, 5888, 17944, 198, 11748, 4423, 346, 198, 11748, 28686, 198, 11748, 640, 198, 6738, 19720, 1330, 309, 29291, 198, 6738, 3108, 8019, ...
3.467213
122
# Copyright 2021, Yahoo # Licensed under the terms of the Apache 2.0 license. See the LICENSE file in the project root for terms from pathlib import Path from typing import Optional, Union from pydantic import BaseModel
[ 2, 220, 15069, 33448, 11, 16551, 198, 2, 220, 49962, 739, 262, 2846, 286, 262, 24843, 362, 13, 15, 5964, 13, 4091, 262, 38559, 24290, 2393, 287, 262, 1628, 6808, 329, 2846, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, ...
3.982456
57
import logging from dvc.main import main from tests.basic_env import TestDvc from tests.func.test_repro import TestRepro from tests.func.test_repro import TestReproChangedDeepData
[ 11748, 18931, 198, 198, 6738, 288, 28435, 13, 12417, 1330, 1388, 198, 6738, 5254, 13, 35487, 62, 24330, 1330, 6208, 35, 28435, 198, 6738, 5254, 13, 20786, 13, 9288, 62, 260, 1676, 1330, 6208, 6207, 305, 198, 6738, 5254, 13, 20786, 13,...
3.254237
59
import procgame.game from procgame.game import AdvancedMode import logging
[ 11748, 13834, 6057, 13, 6057, 198, 6738, 13834, 6057, 13, 6057, 1330, 13435, 19076, 198, 11748, 18931, 628, 198 ]
4.052632
19
from django.contrib import admin from .models import Distribution admin.site.register(Distribution) # Register your models here.
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 764, 27530, 1330, 27484, 198, 198, 28482, 13, 15654, 13, 30238, 7, 20344, 3890, 8, 198, 2, 17296, 534, 4981, 994, 13, 198 ]
3.939394
33
# -*- coding: utf-8 -*- import logging; logging.basicConfig(level=logging.INFO) import numpy as np import matplotlib.pyplot as plt import logictensornetworks_wrapper as ltnw nr_samples=500 data=np.random.uniform([0,0],[1.,1.],(nr_samples,2)).astype(np.float32) data_A=data[np.where(np.sum(np.square(data-[.5,.5]),axis=1)<.09)] data_not_A=data[np.where(np.sum(np.square(data-[.5,.5]),axis=1)>=.09)] ltnw.variable("?data_A",data_A) ltnw.variable("?data_not_A",data_not_A) ltnw.variable("?data",data) ltnw.predicate("A",2) ltnw.axiom("forall ?data_A: A(?data_A)") ltnw.axiom("forall ?data_not_A: ~A(?data_not_A)") ltnw.initialize_knowledgebase(initial_sat_level_threshold=.1) sat_level=ltnw.train(track_sat_levels=1000,sat_level_epsilon=.99) plt.figure(figsize=(12,8)) result=ltnw.ask("A(?data)") plt.subplot(2,2,1) plt.scatter(data[:,0],data[:,1],c=result.squeeze()) plt.colorbar() plt.title("A(x) - training data") result=ltnw.ask("~A(?data)") plt.subplot(2,2,2) plt.scatter(data[:,0],data[:,1],c=result.squeeze()) plt.colorbar() plt.title("~A(x) - training data") data_test=np.random.uniform([0,0],[1.,1.],(500,2)).astype(np.float32) ltnw.variable("?data_test",data_test) result=ltnw.ask("A(?data_test)") plt.subplot(2,2,3) plt.title("A(x) - test") plt.scatter(data_test[:,0],data_test[:,1],c=result.squeeze()) plt.colorbar() plt.title("A(x) - test data") result=ltnw.ask("~A(?data_test)") plt.subplot(2,2,4) plt.scatter(data_test[:,0],data_test[:,1],c=result.squeeze()) plt.title("~A(x) - test data") plt.show() ltnw.constant("a",[0.25,.5]) ltnw.constant("b",[1.,1.]) print("a is in A: %s" % ltnw.ask("A(a)")) print("b is in A: %s" % ltnw.ask("A(b)"))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 18931, 26, 18931, 13, 35487, 16934, 7, 5715, 28, 6404, 2667, 13, 10778, 8, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487...
2.070632
807
# !/usr/bin/env python3 # Author: C.K # Email: theck17@163.com # DateTime:2021-03-15 00:07:14 # Description: if __name__ == "__main__": pass
[ 2, 5145, 14, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 6434, 25, 327, 13, 42, 198, 2, 9570, 25, 262, 694, 1558, 31, 24136, 13, 785, 198, 2, 7536, 7575, 25, 1238, 2481, 12, 3070, 12, 1314, 3571, 25, 2998, 25, 1415, 198, 2,...
2.208955
67
from django.contrib.auth import authenticate, login from django.shortcuts import render, redirect from cart.models import Cart from django.views import View from .forms import LoginForm, RegistrationForm, CreateCompanyForm from customer.models import Customer, ShippingAddress from src.utils.mixins import CustomerMixin from checkout.models import ApplyOrganization
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 8323, 5344, 11, 17594, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 18941, 198, 6738, 6383, 13, 27530, 1330, 13690, 198, 6738, 42625, 14208, 13, 33571, 1330, 3582, 198, 6...
4.305882
85
from flask import Flask, render_template, request # from .recommendation import * # import pickle import pandas as pd import numpy as np # import keras # from keras.models import load_model import pickle return APP
[ 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 11, 2581, 198, 2, 422, 764, 47335, 437, 341, 1330, 1635, 198, 2, 1330, 2298, 293, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 2, 1330, 41927, 292, 198...
3.460317
63
from typing import List, Type from apiron.service.base import ServiceBase
[ 6738, 19720, 1330, 7343, 11, 5994, 198, 198, 6738, 2471, 1934, 13, 15271, 13, 8692, 1330, 4809, 14881, 628 ]
4
19
import math import os import re import shutil from plotman import job GB = 1_000_000_000 def df_b(d): 'Return free space for directory (in bytes)' usage = shutil.disk_usage(d) return usage.free def enough_space_for_k32(b): 'Determine if there is enough space for a k32 given a number of free bytes' return b > 1.2 * get_k32_plotsize() def list_k32_plots(d): 'List completed k32 plots in a directory (not recursive)' plots = [] for plot in os.listdir(d): if re.match(r'^plot-k32-.*plot$', plot): plot = os.path.join(d, plot) try: if os.stat(plot).st_size > (0.95 * get_k32_plotsize()): plots.append(plot) except FileNotFoundError: continue return plots def column_wrap(items, n_cols, filler=None): '''Take items, distribute among n_cols columns, and return a set of rows containing the slices of those columns.''' rows = [] n_rows = math.ceil(len(items) / n_cols) for row in range(n_rows): row_items = items[row : : n_rows] # Pad and truncate rows.append( (row_items + ([filler] * n_cols))[:n_cols] ) return rows
[ 11748, 10688, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 4423, 346, 198, 198, 6738, 7110, 805, 1330, 1693, 198, 198, 4579, 796, 352, 62, 830, 62, 830, 62, 830, 198, 198, 4299, 47764, 62, 65, 7, 67, 2599, 198, 220, 220, 220, 7...
2.250936
534
# (c) Copyright 2016 forkedbranch (http://forkedbranch.eu/) # Licensed under the Apache License, Version 2.0 import configparser config = configparser.ConfigParser() config.read('config.ini')
[ 2, 357, 66, 8, 15069, 1584, 329, 9091, 1671, 3702, 357, 4023, 1378, 32523, 276, 1671, 3702, 13, 12496, 34729, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 198, 198, 11748, 4566, 48610, 198, 198, 11250, 796, 4566, 4...
3.446429
56
# Copyright 2018, Michael DeHaan LLC # License: Apache License Version 2.0 # ------------------------------------------------------------------------- # registration.py - updates the database to say who is building something # and what the current settings are, which is used by the file serving # code to see if it is ok to serve up files in the buildroot. But also # for record keeping. # -------------------------------------------------------------------------- from datetime import datetime import random import fcntl import subprocess import os from django.utils import timezone from django.conf import settings from vespene.common.logger import Logger from vespene.models.worker import Worker LOG = Logger() WORKER_ID_FILE = "/etc/vespene/worker_id" # =============================================================================
[ 2, 220, 15069, 2864, 11, 3899, 1024, 23303, 272, 11419, 198, 2, 220, 13789, 25, 24843, 13789, 10628, 362, 13, 15, 198, 2, 220, 16529, 45537, 198, 2, 220, 9352, 13, 9078, 532, 5992, 262, 6831, 284, 910, 508, 318, 2615, 1223, 198, 2...
4.419689
193
# coding: utf-8 ''' Deformation codes are borrowed from MUDA McFee et al., A software framework for musical data augmentation, 2015 https://github.com/bmcfee/muda ''' import os import time import subprocess import tempfile import numpy as np import pandas as pd import datetime import tqdm import csv import fire import argparse import pickle from sklearn import metrics import pandas as pd import librosa import soundfile as psf import torch import torch.nn as nn from torch.autograd import Variable from solver import skip_files from sklearn.preprocessing import LabelBinarizer import model as Model TAGS = ['genre---downtempo', 'genre---ambient', 'genre---rock', 'instrument---synthesizer', 'genre---atmospheric', 'genre---indie', 'instrument---electricpiano', 'genre---newage', 'instrument---strings', 'instrument---drums', 'instrument---drummachine', 'genre---techno', 'instrument---guitar', 'genre---alternative', 'genre---easylistening', 'genre---instrumentalpop', 'genre---chillout', 'genre---metal', 'mood/theme---happy', 'genre---lounge', 'genre---reggae', 'genre---popfolk', 'genre---orchestral', 'instrument---acousticguitar', 'genre---poprock', 'instrument---piano', 'genre---trance', 'genre---dance', 'instrument---electricguitar', 'genre---soundtrack', 'genre---house', 'genre---hiphop', 'genre---classical', 'mood/theme---energetic', 'genre---electronic', 'genre---world', 'genre---experimental', 'instrument---violin', 'genre---folk', 'mood/theme---emotional', 'instrument---voice', 'instrument---keyboard', 'genre---pop', 'instrument---bass', 'instrument---computer', 'mood/theme---film', 'genre---triphop', 'genre---jazz', 'genre---funk', 'mood/theme---relaxing'] if __name__ == '__main__': parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--num_workers', type=int, default=0) parser.add_argument('--dataset', type=str, default='mtat', choices=['mtat', 'msd', 'jamendo','jamendo-mood']) parser.add_argument('--model_type', type=str, default='fcn', choices=['fcn', 'musicnn', 'crnn', 'sample', 'se', 'short', 'short_res', 'attention', 'hcnn']) parser.add_argument('--batch_size', type=int, default=16) parser.add_argument('--model_load_path', type=str, default='.') parser.add_argument('--data_path', type=str, default='./data') parser.add_argument('--mod', type=str, default='time_stretch') parser.add_argument('--rate', type=float, default=0) config = parser.parse_args() p = Predict(config) p.test()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 7061, 6, 198, 5005, 1161, 12416, 389, 22546, 422, 25108, 5631, 198, 9742, 37, 1453, 2123, 435, 1539, 317, 3788, 9355, 329, 10530, 1366, 16339, 14374, 11, 1853, 198, 5450, 1378, 12567, 13, 785, 14...
2.964245
867
from model.group import Group from model.contact import Contact
[ 6738, 2746, 13, 8094, 1330, 4912, 198, 6738, 2746, 13, 32057, 1330, 14039, 198 ]
4.571429
14
""" Day 5: Normal Distribution I In certain plant, the time taken to assemble a car is a random variable, X having a normal distribution with a mean of 20 hours and a standard deviation of 2 hours. What is the probability that a car can be assembled at this plant in: 1. Less han 19.5 hours? 2. Between 20 and 22 hours? Author: Eda AYDIN """ import math # less than 19.5 hours # Between 20 and 22 hours values = list(map(float, input().split())) mean = values[0] std = values[1] less = float(input()) boundaries = list(map(float, input().split())) lower_range = boundaries[0] upper_range = boundaries[1] cumulative1(mean, std, less) cumulative2(mean, std, lower_range, upper_range)
[ 37811, 201, 198, 12393, 642, 25, 14435, 27484, 314, 201, 198, 201, 198, 818, 1728, 4618, 11, 262, 640, 2077, 284, 25432, 257, 1097, 318, 257, 4738, 7885, 11, 1395, 1719, 257, 3487, 6082, 201, 198, 4480, 257, 1612, 286, 1160, 2250, 2...
2.896414
251
for _ in range(int(input())): print(sum(map(int, input().split())))
[ 1640, 4808, 287, 2837, 7, 600, 7, 15414, 28955, 2599, 198, 197, 4798, 7, 16345, 7, 8899, 7, 600, 11, 5128, 22446, 35312, 3419, 22305 ]
2.72
25
import pytest from apostello import models
[ 11748, 12972, 9288, 198, 198, 6738, 18584, 11109, 1330, 4981, 628 ]
4.090909
11