content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
# Generated by Django 2.1.7 on 2019-03-31 10:31 from django.conf import settings from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 22, 319, 13130, 12, 3070, 12, 3132, 838, 25, 3132, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 142...
3.019231
52
#!/usr/bin/env python3 # encoding: utf-8 # Douglas Crockford's idea for making generators # basically "why do you need a `yield` keyword when you can just maintain some state" # in my view, a class would be a better way to do this, and indeed, in python, # that's how Iterators are defined. gen = iter([1,2,3]) for _ in range(4): print(gen())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 198, 2, 15796, 9325, 694, 3841, 338, 2126, 329, 1642, 27298, 198, 2, 6209, 366, 22850, 466, 345, 761, 257, 4600, 88, 1164, 63, 21179, 618, ...
3.117117
111
from time import time from ss.utils import INF import sys import os import shutil TEMP_DIR = 'temp/' DOMAIN_INPUT = 'domain.pddl' PROBLEM_INPUT = 'problem.pddl' TRANSLATE_OUTPUT = 'output.sas' SEARCH_OUTPUT = 'sas_plan' ENV_VAR = 'FD_PATH' FD_BIN = 'bin' TRANSLATE_DIR = 'translate/' SEARCH_COMMAND = 'downward --internal-plan-file %s %s < %s' SEARCH_OPTIONS = { 'dijkstra': '--heuristic "h=blind(transform=adapt_costs(cost_type=NORMAL))" ' '--search "astar(h,cost_type=NORMAL,max_time=%s,bound=%s)"', 'max-astar': '--heuristic "h=hmax(transform=adapt_costs(cost_type=NORMAL))"' ' --search "astar(h,cost_type=NORMAL,max_time=%s,bound=%s)"', 'ff-astar': '--heuristic "h=ff(transform=adapt_costs(cost_type=NORMAL))" ' '--search "astar(h,cost_type=NORMAL,max_time=%s,bound=%s)"', 'ff-wastar1': '--heuristic "h=ff(transform=adapt_costs(cost_type=NORMAL))" ' '--search "lazy_wastar([h],preferred=[h],reopen_closed=true,boost=100,w=1,' 'preferred_successors_first=true,cost_type=NORMAL,max_time=%s,bound=%s)"', 'ff-wastar3': '--heuristic "h=ff(transform=adapt_costs(cost_type=PLUSONE))" ' '--search "lazy_wastar([h],preferred=[h],reopen_closed=false,boost=100,w=3,' 'preferred_successors_first=true,cost_type=PLUSONE,max_time=%s,bound=%s)"', 'ff-wastar5': '--heuristic "h=ff(transform=adapt_costs(cost_type=PLUSONE))" ' '--search "lazy_wastar([h],preferred=[h],reopen_closed=false,boost=100,w=5,' 'preferred_successors_first=true,cost_type=PLUSONE,max_time=%s,bound=%s)"', 'cea-wastar1': '--heuristic "h=cea(transform=adapt_costs(cost_type=PLUSONE))" ' '--search "lazy_wastar([h],preferred=[h],reopen_closed=false,boost=1000,w=1,' 'preferred_successors_first=true,cost_type=PLUSONE,max_time=%s,bound=%s)"', 'cea-wastar3': '--heuristic "h=cea(transform=adapt_costs(cost_type=PLUSONE))" ' '--search "lazy_wastar([h],preferred=[h],reopen_closed=false,boost=1000,w=3,' 'preferred_successors_first=true,cost_type=PLUSONE,max_time=%s,bound=%s)"', 'cea-wastar5': '--heuristic "h=cea(transform=adapt_costs(cost_type=PLUSONE))" ' '--search "lazy_wastar([h],preferred=[h],reopen_closed=false,boost=1000,w=5,' 'preferred_successors_first=true,cost_type=PLUSONE,max_time=%s,bound=%s)"', 'ff-eager': '--heuristic "hff=ff(transform=adapt_costs(cost_type=PLUSONE))" ' '--search "eager_greedy([hff],max_time=%s,bound=%s)"', 'ff-eager-pref': '--heuristic "hff=ff(transform=adapt_costs(cost_type=PLUSONE))" ' '--search "eager_greedy([hff],preferred=[hff],max_time=%s,bound=%s)"', 'ff-lazy': '--heuristic "hff=ff(transform=adapt_costs(cost_type=PLUSONE))" ' '--search "lazy_greedy([hff],preferred=[hff],max_time=%s,bound=%s)"', }
[ 6738, 640, 1330, 640, 198, 6738, 37786, 13, 26791, 1330, 45594, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 198, 51, 39494, 62, 34720, 796, 705, 29510, 14, 6, 198, 39170, 29833, 62, 1268, 30076, 796, 705, 27830, ...
2.053229
1,409
import requests from api import config
[ 11748, 7007, 198, 6738, 40391, 1330, 4566, 628 ]
5
8
''' Library for gcode commands objects that render to strings. ''' from .number import num2str from .point import XYZ
[ 7061, 6, 198, 23377, 329, 308, 8189, 9729, 5563, 326, 8543, 284, 13042, 13, 198, 7061, 6, 198, 6738, 764, 17618, 1330, 997, 17, 2536, 198, 6738, 764, 4122, 1330, 41420, 57, 628, 628, 628, 628, 628, 628, 628, 628, 628, 198 ]
3.238095
42
''' Description: Problem 3 (rearrange the code) Version: 1.0.1.20210116 Author: Arvin Zhao Date: 2021-01-14 22:51:16 Last Editors: Arvin Zhao LastEditTime: 2021-01-16 04:11:18 ''' if __name__ == '__main__': # It is strongly recommended to add this line. main()
[ 7061, 6, 198, 11828, 25, 20647, 513, 357, 260, 3258, 858, 262, 2438, 8, 198, 14815, 25, 352, 13, 15, 13, 16, 13, 1238, 2481, 486, 1433, 198, 13838, 25, 943, 7114, 29436, 198, 10430, 25, 33448, 12, 486, 12, 1415, 2534, 25, 4349, ...
2.663366
101
from tensorflow import keras # Make sure the tf_trees directory is in the search path. from tf_trees import TEL # The documentation of TEL can be accessed as follows print(TEL.__doc__) # We will fit TEL on the Boston Housing regression dataset. # First, load the dataset. from keras.datasets import boston_housing (x_train, y_train), (x_test, y_test) = boston_housing.load_data() # Define the tree layer; here we choose 10 trees, each of depth 3. # Note output_logits_dim is the dimension of the tree output. # output_logits_dim = 1 in this case, but should be equal to the # number of classes if used as an output layer in a classification task. tree_layer = TEL(output_logits_dim=1, trees_num=10, depth=3) # Construct a sequential model with batch normalization and TEL. model = keras.Sequential() model.add(keras.layers.BatchNormalization()) model.add(tree_layer) # Fit a model with mse loss. model.compile(loss='mse', optimizer='adam', metrics=['mse']) result = model.fit(x_train, y_train, epochs=100, validation_data=(x_test, y_test))
[ 6738, 11192, 273, 11125, 1330, 41927, 292, 198, 2, 6889, 1654, 262, 48700, 62, 83, 6037, 8619, 318, 287, 262, 2989, 3108, 13, 198, 6738, 48700, 62, 83, 6037, 1330, 309, 3698, 198, 198, 2, 383, 10314, 286, 309, 3698, 460, 307, 17535,...
3.094675
338
#!/usr/bin/env python # Core Library modules import argparse import os # Third party modules import pytest # First party modules import nntoolkit.utils as utils
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 7231, 10074, 13103, 198, 11748, 1822, 29572, 198, 11748, 28686, 198, 198, 2, 10467, 2151, 13103, 198, 11748, 12972, 9288, 198, 198, 2, 3274, 2151, 13103, 198, 11748, 299, 429, ...
3.32
50
sum = 0 for x in range(1,1000): if x%3 == 0 or x%5 == 0: sum += x print ("Total is:", sum)
[ 16345, 796, 657, 201, 198, 201, 198, 1640, 2124, 287, 2837, 7, 16, 11, 12825, 2599, 201, 198, 197, 361, 2124, 4, 18, 6624, 657, 393, 2124, 4, 20, 6624, 657, 25, 201, 198, 197, 197, 16345, 15853, 2124, 201, 198, 201, 198, 4798, 5...
1.980392
51
import smtplib import os from email.mime.text import MIMEText from email.utils import formataddr from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.header import Header try: from src.config import CONFIG except ImportError: Zemail = SendEmail(CONFIG.EMAIL.get("user"), CONFIG.EMAIL.get("passwd")) if __name__ == '__main__': main()
[ 11748, 895, 83, 489, 571, 198, 11748, 28686, 198, 6738, 3053, 13, 76, 524, 13, 5239, 1330, 337, 3955, 2767, 2302, 198, 6738, 3053, 13, 26791, 1330, 5794, 29851, 198, 6738, 3053, 13, 76, 524, 13, 9060, 1330, 337, 12789, 5159, 198, 67...
2.972028
143
from typing import List, Optional from can_decoder.Signal import Signal
[ 6738, 19720, 1330, 7343, 11, 32233, 198, 198, 6738, 460, 62, 12501, 12342, 13, 11712, 282, 1330, 26484, 628 ]
3.894737
19
largura = float(input('Digite a largura da parede: ')) altura = float(input('Digite a altura da parede: ')) area = largura * altura tinta = area / 2 print('A rea da parede de {}'.format(area)) print('Ser necessrio para pintar {} litros de tinta'.format(tinta))
[ 15521, 5330, 796, 12178, 7, 15414, 10786, 19511, 578, 257, 2552, 5330, 12379, 279, 1144, 68, 25, 705, 4008, 198, 2501, 5330, 796, 12178, 7, 15414, 10786, 19511, 578, 257, 5988, 5330, 12379, 279, 1144, 68, 25, 705, 4008, 198, 198, 2033...
2.693878
98
#Kyle Slater import re
[ 2, 42516, 44289, 198, 11748, 302 ]
3.666667
6
import os import tempfile import requests api_url = "http://127.0.0.1:8989" def test_no_token(): """Request home without token""" response = requests.get(api_url+"/isvalid") print(response.status_code) assert response.status_code == 401
[ 11748, 28686, 198, 11748, 20218, 7753, 198, 11748, 7007, 198, 198, 15042, 62, 6371, 796, 366, 4023, 1378, 16799, 13, 15, 13, 15, 13, 16, 25, 23, 42520, 1, 198, 198, 4299, 1332, 62, 3919, 62, 30001, 33529, 198, 220, 220, 220, 37227, ...
2.752688
93
#!/usr/bin/python3 # MIT License # # Copyright (c) 2021 gh0$t # # 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. ############################################################################################################################ # imports ############################################################################################################################ import sys import urllib.request from bs4 import BeautifulSoup from urllib.request import Request from selenium import webdriver import os import time from stem import Signal from stem.control import Controller ############################################################################################################################ # Pass URL, extract text, translate ############################################################################################################################ URL = str(sys.argv[1]) GTURL = 'https://translate.google.com/' # this is important, drives the whole translation process. # if google updates the translate.google.com page selectors, this HORRIBLE selector needs to be updated GTXpathSel = '//*[@id="yDmH0d"]/c-wiz/div/div[@class="WFnNle"]/c-wiz/div[@class="OlSOob"]/c-wiz/div[@class="hRFt4b"]/c-wiz/div[@class="ykTHSe"]/div/div[@class="dykxn MeCBDd j33Gae"]/div/div[2]/div/div[@class="Llmcnf"]' print('\nConnecting to ' + URL + ' ...' + '\nExtracting text...') req = Request(URL) html = BeautifulSoup(urllib.request.urlopen(req).read(), 'html.parser') text = html.find('div', {'id': 'bodyContent'}).get_text() with open('out/English.txt', 'w', encoding='utf-8') as f: f.write(text) print('\nExtracted -> out/English.txt') print('\nStarting translation job...') options = webdriver.ChromeOptions() options.add_argument('--incognito') options.add_argument('--headless') driver = webdriver.Chrome(executable_path='driver/chromedriver', options=options) print('\nConnecting to ' + GTURL + ' ...') driver.get(GTURL) time.sleep(1) try: # accept Google's cookies driver.find_elements_by_xpath ('//span[contains(text(), "I agree")]')[0].click() except: pass time.sleep(2) driver.find_element_by_xpath('//*[@aria-label="Document translation"]').click() driver.find_element_by_name('file').send_keys(os.path.abspath('out/English.txt')) langEle = driver.find_elements_by_xpath(GTXpathSel) i = 0 totLang = len(langEle) print('\nTotal languages = ' + str(totLang) + ' [press CTRL + C once or twice or thrice or any number of times you like to press to quit anytime]') print('\nTranslating text...') while i < totLang: init(driver) i += 1 print('\nTranslations completed. Check "/out" for the files.') driver.quit() exit()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 2, 17168, 13789, 198, 2, 220, 198, 2, 15069, 357, 66, 8, 33448, 24997, 15, 3, 83, 198, 2, 220, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, ...
3.39593
1,081
# Generated by Django 3.1.2 on 2021-09-23 21:54 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 17, 319, 33448, 12, 2931, 12, 1954, 2310, 25, 4051, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.766667
30
import tensorflow as tf import keras import numpy as np
[ 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 41927, 292, 198, 11748, 299, 32152, 355, 45941, 628 ]
3.352941
17
import os MONGO_HOST = os.getenv('OPENSHIFT_NOSQL_DB_HOST') MONGO_PORT = os.getenv('OPENSHIFT_NOSQL_DB_PORT') MONGO_USERNAME = os.getenv('OPENSHIFT_NOSQL_DB_USERNAME') MONGO_PASSWORD = os.getenv('OPENSHIFT_NOSQL_DB_PASSWORD') MONGO_DBNAME = 'speakeasy' PRIV_KEY_FILE = os.getenv('OPENSHIFT_DATA_DIR') + '/server_private.pem' PUB_KEY_FILE = os.getenv('OPENSHIFT_DATA_DIR') + '/server_public.pem' PRIV_KEY = open(PRIV_KEY_FILE).read() PUB_KEY = open(PUB_KEY_FILE).read() DEBUG = True
[ 11748, 28686, 198, 198, 27857, 11230, 62, 39, 10892, 796, 28686, 13, 1136, 24330, 10786, 3185, 1677, 9693, 32297, 62, 45, 2640, 9711, 62, 11012, 62, 39, 10892, 11537, 198, 27857, 11230, 62, 15490, 796, 28686, 13, 1136, 24330, 10786, 318...
2.179372
223
r''' perl_io - Opens a file or pipe in the Perl style Copyright (c) 2016 Yoichi Hariguchi 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. Usage: from perl_io import PerlIO Example 1: pio = PerlIO('/proc/meminfo') # open `/proc/meminfo' for input Example 2: pio = PerlIO('> /tmp/foo.txt') # open '/tmp/foo.txt' for output Example 3: pio = PerlIO('>> /tmp/foo.txt') # open '/tmp/foo.txt' for appending Example 4: pio = PerlIO('| cmd arg1 ...') # we pipe output to the command `cmd' Example 5: pio = PerlIO('cmd arg1 ... |') # execute `cmd' that pipes output to us You can access the Python file object as `pio.fo' after PerlIO object `pio' was successfully created. `pio.fo' is set to `None' if PelIO failed to open a file or pipe. Example6 : Read the output of `strings /usr/bin/python' from a pipe with PerlIO('strings /usr/bin/python |') as pio: for line in pio.fo.xreadlines(): # # do something... # Example7 : Write to a file with PerlIO('>/tmp/.tmpfile-%d' % (os.getpid())) as pio: print >> pio.fo, 'This is an example' pio.fo.write('This is another example') pio.fo.write('\n') Note: PerlIO parses the parameter as follows in the case it indicates to input from or output to a pipe. 1. Strips the first or last `|' (which indicates to open a pipe) 2. If the remaining string includes shell special characters like `|', `>', `;', etc., PerlIO calls Popen() with "sh -c 'remaining_string'", which means it can be a security hazard when the remaining string includes the unsanitized input from an untrusted source. 3. If the remaining string includes no shell special characters, PerlIO does not invoke shell when it calls Popen(). How to test: python -m unittest -v perl_io ''' import os import platform import re import sys import syslog import time import subprocess import shlex import unittest class TestPerlIO(unittest.TestCase): # # 1. Open a file to write using PerlIO # 2. Open a pipe outputting to us with a complex command line # PerlIO('strings `which ls` | sort | uniq | ') # so that shell is invoked with Popen(). # 3. Write all the input to the file created in No. 1 # 4. Check the contents # # # 1. Open a pipe to write with a complex command line # PerlIO('| cat > /tmp/.pio_pipe_rt_test-XXXX') # so that shell is invoked with Popen(). # The output to the pipe is redirected to a file # 2. Open the file to read using PerlIO # 3. Check the contents # # # Read from a pipe with a simple command line # so that shell is not invoked with Popen(). # Confirm the contents of the file is correct. # Must be called after file_test(). #
[ 81, 7061, 6, 48746, 62, 952, 532, 8670, 641, 257, 2393, 393, 12656, 287, 262, 24316, 3918, 198, 198, 15269, 357, 66, 8, 1584, 25455, 16590, 2113, 328, 22200, 198, 198, 5990, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597,...
2.969064
1,293
from .. import bp from flask import request, render_template, flash, redirect, url_for from flask_login import current_user, login_required from app.lib.base.provider import Provider from app.lib.base.decorators import admin_required
[ 6738, 11485, 1330, 275, 79, 198, 6738, 42903, 1330, 2581, 11, 8543, 62, 28243, 11, 7644, 11, 18941, 11, 19016, 62, 1640, 198, 6738, 42903, 62, 38235, 1330, 1459, 62, 7220, 11, 17594, 62, 35827, 198, 6738, 598, 13, 8019, 13, 8692, 13...
3.730159
63
#!/usr/bin/env python # Copyright 2014 Open Connectome Project (http://openconnecto.me) # # 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. # # create_atlas.py # Created by Disa Mhembere on 2014-04-10. # Email: disa@jhu.edu # Copyright (c) 2014. All rights reserved. # This simply takes a (182, 218, 182) atlas and creates # a ~30-non-zero k region atlas by relabelling each # 3x3x3 region with a new label then masking # using a base atlas import argparse import nibabel as nib import numpy as np from math import ceil from copy import copy import sys, pdb from time import time import os from packages.utils.setup import get_files def create(roifn=os.path.join(os.environ["M2G_HOME"],"data","Atlas", "MNI152_T1_1mm_brain.nii"), start=2): """ Downsamples an atlas from a template brain. Create a new atlas given some scaling factor determined by the start index. Can be useful if looking for parcellation of certain scale for graph generation. **Positional Arguments** roifn: [.nii; nifti image] (default = MNI152) - Nifti roi mask file name start: [int] (default = 2) - The x,y,z start position which determines the scaling. **Returns** atlas: [.nii; nifti image] - Atlas labels in MNI space. """ start_time = time() atlmap = None print "Loading rois as base ..." if not os.path.exists(roifn): get_files() img = nib.load(roifn) base = img.get_data() aff = img.get_affine() fm = img.file_map true_dim = base.shape # Labelling new label_used = False print "Labeling new ..." region_num = 1 step = 1+(start*2) mstart = -start mend = start+1 # Align new to scale factor xdim, ydim, zdim = map(ceil, np.array(base.shape)/float(step)) if step == 1: assert xdim == base.shape[0] and ydim == base.shape[1] and zdim == base.shape[2] resized_base = np.zeros((xdim*step, ydim*step, zdim*step), dtype=int) resized_base[:base.shape[0], :base.shape[1], :base.shape[2]] = base base = resized_base del resized_base # Create new matrix new = np.zeros_like(base, dtype=np.int) # poke my finger in the eye of bjarne # TODO: Cythonize for z in xrange(start, base.shape[2]-start, step): for y in xrange(start, base.shape[1]-start, step): for x in xrange(start, base.shape[0]-start, step): if label_used: region_num += 1 # only increase counter when a label was used label_used = False # set other (step*step)-1 around me to same region for zz in xrange(mstart,mend): for yy in xrange(mstart,mend): for xx in xrange(mstart,mend): if (base[x+xx,y+yy,z+zz]): # Masking label_used = True new[x+xx,y+yy,z+zz] = region_num new = new[:true_dim[0], :true_dim[1], :true_dim[2]] # shrink new to correct size print "Your atlas has %d regions ..." % len(np.unique(new)) img = nib.Nifti1Image(new, affine=img.get_affine(), header=img.get_header(), file_map=img.file_map) del new print "Building atlas took %.3f sec ..." % (time()-start_time) return img def validate(atlas_fn, roifn): """ Validate that an atlas you've created is a valid based on the masking you have @param atlas_fn: the new atlas you've created @param roifn: nifti roi file name """ base = nib.load(roifn).get_data() try: new = nib.load(atlas_fn).get_data() except: sys.stderr.write("[Error]: Loading file %s failed!\n" % atlas_fn); exit(-1) # This is a mapping from base to new where if we get any conflicting regions we failed to make a valid atlas old_to_new = {} for i in xrange(new.shape[2]): for ii in xrange(new.shape[1]): for iii in xrange(new.shape[0]): if old_to_new.has_key(base[i,ii,iii]): if old_to_new[base[i,ii,iii]] != new[i,ii,iii]: print "[Error]; Index [%d,%d,%d] Should be: {0}, but is {1}".format(i, ii, iii, old_to_new[base[i,ii,iii]], new[i,ii,iii]) exit(911) else: if start == 0 and new[i,i,iii] in old_to_new.values(): import pdb; pdb.set_trace() old_to_new[base[i,ii,iii]] = new[i,i,iii] print "Success! Validation complete." if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 15069, 1946, 4946, 8113, 462, 4935, 357, 4023, 1378, 9654, 8443, 78, 13, 1326, 8, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 341...
2.521832
1,878
# Copyright 2017 reinforce.io. 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. # ============================================================================== """ Random agent that always returns a random action. """ from __future__ import absolute_import from __future__ import print_function from __future__ import division from random import gauss, random, randrange from tensorforce.agents import Agent
[ 2, 15069, 2177, 19594, 13, 952, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 137...
4.198198
222
import os import re import time from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver import Chrome from selenium.webdriver.support.expected_conditions import presence_of_element_located from selenium import webdriver from selenium.webdriver.chrome.options import Options ## ORIGINAL CODE ### # OS = os.name # # s.environ['PATH'] += '/Users/macbook/Documents/CS/PROJECT/AutoDownloader/TEST_DOWNLOADS/fileexteniontest.torrenttorrent.torrent' # driver = webdriver.Chrome(r'/Users/macbook/Documents/CS/PROJECT/AutoDownloader/TEST_DOWNLOADS/fileexteniontest.torrenttorrent.torrent/chromedriver') # driver.get('https://1337x.to/') ## To Load Extensions:: try: OS = os.name chrome_options = Options() chrome_options.add_extension('/Users/macbook/Documents/CS/PROJECT/AutoDownloader/TEST_DOWNLOADS/Selenium_Project/ad_blocker.crx') driver = webdriver.Chrome(options=chrome_options, executable_path= r'/Users/macbook/Documents/CS/PROJECT/AutoDownloader/TEST_DOWNLOADS/fileexteniontest.torrenttorrent.torrent/chromedriver') time.sleep(2) driver.get('https://1337x.to/') driver.implicitly_wait(25) ### no need to call more than once print(OS) print(driver) #print(driver.text) except Exception as e: print('ERROR IN PARSING CHROME EXTENSION', str(e)) try: search_box = driver.find_element_by_id('autocomplete') print(search_box.text) search_box.click() search_box.send_keys('chopper') click_search_box = driver.find_element_by_class_name('flaticon-search') #click_seach_box.click() #click_search_box.send_keys(Keys.ENTER) search_box.send_keys(Keys.ENTER) #driver.find_element_by_xpath("html/xxxxx").send_keys('keys.ENTER') except Exception as e: print('Element not found CANNOT FIND SEARCH BOX ', str(e)) try: search_box01 = driver.find_element_by_id('autocomplete') print(search_box01.text) search_box01.click() search_box01.send_keys(Keys.CONTROL, "a") search_box01.clear() search_box01.send_keys('the titanic') search_box01.send_keys(Keys.ENTER) except Exception as e: print('Element not found 2nd search', str(e)) ### IMPLIMENT EXPLICIT WAIT ## SINCE THE WEBPAGE MAY TAKE LONG TO LOAD, AND TIME TO PARSE, SET UP AN EXPLICIT WAIT--> THIS WILL WAIT UNTIL THE DEFINED THING IS LOADED ## SET UP LOOP TO ITERATE THROUGH LIST OF ELEMENTS try: body = WebDriverWait(driver, 15).until( EC.presence_of_element_located((By.CLASS_NAME, 'table-list-wrap')) #EC.presence_of_all_elements_located((by.CLASS, 'table-list table table-responsive table-striped')) ## ) print(body.text) print(),print() print('1111111111') href_link = body.find_element_by_xpath("/html/body/main/div/div/div/div[2]/div[1]/table/tbody/tr[1]/td[1]") print(href_link.text) except Exception as e: print('Element not found body search', str(e)) try: click_link = driver.find_element_by_link_text('The Titanic Secret by Clive Cussler, Jack Du Brul EPUB') print(click_link.text) click_link.click() except Exception as e: print('Element not found click test', str(e)) try: # magnet = driver.find_element magnet_pull =WebDriverWait(driver, 15).until( EC.presence_of_element_located((By.CLASS_NAME, "l4702248fa49fbaf25efd33c5904b4b3175b29571 l0e850ee5d16878d261dd01e2486970eda4fb2b0c l8680f3a1872d2d50e0908459a4bfa4dc04f0e610")) ) print('magnetpull info') print(magnet_pull.text) magnet_link = driver.find_element_by_xpath("/html/body/main/div/div/div/div[2]/div[1]/ul[1]/li[1]/a") print(magnet_link.text) magnet_link.click() except Exception as e: print('MAGNET PULL ERROR', str(e)) driver.quit() ###### GOOOD CODE ###### ##### TO LOOP THROUGH A LIST WHILE IN IMPLICIT WAIT # sm_table = body.find_element_by_class_name('"table-list table table-responsive table-striped"') # # sm_table = body.find_element_by_class_name('coll-1 name') # #sm_table = body.find_element_by_xpath("/html/body/main/div/div/div/div[2]/div[1]/table/tbody/tr[1]/td[1]") # # for cell in sm_table: # href_link = cell.find_element_by_xpath("/html/body/main/div/div/div/div[2]/div[1]/table/tbody/tr[1]/td[1]") # print(href_link.text) ## ORIGINAL CODE ### # OS = os.name # # s.environ['PATH'] += '/Users/macbook/Documents/CS/PROJECT/AutoDownloader/TEST_DOWNLOADS/fileexteniontest.torrenttorrent.torrent' # driver = webdriver.Chrome(r'/Users/macbook/Documents/CS/PROJECT/AutoDownloader/TEST_DOWNLOADS/fileexteniontest.torrenttorrent.torrent/chromedriver') # driver.get('https://1337x.to/') #################### EXPLICIT WAIT ########################### ###### USE WHEN DOWNLOAD COMPLETES ######### (23:00) #### use when you want to wait some to for executution ## explicit wait -- waits until condition is returned true. ## driver, 30 --> how long to wait till true # ## use body class to find element # ## nest elements in a tuple # print(f"my_element") # WebDriverWait(driver, 30).until( # EC.text_to_b_present_in_element( # (by.CLASS_NAME, 'progress-label'),## element filtration (class name, class name vaue as a tuple # 'complete' ## expected text as a string # # ) # # ) # my_element00 = driver.find_element_by_class_name('') ## <--- pass in class value #-> class styling method # print(my_element00) # # #### DROP DOWN CLASSES FOR MAGNET / TORRENT DOWNLOAD ## # <ul class="lfa750b508ad7d04e3fc96bae2ea94a5d121e6607 lcafae12a818cf41a5873ad374b98e79512c946c6"> # <li><a class="l4702248fa49fbaf25efd33c5904b4b3175b29571 l0e850ee5d16878d261dd01e2486970eda4fb2b0c l8680f3a1872d2d50e0908459a4bfa4dc04f0e610" href="magnet:?xt=urn:btih:F5BC20E9AA709CFC32BE63B2F6BEE56882EB7BD2&amp;dn=The+Titanic+Secret+by+Clive+Cussler%2C+Jack+Du+Brul+EPUB&amp;tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969%2Fannounce&amp;tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969%2Fannounce&amp;tr=udp%3A%2F%2F9.rarbg.to%3A2710%2Fannounce&amp;tr=udp%3A%2F%2Fexodus.desync.com%3A6969%2Fannounce&amp;tr=udp%3A%2F%2Ftracker.uw0.xyz%3A6969%2Fannounce&amp;tr=udp%3A%2F%2Fopen.stealth.si%3A80%2Fannounce&amp;tr=udp%3A%2F%2Ftracker.tiny-vps.com%3A6969%2Fannounce&amp;tr=udp%3A%2F%2Fopen.demonii.si%3A1337%2Fannounce&amp;tr=udp%3A%2F%2Ftracker.nibba.trade%3A1337%2Fannounce&amp;tr=udp%3A%2F%2Fopentracker.sktorrent.org%3A6969%2Fannounce&amp;tr=udp%3A%2F%2Fexplodie.org%3A6969%2Fannounce&amp;tr=udp%3A%2F%2Fbt.xxx-tracker.com%3A2710%2Fannounce&amp;tr=udp%3A%2F%2Fzephir.monocul.us%3A6969%2Fannounce&amp;tr=udp%3A%2F%2Famigacity.xyz%3A6969%2Fannounce&amp;tr=udp%3A%2F%2Ftracker.zer0day.to%3A1337%2Fannounce&amp;tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969%2Fannounce&amp;tr=udp%3A%2F%2Fcoppersurfer.tk%3A6969%2Fannounce" onclick="javascript: count(this);"><span class="icon"><i class="flaticon-ld08a4206c278863eddc1bf813faa024ef55ce0ef"></i></span>Magnet Download</a> </li> # <li class="dropdown"> # <a data-toggle="dropdown" class="l4702248fa49fbaf25efd33c5904b4b3175b29571 l0e850ee5d16878d261dd01e2486970eda4fb2b0c le41399670fcf7cac9ad72cbf1af20d76a1fa16ad" onclick="javascript: count(this);" href="#"><span class="icon"><i class="flaticon-le9f40194aef2ed76d8d0f7f1be7fe5aad6fce5e6"></i></span>Torrent Download</a> # <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> # <li><a class="l4702248fa49fbaf25efd33c5904b4b3175b29571 l0e850ee5d16878d261dd01e2486970eda4fb2b0c l13bf8e2d22d06c362f67b795686b16d022e80098" target="_blank" href="http://itorrents.org/torrent/F5BC20E9AA709CFC32BE63B2F6BEE56882EB7BD2.torrent"><span class="icon"><i class="flaticon-lbebff891414215bfc65d51afbd7677e45be19fad"></i></span>ITORRENTS MIRROR</a> </li> # <li><a class="l4702248fa49fbaf25efd33c5904b4b3175b29571 l0e850ee5d16878d261dd01e2486970eda4fb2b0c l13bf8e2d22d06c362f67b795686b16d022e80098" target="_blank" href="http://torrage.info/torrent.php?h=F5BC20E9AA709CFC32BE63B2F6BEE56882EB7BD2"><span class="icon"><i class="flaticon-lbebff891414215bfc65d51afbd7677e45be19fad"></i></span>TORRAGE MIRROR</a></li> # <li><a class="l4702248fa49fbaf25efd33c5904b4b3175b29571 l0e850ee5d16878d261dd01e2486970eda4fb2b0c l13bf8e2d22d06c362f67b795686b16d022e80098" target="_blank" href="http://btcache.me/torrent/F5BC20E9AA709CFC32BE63B2F6BEE56882EB7BD2"><span class="icon"><i class="flaticon-lbebff891414215bfc65d51afbd7677e45be19fad"></i></span>BTCACHE MIRROR</a></li> # <li><a class="l4702248fa49fbaf25efd33c5904b4b3175b29571 l0e850ee5d16878d261dd01e2486970eda4fb2b0c l8680f3a1872d2d50e0908459a4bfa4dc04f0e610" href="magnet:?xt=urn:btih:F5BC20E9AA709CFC32BE63B2F6BEE56882EB7BD2&amp;dn=The+Titanic+Secret+by+Clive+Cussler%2C+Jack+Du+Brul+EPUB&amp;tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969%2Fannounce&amp;tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969%2Fannounce&amp;tr=udp%3A%2F%2F9.rarbg.to%3A2710%2Fannounce&amp;tr=udp%3A%2F%2Fexodus.desync.com%3A6969%2Fannounce&amp;tr=udp%3A%2F%2Ftracker.uw0.xyz%3A6969%2Fannounce&amp;tr=udp%3A%2F%2Fopen.stealth.si%3A80%2Fannounce&amp;tr=udp%3A%2F%2Ftracker.tiny-vps.com%3A6969%2Fannounce&amp;tr=udp%3A%2F%2Fopen.demonii.si%3A1337%2Fannounce&amp;tr=udp%3A%2F%2Ftracker.nibba.trade%3A1337%2Fannounce&amp;tr=udp%3A%2F%2Fopentracker.sktorrent.org%3A6969%2Fannounce&amp;tr=udp%3A%2F%2Fexplodie.org%3A6969%2Fannounce&amp;tr=udp%3A%2F%2Fbt.xxx-tracker.com%3A2710%2Fannounce&amp;tr=udp%3A%2F%2Fzephir.monocul.us%3A6969%2Fannounce&amp;tr=udp%3A%2F%2Famigacity.xyz%3A6969%2Fannounce&amp;tr=udp%3A%2F%2Ftracker.zer0day.to%3A1337%2Fannounce&amp;tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969%2Fannounce&amp;tr=udp%3A%2F%2Fcoppersurfer.tk%3A6969%2Fannounce"><span class="icon"><i class="flaticon-ld08a4206c278863eddc1bf813faa024ef55ce0ef"></i></span>None Working? Use Magnet</a></li> #
[ 11748, 28686, 198, 11748, 302, 198, 11748, 640, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 11321, 13, 13083, 1330, 26363, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 11321, ...
2.196035
4,540
import os import tempfile import shutil import requests import sys import logging import json from src.server.dependency import ModelData import tensorflow as tf def train_model(training_id, model_data: ModelData): """ Train model(s) based on a given model and hyperparameters Now supporting two hyperparameters which are - Optimizer and learning_rate """ # SET LOGGER TO PRINT TO STDOUT AND WRITE TO FILE logging.basicConfig( level=logging.DEBUG, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[ logging.FileHandler("/log/{}.log".format(training_id)), logging.StreamHandler(sys.stdout) ] ) log = logging.getLogger('db_microservice_logger') sys.stdout = StreamToLogger(log,logging.INFO) sys.stderr = StreamToLogger(log,logging.ERROR) # get API KEY from the environment file API_KEY = os.getenv('API_KEY') best_acc = -1 best_val_acc = -1 best_loss = -1 best_val_loss = -1 best_model = None best_config = None best_optimizer = None best_loss_fn = None # print("Save:" + str(model_data.save)) logging.info("Save:" + str(model_data.save)) try: # print('[Training] Starting to train model ID: ' + training_id) logging.info('[Training] Starting to train model ID: ' + training_id) dataset_root = '/app/src/public_dataset' img_height = 28 img_width = 28 train_ds = tf.keras.preprocessing.image_dataset_from_directory( dataset_root, validation_split=model_data.split, subset="training", seed=model_data.seed, image_size=(img_height, img_width), batch_size=model_data.batch_size ) validation_ds = tf.keras.preprocessing.image_dataset_from_directory( dataset_root, validation_split=model_data.split, subset="validation", seed=model_data.seed, image_size=(img_height, img_width), batch_size=model_data.batch_size ) autotune_buf_size = tf.data.AUTOTUNE train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=autotune_buf_size) validation_ds = validation_ds.cache().prefetch(buffer_size=autotune_buf_size) optimizer_dict = model_data.optimizer.dict() config = {} if "config" in optimizer_dict and optimizer_dict["config"]: # convert all float config from string to float convert_data_type(optimizer_dict["config"]) config = optimizer_dict["config"] # if learning_rate is not defined, it will use the optimizor's default value learning_rate_list = [None] if model_data.optimizer.learning_rate: learning_rate_list = model_data.optimizer.learning_rate # get loss function object loss_dict = model_data.loss_function.dict() if loss_dict["config"] is None: loss_dict["config"] = {} else: convert_data_type(loss_dict["config"]) loss_fn = tf.keras.losses.get(loss_dict) logging.info(loss_fn) # create all hyperparameters combination optimizer_class = model_data.optimizer.dict() hyperparameters = [[o,lr] for o in optimizer_dict["class_name"] for lr in learning_rate_list] # loop through all hyperparameters for hp in hyperparameters: # load model from json file model = tf.keras.models.model_from_json(model_data.model_structure) optimizer_obj = { "class_name": hp[0], "config": config } # set learning rate if not None if hp[1]: optimizer_obj["config"]["learning_rate"] = hp[1] optimizer = tf.keras.optimizers.get(optimizer_obj) n_epochs = model_data.n_epochs # train the model (acc, val_acc, loss, val_loss, model) = fit(model, loss_fn, optimizer, train_ds, validation_ds, n_epochs) # CHECK FOR THE BEST MODEL (from validation accuracy) if val_acc > best_val_acc: best_acc = acc best_val_acc = val_acc best_loss = loss best_val_loss = val_loss best_model = model best_optimizer = optimizer.get_config() best_loss_fn = loss_fn.get_config() # END LOOP logging.info('[Training] Completed training on model ID: ' + training_id) # If we are saving the model, we must save it to folder, zip that folder, # and then send the zip file to the server via HTTP requests if model_data.save: # print('[Training] Preparing to save Model data on model ID: ' + training_id) logging.info('[Training] Preparing to save Model data on model ID: ' + training_id) # Create temp dir and save model to it tmpdir = tempfile.mkdtemp() model_save_path = os.path.join(tmpdir, training_id) # Save model nested 1 more layer down to facilitate unzipping tf.saved_model.save(best_model, os.path.join(model_save_path, training_id)) shutil.make_archive(model_save_path, 'zip', model_save_path) print(tmpdir) files = {'model': open(model_save_path+'.zip', 'rb')} requests.post( 'http://host.docker.internal:' + str(os.getenv('SERVER_PORT')) + '/training/model', headers={'api_key': API_KEY}, params={'training_id': training_id}, files=files ) # print('[Training] Sent SavedModel file data on model ID: ' + training_id) logging.info('[Training] Sent SavedModel file data on model ID: ' + training_id) except: # print('[Training] Critical error on training: ' + training_id) logging.exception('[Training] Critical error on training: ' + training_id) result = { 'training_accuracy': best_acc, 'validation_accuracy': best_val_acc, 'training_loss': best_loss, 'validation_loss': best_val_loss, 'optimizer_config': str(best_optimizer), 'loss_config': str(best_loss_fn) } logging.info('[Training] results: ' + str(result)) # Send HTTP request to server with the statistics on this training r = requests.post( 'http://host.docker.internal:' + str(os.getenv('SERVER_PORT')) + '/training/result', headers={'api_key': API_KEY}, json={ 'dataset_name': os.getenv('DATASET_NAME'), 'training_id': training_id, 'results': result }) r.raise_for_status() # print("[Training Results] Sent training results to server.") logging.info("[Training Results] Sent training results to server.")
[ 11748, 28686, 198, 11748, 20218, 7753, 198, 11748, 4423, 346, 198, 11748, 7007, 198, 11748, 25064, 198, 11748, 18931, 198, 11748, 33918, 198, 198, 6738, 12351, 13, 15388, 13, 45841, 1387, 1330, 9104, 6601, 198, 11748, 11192, 273, 11125, 3...
2.247742
3,100
from flask import Flask from flask import render_template from flask import request from model import MovieWebDAO import json from ml import Forcast app = Flask(__name__) if __name__ == '__main__': print("http://localhost:15001") app.run(host='0.0.0.0', debug=True, port=15001)
[ 6738, 42903, 1330, 46947, 198, 6738, 42903, 1330, 8543, 62, 28243, 198, 6738, 42903, 1330, 2581, 198, 6738, 2746, 1330, 15875, 13908, 5631, 46, 198, 11748, 33918, 198, 6738, 25962, 1330, 1114, 2701, 198, 198, 1324, 796, 46947, 7, 834, 3...
3.010417
96
import h5py import numpy as np import cv2 """ Just gets rid of the negatives by only reading the positives, then writing them to replace the existing archive """ archive_dir="positive_augmented_samples.h5" x,y = read_new(archive_dir) write_new(archive_dir, x, y)
[ 11748, 289, 20, 9078, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 198, 37811, 198, 5703, 3011, 5755, 286, 262, 42510, 416, 691, 3555, 262, 38548, 11, 788, 3597, 606, 284, 6330, 262, 4683, 15424, 198, 37811, 198, ...
3.117647
85
# -*- coding: utf-8 -*- """ Automate WhatsApp - Sending WhatsApp message @author: DELL Ishvina Kapoor """ #importing the necessary modules import pywhatkit as pkt import getpass as gp #displaying a welcome message print("Automating Whatsapp!") #capturing the target phone number from the user phone_num = gp.getpass(prompt = 'Enter the phone number(with country code) : ', stream = None) #capture the message message = "Hi IK this side" #call the method #the time is in 24 hr format pkt.sendwhatmsg(phone_num, message, 22 , 33) #will be displayed once whatsapp is automated print("Delivered to the target user")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 38062, 378, 37666, 532, 32038, 37666, 3275, 201, 198, 201, 198, 31, 9800, 25, 5550, 3069, 24303, 85, 1437, 27344, 2675, 201, 198, 37811, 201, 198, ...
2.990741
216
import gast as ast from beniget import Ancestors, DefUseChains as DUC, UseDefChains from beniget.beniget import Def __all__ = ["Ancestors", "DefUseChains", "UseDefChains"] # this import has to be after the definition of DefUseChains from transonic.analyses.extast import CommentLine # noqa: E402
[ 11748, 21956, 355, 6468, 198, 198, 6738, 1888, 328, 316, 1330, 31200, 669, 11, 2896, 11041, 1925, 1299, 355, 360, 9598, 11, 5765, 7469, 1925, 1299, 198, 198, 6738, 1888, 328, 316, 13, 11722, 328, 316, 1330, 2896, 628, 198, 834, 439, ...
3.070707
99
# -*- coding: utf-8 -*- """ Created on Thu Sep 3 16:43:28 2020 @author: nicholls """
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 26223, 8621, 220, 513, 1467, 25, 3559, 25, 2078, 12131, 198, 198, 31, 9800, 25, 299, 488, 33421, 198, 37811, 628 ]
2.25641
39
from collections import Counter print(main('day16.txt'))
[ 6738, 17268, 1330, 15034, 628, 628, 198, 220, 220, 220, 220, 220, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 198, 4798, 7, 12417, 10786, 820, 1433, 13, 14116, 6, 4008, 198 ]
2.264706
34
# Author: Ibrahim Alhas - ID: 1533204. # MODEL 3: CNN with built-in tensorflow tokenizer. # This is the final version of the model (not the base). # Packages and libraries used for this model. # ** Install these if not installed already **. import numpy as np import pandas as pd import matplotlib.pyplot as plt import datetime from time import time import re from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score, f1_score, roc_curve, \ classification_report from tensorflow import keras from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.utils import to_categorical from keras import layers from keras.models import Sequential from sklearn.model_selection import train_test_split, cross_validate import tensorflow as tf import seaborn as sns import warnings import keras from keras.models import Sequential, Model from keras.layers import Dense, Dropout, Flatten, Activation, BatchNormalization from keras.layers.noise import GaussianNoise from keras.layers import Conv2D, MaxPooling2D warnings.filterwarnings('ignore') # plt.style.use('ggplot') # Basic data visualisation and analysis ------------------------------------------------------------------------------ # We see that the title column is from news articles, and the text column forms the twitter tweet extracts. true = pd.read_csv('True.csv') false = pd.read_csv('Fake.csv') # We drop the columns we do not need. See chapter 3, model CNN for more details. true = true.drop('title', axis=1) true = true.drop('subject', axis=1) true = true.drop('date', axis=1) false = false.drop('title', axis=1) false = false.drop('subject', axis=1) false = false.drop('date', axis=1) # We set the labels for each data instance, where factual = 1, otherwise 0. false['label'] = 0 true['label'] = 1 # We merge the two divided datasets (true and fake) into a singular dataset. data = pd.concat([true, false], ignore_index=True) texts = data['text'] labels = data['label'] x = texts y = labels # We incorporate the publishers feature from title and text instances, and place it into the dataset manually. # First Creating list of index that do not have publication part. We can use this as a new feature. unknown_publishers = [] for index, row in enumerate(true.text.values): try: record = row.split(" -", maxsplit=1) # if no text part is present, following will give error print(record[1]) # if len of piblication part is greater than 260 # following will give error, ensuring no text having "-" in between is counted assert (len(record[0]) < 260) except: unknown_publishers.append(index) # We print the instances where publication information is absent or different. print(true.iloc[unknown_publishers].text) # We want to use the publication information as a new feature. publisher = [] tmp_text = [] for index, row in enumerate(true.text.values): if index in unknown_publishers: # Append unknown publisher: tmp_text.append(row) publisher.append("Unknown") continue record = row.split(" -", maxsplit=1) publisher.append(record[0]) tmp_text.append(record[1]) # Replace text column with new text + add a new feature column called publisher/source. true["publisher"] = publisher true["text"] = tmp_text del publisher, tmp_text, record, unknown_publishers # Validate that the publisher/source column has been added to the dataset. print(true.head()) # Check for missing values, then drop them for both datasets. print([index for index, text in enumerate(true.text.values) if str(text).strip() == '']) true = true.drop(8970, axis=0) fakeEmptyIndex = [index for index, text in enumerate(false.text.values) if str(text).strip() == ''] print(f"No of empty rows: {len(fakeEmptyIndex)}") false.iloc[fakeEmptyIndex].tail() # - # For CNNs, we have to vectorize the text into 2d integers (tensors). MAX_SEQUENCE_LENGTH = 5000 MAX_NUM_WORDS = 25000 EMBEDDING_DIM = 300 TEST_SPLIT = 0.2 epochs = 1 # We tokenize the text, just like all other models-------------------------------------------------------------------- tokenizer = Tokenizer(num_words=MAX_NUM_WORDS) tokenizer.fit_on_texts(texts) sequences = tokenizer.texts_to_sequences(texts) word_index = tokenizer.word_index num_words = min(MAX_NUM_WORDS, len(word_index)) + 1 data = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH, padding='pre', truncating='pre') # Print the total number of tokens: print('Found %s tokens.' % len(word_index)) # We partition our dataset into train/test. x_train, x_val, y_train, y_val = train_test_split(data, labels.apply(lambda x: 0 if x == 0 else 1), test_size=TEST_SPLIT) log_dir = "logs\\model\\" # A custom callbacks function, which initially included tensorboard. mycallbacks = [ tf.keras.callbacks.ReduceLROnPlateau(monitor='val_accuracy', patience=2, verbose=1, factor=0.5, min_lr=0.00001), tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=2, restore_best_weights=True), # Restoring the best # ...weights will help keep the optimal weights. # tf.keras.callbacks.TensorBoard(log_dir="./logs"), # NEWLY ADDED - CHECK. # tf.keras.callbacks.TensorBoard(log_dir=log_dir.format(time())), # NEWLY ADDED - CHECK. # tensorboard --logdir logs --> to check tensorboard feedback. ] # Parameters for our model. We experimented with some combinations and settled on this configuration------------------ model = Sequential( [ # Word/sequence processing: layers.Embedding(num_words, EMBEDDING_DIM, input_length=MAX_SEQUENCE_LENGTH, trainable=True), # The layers: layers.Conv1D(128, 5, activation='relu'), layers.GlobalMaxPooling1D(), # We classify our model here: layers.Dense(128, activation='relu'), layers.Dense(1, activation='sigmoid') ]) # We compile our model and run, with the loss function crossentropy, and optimizer rmsprop (we experimented with adam, # ...but rmsprop produced better results). model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) model.summary() print("Model weights:") print(model.weights) # tensorboard_callback = keras.callbacks.TensorBoard(log_dir="./logs") history = model.fit(x_train, y_train, batch_size=256, epochs=epochs, validation_data=(x_val, y_val), callbacks=mycallbacks) # Produce a figure, for every epoch, and show performance metrics. epochs = [i for i in range(1)] fig, ax = plt.subplots(1, 2) train_acc = history.history['accuracy'] train_loss = history.history['loss'] val_acc = history.history['val_accuracy'] val_loss = history.history['val_loss'] fig.set_size_inches(20, 10) ax[0].plot(epochs, train_acc, 'go-', label='Training Accuracy') ax[0].plot(epochs, val_acc, 'ro-', label='Testing Accuracy') ax[0].set_title('Training & Testing Accuracy') ax[0].legend() ax[0].set_xlabel("Epochs") ax[0].set_ylabel("Accuracy") ax[1].plot(epochs, train_loss, 'go-', label='Training Loss') ax[1].plot(epochs, val_loss, 'ro-', label='Testing Loss') ax[1].set_title('Training & Testing Loss') ax[1].legend() ax[1].set_xlabel("Epochs") ax[1].set_ylabel("Loss") plt.show() ''' history_dict = history.history acc = history_dict['accuracy'] val_acc = history_dict['val_accuracy'] loss = history_dict['loss'] val_loss = history_dict['val_loss'] epochs = history.epoch plt.figure(figsize=(12, 9)) plt.plot(epochs, loss, 'r', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss', size=20) plt.xlabel('Epochs', size=20) plt.ylabel('Loss', size=20) plt.legend(prop={'size': 20}) plt.show() plt.figure(figsize=(12, 9)) plt.plot(epochs, acc, 'g', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy', size=20) plt.xlabel('Epochs', size=20) plt.ylabel('Accuracy', size=20) plt.legend(prop={'size': 20}) plt.ylim((0.5, 1)) plt.show() ''' # We evaluate our model by predicting a few instances from our test data (the first 5)-------------------------------- print("Evaluation:") print(model.evaluate(x_val, y_val)) # We predict a few instances (up to 5). pred = model.predict(x_val) print(pred[:5]) binary_predictions = [] for i in pred: if i >= 0.5: binary_predictions.append(1) else: binary_predictions.append(0) # We print performance metrics: print('Accuracy on test set:', accuracy_score(binary_predictions, y_val)) print('Precision on test set:', precision_score(binary_predictions, y_val)) print('Recall on test set:', recall_score(binary_predictions, y_val)) print('F1 on test set:', f1_score(binary_predictions, y_val)) # We print the classification report (as an extra): print(classification_report(y_val, pred.round(), target_names=['Fact', 'Fiction'])) # We print the confusion matrix. cmm = confusion_matrix(y_val, pred.round()) print(cmm) print("Ibrahim Alhas") cmm = pd.DataFrame(cmm, index=['Fake', 'Original'], columns=['Fake', 'Original']) plt.figure(figsize=(10, 10)) sns.heatmap(cmm, cmap="Blues", linecolor='black', linewidth=1, annot=True, fmt='', xticklabels=['Fake', 'Original'], yticklabels=['Fake', 'Original']) plt.xlabel("Predicted") plt.ylabel("Actual") plt.show() # End----------------------------------------------------
[ 2, 220, 220, 6434, 25, 30917, 978, 10134, 532, 4522, 25, 1315, 2091, 18638, 13, 198, 198, 2, 220, 220, 19164, 3698, 513, 25, 220, 220, 220, 8100, 351, 3170, 12, 259, 11192, 273, 11125, 11241, 7509, 13, 198, 2, 220, 220, 770, 318, ...
2.836017
3,354
#!/usr/bin/env python2 # -*- coding: utf8 -*- # # Copyright (c) 2017 unfoldingWord # http://creativecommons.org/licenses/MIT/ # See LICENSE file for details. # # Contributors: # Richard Mahn <rich.mahn@unfoldingword.org> """ This script generates the HTML tN documents for each book of the Bible """ from __future__ import unicode_literals, print_function import os import sys import re import pprint import logging import argparse import tempfile import markdown import shutil import subprocess import csv import codecs import markdown2 import json from glob import glob from bs4 import BeautifulSoup from usfm_tools.transform import UsfmTransform from ...general_tools.file_utils import write_file, read_file, load_json_object, unzip, load_yaml_object from ...general_tools.url_utils import download_file from ...general_tools.bible_books import BOOK_NUMBERS, BOOK_CHAPTER_VERSES from ...general_tools.usfm_utils import usfm3_to_usfm2 _print = print def main(ta_tag, tn_tag, tw_tag, ust_tag, ult_tag, ugnt_tag, lang_code, books, working_dir, output_dir): """ :param ta_tag: :param tn_tag: :param tw_tag: :param ust_tag: :param ult_tag: :param ugnt_tag: :param lang_code: :param books: :param working_dir: :param output_dir: :return: """ tn_converter = TnConverter(ta_tag, tn_tag, tw_tag, ust_tag, ult_tag, ugnt_tag, working_dir, output_dir, lang_code, books) tn_converter.run() if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-l', '--lang', dest='lang_code', default='en', required=False, help="Language Code") parser.add_argument('-b', '--book_id', dest='books', nargs='+', default=None, required=False, help="Bible Book(s)") parser.add_argument('-w', '--working', dest='working_dir', default=False, required=False, help="Working Directory") parser.add_argument('-o', '--output', dest='output_dir', default=False, required=False, help="Output Directory") parser.add_argument('--ta-tag', dest='ta', default='v10', required=False, help="tA Tag") parser.add_argument('--tn-tag', dest='tn', default='v13', required=False, help="tN Tag") parser.add_argument('--tw-tag', dest='tw', default='v9', required=False, help="tW Tag") parser.add_argument('--ust-tag', dest='ust', default='master', required=False, help="UST Tag") parser.add_argument('--ult-tag', dest='ult', default='master', required=False, help="ULT Tag") parser.add_argument('--ugnt-tag', dest='ugnt', default='v0.4', required=False, help="UGNT Tag") args = parser.parse_args(sys.argv[1:]) main(args.ta, args.tn, args.tw, args.ust, args.ult, args.ugnt, args.lang_code, args.books, args.working_dir, args.output_dir)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 23, 532, 9, 12, 198, 2, 198, 2, 220, 15069, 357, 66, 8, 2177, 34502, 26449, 198, 2, 220, 2638, 1378, 20123, 425, 9503, 684, 13, 2398, 14...
2.647654
1,087
import pandas as pd import numpy as np from tqdm import tqdm import argparse from pyscenic.aucell import aucell from .aucell import create_gene_signatures from .aucell import assign_bootstrap if __name__ == "__main__": main()
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 11748, 1822, 29572, 198, 6738, 279, 28349, 35866, 13, 559, 3846, 1330, 35851, 3846, 198, 6738, 764, 559, 3846, ...
3
76
"""Custom topology example s7 ---- s8 ---- s9 / \ / \ / \ h1 h2 h3 h4 h5 h6 """ from mininet.topo import Topo print('Loading MyTopo') topos = {'mytopo': (lambda: MyTopo())}
[ 37811, 15022, 1353, 1435, 1672, 628, 220, 220, 220, 264, 22, 13498, 264, 23, 13498, 264, 24, 198, 220, 220, 1220, 220, 3467, 220, 220, 220, 1220, 220, 3467, 220, 220, 220, 1220, 220, 3467, 198, 220, 289, 16, 220, 289, 17, 220, 289...
2.082474
97
from rule_condition import Condition from rule_action import Action from rule_template import RuleTemplate from rule_engine import RuleEngine from rule import Rule from rule_data import Data from rule_scope import Scope from action_handler_send_email import SendEmailHandler from action_handler_report_alarm import ReportAlarmHandler if __name__=="__main__": main()
[ 6738, 3896, 62, 31448, 1330, 24295, 198, 6738, 3896, 62, 2673, 1330, 7561, 198, 6738, 3896, 62, 28243, 1330, 14330, 30800, 198, 6738, 3896, 62, 18392, 1330, 14330, 13798, 198, 6738, 3896, 1330, 14330, 198, 6738, 3896, 62, 7890, 1330, 60...
3.495495
111
from django.urls import path from .views import * rest_urls = list(map(lambda x: path(x[0], x[1], name=x[2]), [ ('login/', login, 'login'), ('issue_asset/', issue_asset, 'issue_asset'), ('buy/', buy, 'buy'), ('get_assets/', get_assets, 'get_assets'), ('get_transactions/', get_transactions, 'get_transactions') ])) urlpatterns = rest_urls
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 198, 6738, 764, 33571, 1330, 1635, 198, 198, 2118, 62, 6371, 82, 796, 1351, 7, 8899, 7, 50033, 2124, 25, 3108, 7, 87, 58, 15, 4357, 2124, 58, 16, 4357, 1438, 28, 87, 58, 17, 465...
2.42953
149
import os import numpy as np import monai import math import torch import glob from skimage.morphology import remove_small_holes, remove_small_objects from monai.transforms import ( LoadImaged, AddChanneld, Orientationd, Spacingd, ScaleIntensityRanged, SpatialPadd, RandAffined, RandCropByPosNegLabeld, RandGaussianNoised, RandFlipd, RandFlipd, RandFlipd, CastToTyped, ) def get_xforms_scans_or_synthetic_lesions(mode="scans", keys=("image", "label")): """returns a composed transform for scans or synthetic lesions.""" xforms = [ LoadImaged(keys), AddChanneld(keys), Orientationd(keys, axcodes="LPS"), Spacingd(keys, pixdim=(1.25, 1.25, 5.0), mode=("bilinear", "nearest")[: len(keys)]), ] dtype = (np.int16, np.uint8) if mode == "synthetic": xforms.extend([ ScaleIntensityRanged(keys[0], a_min=-1000.0, a_max=500.0, b_min=0.0, b_max=1.0, clip=True), ]) dtype = (np.float32, np.uint8) xforms.extend([CastToTyped(keys, dtype=dtype)]) return monai.transforms.Compose(xforms) def get_xforms_load(mode="load", keys=("image", "label")): """returns a composed transform.""" xforms = [ LoadImaged(keys), ScaleIntensityRanged(keys[0], a_min=-1000.0, a_max=500.0, b_min=0.0, b_max=1.0, clip=True), ] if mode == "load": dtype = (np.float32, np.uint8) xforms.extend([CastToTyped(keys, dtype=dtype)]) return monai.transforms.Compose(xforms)
[ 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 937, 1872, 198, 11748, 10688, 198, 11748, 28034, 198, 11748, 15095, 198, 6738, 1341, 9060, 13, 24503, 1435, 1330, 4781, 62, 17470, 62, 28439, 11, 4781, 62, 17470, 62, 48205, ...
2.198847
694
import json import pytest from unittest import TestCase from rest_framework.test import APIClient from ..models import Group, Prediction
[ 11748, 33918, 198, 11748, 12972, 9288, 198, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 6738, 1334, 62, 30604, 13, 9288, 1330, 3486, 2149, 75, 1153, 198, 6738, 11485, 27530, 1330, 4912, 11, 46690, 628, 198 ]
3.783784
37
import stringdist def levenshtein(stru1, stru2): """ Measures the Levenshtein distance between two strings Parameters --------------- stru1 First string stru2 Second string Returns --------------- levens_dist Levenshtein distance """ return stringdist.levenshtein(stru1, stru2)
[ 11748, 4731, 17080, 628, 198, 4299, 443, 574, 1477, 22006, 7, 19554, 16, 11, 2874, 17, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 45040, 262, 1004, 574, 1477, 22006, 5253, 1022, 734, 13042, 628, 220, 220, 220, 40117, 198, ...
2.562044
137
"""Specification for the RoboMaker delete. simulation application component.""" # 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 dataclasses import dataclass from typing import List from common.sagemaker_component_spec import SageMakerComponentSpec from common.common_inputs import ( COMMON_INPUTS, SageMakerComponentCommonInputs, SageMakerComponentInput as Input, SageMakerComponentOutput as Output, SageMakerComponentBaseOutputs, SageMakerComponentInputValidator as InputValidator, SageMakerComponentOutputValidator as OutputValidator, ) class RoboMakerDeleteSimulationAppSpec( SageMakerComponentSpec[ RoboMakerDeleteSimulationAppInputs, RoboMakerDeleteSimulationAppOutputs ] ): INPUTS: RoboMakerDeleteSimulationAppInputs = RoboMakerDeleteSimulationAppInputs( arn=InputValidator( input_type=str, required=True, description="The Amazon Resource Name (ARN) of the simulation application.", default="", ), version=InputValidator( input_type=str, required=False, description="The version of the simulation application.", default=None, ), **vars(COMMON_INPUTS), ) OUTPUTS = RoboMakerDeleteSimulationAppOutputs( arn=OutputValidator( description="The Amazon Resource Name (ARN) of the simulation application." ), )
[ 37811, 22882, 2649, 329, 262, 39702, 48890, 12233, 13, 18640, 3586, 7515, 526, 15931, 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...
2.98
650
DOWNLOADS_PER_DATASET = ''' /* VER 1.2 used for total downloads from 2016-08-01 which is used to sort datasets by "most downloads" for the "XXX downloads" counter on /search and on each individual dataset gets all download events and counts occurrences of unique combinations of user, resource, and dataset, and day, then counts the number of occurrences of dataset by week. In other words, if a user downloaded all 3 resources on a dataset 2 different times on the same day (6 total downloads), the result of this query would be 3. It answers the question "What is the total number of downloads of any resource on a given dataset, ignorning repeated downloads from the same user the same day?"*/ function main() {{ return Events({{ from_date: '{}', to_date: '{}', event_selectors: [{{event: "resource download"}}] }}) .groupBy(["distinct_id","properties.resource id","properties.dataset id",mixpanel.numeric_bucket('time',mixpanel.daily_time_buckets)],mixpanel.reducer.count()) .groupBy(["key.2"], mixpanel.reducer.count()) .map(function(r){{ return {{ dataset_id: r.key[0], value: r.value }}; }}); }} ''' PAGEVIEWS_PER_DATASET = ''' /* VER 1.0 gets all page view events and counts the occurrence of each unique dataset. It answers the question "How many times has this dataset page been viewed?"*/ /* Note: as of 12-july-2017, this query fails (or at least doesn't return what is expected), because there are no dataset IDs being sent with the page view event.*/ function main() {{ return Events({{ from_date: '{}', to_date: '{}', event_selectors: [{{event: "page view"}}] }}) .groupBy(["properties.dataset id"],mixpanel.reducer.count()) .map(function(r){{ return {{ dataset_id: r.key[0], value: r.value }}; }}); }} ''' DOWNLOADS_PER_DATASET_PER_WEEK = ''' /* VER 1.0 selects all download events, counts unique combinations of week, user, resource, and dataset, then counts the number of those unique combinations by dataset. That is to say if a single user downloaded 10 different resources two times each (20 total downloads) from a single dataset in a given week, the count returned by this query would be 10*/ function main() {{ return Events({{ from_date: '{}', to_date: '{}', event_selectors: [{{event: "resource download"}}] }}) .groupBy(["distinct_id","properties.resource id","properties.dataset id",mixpanel.numeric_bucket('time',mixpanel.daily_time_buckets)],mixpanel.reducer.count()) .groupBy(["key.2",(mixpanel.numeric_bucket('key.3',mixpanel.weekly_time_buckets))],mixpanel.reducer.count()) .sortAsc(function(row){{return row.key[1]}}) .map(function(r){{ return {{ dataset_id: r.key[0], date: new Date(r.key[1]).toISOString().substring(0,10), value: r.value }}; }}); }} ''' PAGEVIEWS_PER_ORGANIZATION = ''' /* VER 1.0 gets all page view events and counts unique combinations of user and org. This is to say, if a single user looked at 3 different datasets from a single organization and then looked at the organization page as well (4 total page views), the count returned by this query would be 1. It answers the question "How many individuals looked at one or more of an organization's content."*/ function main() {{ return Events({{ from_date: '{}', to_date: '{}', event_selectors: [{{event: "page view"}}] }}) .groupBy(["distinct_id","properties.org id"],mixpanel.reducer.count()) .groupBy([function(row) {{return row.key.slice(1)}}],mixpanel.reducer.count()) .map(function(r){{ return {{ org_id: r.key[0], value: r.value }}; }}); }} ''' DOWNLOADS_PER_ORGANIZATION = ''' /* VER 1.0 gets all download events and counts unique combinations of user and org. This is to say, if a single user downloaded 5 resources 2 times from datasets belonging to a given organization (10 total downloads), the count returned by this query would be 1. It answers the question "How many individuals one or more resources from an organization's datasets."*/ function main() {{ return Events({{ from_date: '{}', to_date: '{}', event_selectors: [{{event: "resource download"}}] }}) .groupBy(["distinct_id","properties.org id"],mixpanel.reducer.count()) .groupBy([function(row) {{return row.key.slice(1)}}],mixpanel.reducer.count()) .map(function(r){{ return {{ org_id: r.key[0], value: r.value }}; }}); }} ''' PAGEVIEWS_PER_ORGANIZATION_PER_WEEK = ''' /* VER 1.0 gets all page view events and counts unique combinations of week and org. This is to say, if a single user looked at 3 different datasets from a single organization and then looked at the organization page as well (4 total page views) in a given week, the count returned by this query for that week would be 4. It answers the question "How many page views did an organization's content receive in a given week."*/ function main() {{ return Events({{ from_date: '{}', to_date: '{}', event_selectors: [{{event: "page view", selector: 'properties["org id"] != ""'}}] }}) .groupBy(["properties.org id",mixpanel.numeric_bucket('time',mixpanel.weekly_time_buckets)],mixpanel.reducer.count()) .sortAsc(function(row){{return row.key[1]}}) .map(function(r){{ return {{ org_id: r.key[0], date: new Date(r.key[1]).toISOString().substring(0,10), value: r.value }}; }}); }} ''' DOWNLOADS_PER_ORGANIZATION_PER_WEEK = ''' /* VER 1.0 selects all download events, counts unique combinations of week, user, resource, and org, then counts the number of those unique combinations by org. That is to say if a single user downloaded 10 different resources two times each (20 total downloads) from a given org in a given week, the count returned by this query would be 10*/ function main() {{ return Events({{ from_date: '{}', to_date: '{}', event_selectors: [{{event: "resource download"}}] }}) .groupBy(["distinct_id","properties.resource id","properties.org id",mixpanel.numeric_bucket('time',mixpanel.daily_time_buckets)],mixpanel.reducer.count()) .groupBy(["key.2",(mixpanel.numeric_bucket('key.3',mixpanel.weekly_time_buckets))],mixpanel.reducer.count()) .sortAsc(function(row){{return row.key[1]}}) .map(function(r){{ return {{ org_id: r.key[0], date: new Date(r.key[1]).toISOString().substring(0,10), value: r.value }}; }}); }} ''' DOWNLOADS_PER_ORGANIZATION_PER_DATASET = ''' /* VER 1.0 unique (by distinct id, resource id, dataset id, org id) downloads by dataset id (24 weeks, used for top downloads on org page)*/ /*selects all download events, counts unique combinations of day, user, resource, dataset, and org, then counts the number of those unique combinations by dataset. That is to say if a single user downloaded 10 different resources two times each (20 total downloads) from a single dataset in a given day (and on no other days), the count returned by this query would be 10*/ function main() {{ return Events({{ from_date: '{}', to_date: '{}', event_selectors: [{{event: "resource download"}}] }}) .groupBy(["distinct_id","properties.resource id",mixpanel.numeric_bucket('time',mixpanel.daily_time_buckets),"properties.dataset id", "properties.org id"],mixpanel.reducer.count()) .groupBy([function(row) {{return row.key.slice(4)}}, function(row) {{return row.key.slice(3)}}],mixpanel.reducer.count()) .map(function(r){{ return {{ org_id: r.key[0], dataset_id: r.key[1], value: r.value }}; }}) .sortDesc('value'); }} '''
[ 41925, 35613, 50, 62, 18973, 62, 35, 1404, 1921, 2767, 796, 705, 7061, 198, 15211, 33310, 352, 13, 17, 198, 198, 1484, 329, 2472, 21333, 422, 1584, 12, 2919, 12, 486, 543, 318, 973, 284, 3297, 40522, 416, 366, 1712, 21333, 1, 329, ...
2.955253
2,570
""" Profile ../profile-datasets-py/div83/077.py file automaticaly created by prof_gen.py script """ self["ID"] = "../profile-datasets-py/div83/077.py" self["Q"] = numpy.array([ 3.01408100e+00, 3.40341800e+00, 3.94918400e+00, 4.08209300e+00, 4.65722800e+00, 5.59385900e+00, 5.96882400e+00, 5.96578400e+00, 6.02361400e+00, 6.13266200e+00, 5.61561800e+00, 5.17541300e+00, 4.73120800e+00, 4.38244100e+00, 4.13858300e+00, 3.94732400e+00, 3.82339500e+00, 3.74146600e+00, 3.68389600e+00, 3.64322700e+00, 3.61384700e+00, 3.58783700e+00, 3.57544700e+00, 3.57424700e+00, 3.57814700e+00, 3.57652700e+00, 3.56295700e+00, 3.53513800e+00, 3.51090800e+00, 3.50409800e+00, 3.51977800e+00, 3.54417700e+00, 3.53987700e+00, 3.51452800e+00, 3.48830800e+00, 3.47651800e+00, 3.48119800e+00, 3.49274800e+00, 3.50137800e+00, 3.50850800e+00, 3.52815800e+00, 3.56910700e+00, 3.61097700e+00, 3.71830600e+00, 3.89014500e+00, 3.89370500e+00, 3.85655500e+00, 3.87925500e+00, 3.95365400e+00, 4.00917400e+00, 4.16308300e+00, 4.52899900e+00, 5.18923300e+00, 6.26899100e+00, 7.92153700e+00, 1.00846000e+01, 1.24507400e+01, 1.47046800e+01, 1.67259200e+01, 1.84705600e+01, 1.96999100e+01, 2.08678600e+01, 2.23955000e+01, 2.44190000e+01, 2.71340600e+01, 3.11191300e+01, 3.80605500e+01, 4.93422700e+01, 7.03837500e+01, 1.05079000e+02, 1.47056400e+02, 1.80304500e+02, 2.22368500e+02, 2.73803000e+02, 3.33293900e+02, 4.05331600e+02, 4.94623200e+02, 6.04438400e+02, 7.36045800e+02, 8.86931700e+02, 1.05317000e+03, 1.23561100e+03, 1.43888700e+03, 1.66709600e+03, 1.91848200e+03, 2.17581600e+03, 2.42905500e+03, 2.65031700e+03, 2.83038600e+03, 2.95328200e+03, 2.87015800e+03, 2.97041000e+03, 3.22605900e+03, 3.13244700e+03, 3.04276300e+03, 2.95681100e+03, 2.87439400e+03, 2.79532400e+03, 2.71943500e+03, 2.64656700e+03, 2.57657400e+03]) self["P"] = numpy.array([ 5.00000000e-03, 1.61000000e-02, 3.84000000e-02, 7.69000000e-02, 1.37000000e-01, 2.24400000e-01, 3.45400000e-01, 5.06400000e-01, 7.14000000e-01, 9.75300000e-01, 1.29720000e+00, 1.68720000e+00, 2.15260000e+00, 2.70090000e+00, 3.33980000e+00, 4.07700000e+00, 4.92040000e+00, 5.87760000e+00, 6.95670000e+00, 8.16550000e+00, 9.51190000e+00, 1.10038000e+01, 1.26492000e+01, 1.44559000e+01, 1.64318000e+01, 1.85847000e+01, 2.09224000e+01, 2.34526000e+01, 2.61829000e+01, 2.91210000e+01, 3.22744000e+01, 3.56505000e+01, 3.92566000e+01, 4.31001000e+01, 4.71882000e+01, 5.15278000e+01, 5.61260000e+01, 6.09895000e+01, 6.61253000e+01, 7.15398000e+01, 7.72396000e+01, 8.32310000e+01, 8.95204000e+01, 9.61138000e+01, 1.03017000e+02, 1.10237000e+02, 1.17778000e+02, 1.25646000e+02, 1.33846000e+02, 1.42385000e+02, 1.51266000e+02, 1.60496000e+02, 1.70078000e+02, 1.80018000e+02, 1.90320000e+02, 2.00989000e+02, 2.12028000e+02, 2.23442000e+02, 2.35234000e+02, 2.47408000e+02, 2.59969000e+02, 2.72919000e+02, 2.86262000e+02, 3.00000000e+02, 3.14137000e+02, 3.28675000e+02, 3.43618000e+02, 3.58966000e+02, 3.74724000e+02, 3.90893000e+02, 4.07474000e+02, 4.24470000e+02, 4.41882000e+02, 4.59712000e+02, 4.77961000e+02, 4.96630000e+02, 5.15720000e+02, 5.35232000e+02, 5.55167000e+02, 5.75525000e+02, 5.96306000e+02, 6.17511000e+02, 6.39140000e+02, 6.61192000e+02, 6.83667000e+02, 7.06565000e+02, 7.29886000e+02, 7.53628000e+02, 7.77790000e+02, 8.02371000e+02, 8.27371000e+02, 8.52788000e+02, 8.78620000e+02, 9.04866000e+02, 9.31524000e+02, 9.58591000e+02, 9.86067000e+02, 1.01395000e+03, 1.04223000e+03, 1.07092000e+03, 1.10000000e+03]) self["CO2"] = numpy.array([ 376.9289, 376.9267, 376.9235, 376.9185, 376.9102, 376.8979, 376.8878, 376.8858, 376.8987, 376.9157, 376.9379, 376.967 , 377.0032, 377.0483, 377.0994, 377.1415, 377.1806, 377.2196, 377.2566, 377.2936, 377.3406, 377.4116, 377.4967, 377.5807, 377.6576, 377.7326, 377.7957, 377.8617, 377.9087, 377.9647, 378.0677, 378.1777, 378.3247, 378.4827, 378.5467, 378.5667, 378.6177, 378.7377, 378.8647, 379.1987, 379.5707, 379.8876, 380.1336, 380.3936, 380.7865, 381.1975, 381.5395, 381.8335, 382.1145, 382.2825, 382.4564, 382.5853, 382.705 , 382.8186, 382.922 , 383.0401, 383.2172, 383.4014, 383.6806, 383.9769, 384.2704, 384.569 , 384.8374, 385.0826, 385.3235, 385.554 , 385.7733, 385.971 , 386.1468, 386.2794, 386.3942, 386.4873, 386.57 , 386.6411, 386.7101, 386.7782, 386.8426, 386.902 , 386.948 , 386.9845, 387.009 , 387.0222, 387.0443, 387.0946, 387.2027, 387.3873, 387.5952, 387.7785, 388.0156, 388.3936, 388.8278, 389.5115, 390.0167, 390.5358, 390.9229, 391.1729, 391.2791, 391.3101, 391.3399, 391.3685, 391.3959]) self["CO"] = numpy.array([ 0.4988025 , 0.4837694 , 0.4549212 , 0.4091083 , 0.3466384 , 0.2724125 , 0.2529705 , 0.3556049 , 0.3436299 , 0.3118041 , 0.2360657 , 0.1332083 , 0.06529029, 0.04917818, 0.04630671, 0.04344553, 0.04531133, 0.04861692, 0.05090421, 0.05133911, 0.05167021, 0.04959452, 0.04651663, 0.04325405, 0.04006766, 0.03693337, 0.03511297, 0.03345558, 0.03285768, 0.03228319, 0.03236039, 0.03244319, 0.03296888, 0.03355668, 0.03477178, 0.03638897, 0.03844617, 0.04135936, 0.04467554, 0.05192792, 0.06128788, 0.07390404, 0.09132347, 0.1136636 , 0.1258555 , 0.1400065 , 0.1455584 , 0.1438834 , 0.1412344 , 0.1340595 , 0.1269835 , 0.1253564 , 0.1252244 , 0.1268982 , 0.131127 , 0.1360076 , 0.1437272 , 0.1521708 , 0.1615463 , 0.1718538 , 0.1819464 , 0.192305 , 0.2043344 , 0.2183397 , 0.2317967 , 0.2427394 , 0.2529074 , 0.2590382 , 0.2647594 , 0.2679568 , 0.2707162 , 0.2713961 , 0.2720315 , 0.2725024 , 0.2734588 , 0.2752834 , 0.2772678 , 0.279404 , 0.2813058 , 0.2830447 , 0.2835061 , 0.2839138 , 0.2842594 , 0.2847725 , 0.2852078 , 0.2855673 , 0.2859427 , 0.2860628 , 0.2855026 , 0.2845641 , 0.2836705 , 0.2825133 , 0.28085 , 0.2789235 , 0.2766895 , 0.2739117 , 0.2711194 , 0.2683139 , 0.265496 , 0.262667 , 0.2598288 ]) self["T"] = numpy.array([ 197.478, 204.431, 217.518, 232.024, 240.06 , 241.488, 237.615, 229.648, 222.059, 220.002, 221.016, 222.004, 224.079, 226.704, 229.151, 230.726, 232.026, 233.278, 234.389, 235.37 , 236.325, 237.27 , 238.285, 239.125, 239.562, 239.408, 239.074, 238.623, 237.788, 236.618, 235.366, 234.287, 233.649, 232.492, 231.082, 230.178, 230.011, 230.065, 229.721, 228.916, 227.9 , 226.942, 226.202, 225.266, 224.187, 223.613, 222.971, 222.094, 221.208, 220.74 , 220.537, 220.284, 219.887, 219.382, 218.843, 218.328, 217.832, 217.287, 216.618, 215.885, 215.461, 215.505, 215.981, 216.806, 217.881, 219.112, 220.38 , 221.707, 223.156, 224.773, 226.616, 228.678, 230.824, 232.99 , 235.092, 237.21 , 239.397, 241.632, 243.87 , 246.04 , 248.097, 250.061, 251.959, 253.803, 255.582, 257.221, 258.709, 259.968, 261.008, 261.803, 262.785, 263.963, 265.207, 265.207, 265.207, 265.207, 265.207, 265.207, 265.207, 265.207, 265.207]) self["N2O"] = numpy.array([ 0.00386999, 0.00306999, 0.00246999, 0.00239999, 0.00190999, 0.00132999, 0.00145999, 0.00159999, 0.00196999, 0.00296998, 0.00447997, 0.00696996, 0.01015995, 0.01528993, 0.02053991, 0.02663989, 0.03359987, 0.04270984, 0.05238981, 0.06860975, 0.0840797 , 0.1006696 , 0.1174596 , 0.1335495 , 0.1466895 , 0.1590294 , 0.1708994 , 0.1853993 , 0.2003893 , 0.2148792 , 0.2275592 , 0.2346592 , 0.2415291 , 0.2481891 , 0.2543991 , 0.2593091 , 0.2640791 , 0.2687091 , 0.272769 , 0.276369 , 0.279779 , 0.282829 , 0.285849 , 0.2887289 , 0.2917289 , 0.2947289 , 0.2977089 , 0.3006588 , 0.3035488 , 0.3063688 , 0.3090987 , 0.3116986 , 0.3141584 , 0.316448 , 0.3185375 , 0.3203968 , 0.321996 , 0.3226453 , 0.3232446 , 0.323774 , 0.3242236 , 0.3245932 , 0.3248727 , 0.3250421 , 0.3251012 , 0.3250999 , 0.3250976 , 0.325094 , 0.3250871 , 0.3250758 , 0.3250622 , 0.3250514 , 0.3250377 , 0.325021 , 0.3250016 , 0.3249782 , 0.3249492 , 0.3249135 , 0.3248707 , 0.3248216 , 0.3247676 , 0.3247083 , 0.3246422 , 0.324568 , 0.3244863 , 0.3244026 , 0.3243203 , 0.3242484 , 0.3241898 , 0.3241499 , 0.3241769 , 0.3241443 , 0.3240612 , 0.3240916 , 0.3241208 , 0.3241487 , 0.3241755 , 0.3242012 , 0.3242259 , 0.3242496 , 0.3242723 ]) self["O3"] = numpy.array([ 0.4650166 , 0.3722967 , 0.25801 , 0.3565255 , 0.5657804 , 0.8310854 , 1.275442 , 1.941668 , 2.751043 , 3.509408 , 4.226426 , 4.982314 , 5.571684 , 5.950054 , 6.172944 , 6.354005 , 6.459525 , 6.548995 , 6.644776 , 6.735845 , 6.790695 , 6.827586 , 6.854715 , 6.862505 , 6.844556 , 6.799816 , 6.769176 , 6.719646 , 6.545257 , 6.195258 , 5.70893 , 5.274831 , 4.976922 , 4.668544 , 4.294395 , 3.893666 , 3.566958 , 3.348398 , 3.139029 , 2.84919 , 2.451261 , 2.077143 , 1.888043 , 1.731914 , 1.409245 , 1.303475 , 1.292365 , 1.148696 , 0.9682352 , 0.8581456 , 0.728699 , 0.5758034 , 0.4443007 , 0.3535498 , 0.2938877 , 0.2527305 , 0.2229512 , 0.1999561 , 0.178937 , 0.1568281 , 0.1353713 , 0.1190565 , 0.1065156 , 0.09549277, 0.08532788, 0.07889094, 0.07722016, 0.07431793, 0.06841198, 0.05924887, 0.04912847, 0.04243675, 0.03862361, 0.03721341, 0.03721039, 0.03694232, 0.03630673, 0.03556769, 0.03509875, 0.03521114, 0.03578028, 0.03636931, 0.03676782, 0.03692234, 0.03683649, 0.03651109, 0.03619457, 0.03624089, 0.03710717, 0.03880576, 0.04014684, 0.03936333, 0.03682412, 0.03682758, 0.03683089, 0.03683407, 0.03683711, 0.03684003, 0.03684284, 0.03684553, 0.03684811]) self["CH4"] = numpy.array([ 0.3005231, 0.2351152, 0.1864963, 0.1572414, 0.1760812, 0.1975499, 0.2255547, 0.2531465, 0.2866593, 0.31921 , 0.3721429, 0.4494437, 0.5428354, 0.6650551, 0.7814038, 0.8957425, 0.9909472, 1.054496 , 1.115956 , 1.182386 , 1.245675 , 1.300155 , 1.349285 , 1.396355 , 1.424055 , 1.448405 , 1.471845 , 1.501435 , 1.532305 , 1.537285 , 1.542625 , 1.548345 , 1.554454 , 1.551955 , 1.549555 , 1.547285 , 1.545195 , 1.543345 , 1.549515 , 1.556025 , 1.562874 , 1.570084 , 1.577644 , 1.617574 , 1.657994 , 1.700273 , 1.730303 , 1.751553 , 1.771163 , 1.779313 , 1.787803 , 1.793322 , 1.798201 , 1.802289 , 1.805406 , 1.808492 , 1.811087 , 1.813773 , 1.81631 , 1.818906 , 1.821484 , 1.824092 , 1.826669 , 1.829225 , 1.83172 , 1.834133 , 1.83637 , 1.838309 , 1.84005 , 1.841406 , 1.842689 , 1.843857 , 1.84505 , 1.846294 , 1.847644 , 1.84909 , 1.850584 , 1.85209 , 1.853525 , 1.854883 , 1.856113 , 1.857182 , 1.858302 , 1.859615 , 1.861771 , 1.864195 , 1.866575 , 1.868445 , 1.869743 , 1.871178 , 1.873019 , 1.875702 , 1.877623 , 1.879713 , 1.881288 , 1.882308 , 1.882753 , 1.882902 , 1.883045 , 1.883183 , 1.883315 ]) self["CTP"] = 500.0 self["CFRACTION"] = 0.0 self["IDG"] = 0 self["ISH"] = 0 self["ELEVATION"] = 0.0 self["S2M"]["T"] = 265.207 self["S2M"]["Q"] = 2576.57411645 self["S2M"]["O"] = 0.0368481128494 self["S2M"]["P"] = 876.30151 self["S2M"]["U"] = 0.0 self["S2M"]["V"] = 0.0 self["S2M"]["WFETC"] = 100000.0 self["SKIN"]["SURFTYPE"] = 0 self["SKIN"]["WATERTYPE"] = 1 self["SKIN"]["T"] = 265.207 self["SKIN"]["SALINITY"] = 35.0 self["SKIN"]["FOAM_FRACTION"] = 0.0 self["SKIN"]["FASTEM"] = numpy.array([ 3. , 5. , 15. , 0.1, 0.3]) self["ZENANGLE"] = 0.0 self["AZANGLE"] = 0.0 self["SUNZENANGLE"] = 0.0 self["SUNAZANGLE"] = 0.0 self["LATITUDE"] = 60.824 self["GAS_UNITS"] = 2 self["BE"] = 0.0 self["COSBK"] = 0.0 self["DATE"] = numpy.array([2006, 12, 10]) self["TIME"] = numpy.array([0, 0, 0])
[ 37811, 198, 220, 220, 220, 13118, 11485, 14, 13317, 12, 19608, 292, 1039, 12, 9078, 14, 7146, 5999, 14, 2998, 22, 13, 9078, 198, 220, 220, 220, 220, 220, 220, 220, 2393, 3557, 39056, 88, 2727, 416, 1534, 62, 5235, 13, 9078, 4226, ...
1.63417
8,165
#!/usr/bin/python import fnmatch import logging sflow_sub_database=[]
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 11748, 24714, 15699, 198, 11748, 18931, 198, 198, 82, 11125, 62, 7266, 62, 48806, 28, 21737, 220, 198 ]
2.769231
26
""" A script to run XFaster for gcorr calculation. Called by iterate.py. """ import os import xfaster as xf import argparse as ap from configparser import ConfigParser # Change XFaster options here to suit your purposes opts = dict( likelihood=False, residual_fit=False, foreground_fit=False, # change options below for your purposes tbeb=True, bin_width=25, lmin=2, lmax=500, ) # Change submit options here to fit your system submit_opts = dict(nodes=1, ppn=1, mem=6, omp_threads=10, wallt=4) P = ap.ArgumentParser() P.add_argument("--gcorr-config", help="The config file for gcorr computation") P.add_argument("-f", "--first", default=0, type=int, help="First sim index to run") P.add_argument("-n", "--num", default=1, type=int, help="Number of sims to run") P.add_argument( "-o", "--output", default="xfaster_gcal", help="Name of output subdirectory" ) P.add_argument( "--no-gcorr", dest="gcorr", default=True, action="store_false", help="Don't apply a g-gcorrection", ) P.add_argument( "--reload-gcorr", default=False, action="store_true", help="Reload the gcorr factor" ) P.add_argument("--check-point", default="bandpowers", help="XFaster checkpoint") P.add_argument( "--no-submit", dest="submit", action="store_false", help="Don't submit, run locally" ) P.add_argument( "--omp", default=None, type=int, help="Number of omp threads, if submit. Overwrites value in config file", ) args = P.parse_args() # start by loading up gcorr config file and parsing it assert os.path.exists(args.gcorr_config), "Missing config file {}".format( args.gcorr_config ) g_cfg = ConfigParser() g_cfg.read(args.gcorr_config) # set all user-specific xfaster opts for k, v in g_cfg["xfaster_opts"].items(): opts[k] = v null = g_cfg.getboolean("gcorr_opts", "null") tags = g_cfg["gcorr_opts"]["map_tags"].split(",") # null tests should use noise sims. signal shouldn't. if null: opts["noise_type"] = g_cfg["xfaster_opts"]["noise_type"] opts["sim_data_components"] = ["signal", "noise"] else: opts["noise_type"] = None opts["sim_data_components"] = ["signal"] opts["output_root"] = os.path.join(g_cfg["gcorr_opts"]["output_root"], args.output) # update opts with command line args opts["apply_gcorr"] = args.gcorr opts["reload_gcorr"] = args.reload_gcorr opts["checkpoint"] = args.check_point seeds = list(range(args.first, args.first + args.num)) for tag in tags: opts["sim_data"] = True opts["output_tag"] = tag opts["gcorr_file"] = os.path.abspath( os.path.join( g_cfg["gcorr_opts"]["output_root"], "xfaster_gcal", tag, "gcorr_{}_total.npz".format(tag), ) ) opts["data_subset"] = os.path.join( g_cfg["gcorr_opts"]["data_subset"], "*{}".format(tag) ) if args.omp is not None: submit_opts["omp_threads"] = args.omp if args.submit: opts.update(**submit_opts) for s in seeds: opts["sim_index_default"] = s if args.submit: xf.xfaster_submit(**opts) else: xf.xfaster_run(**opts)
[ 37811, 198, 32, 4226, 284, 1057, 1395, 37, 1603, 329, 308, 10215, 81, 17952, 13, 34099, 416, 11629, 378, 13, 9078, 13, 198, 37811, 198, 11748, 28686, 198, 11748, 2124, 69, 1603, 355, 2124, 69, 198, 11748, 1822, 29572, 355, 2471, 198, ...
2.344006
1,343
import unittest from src.examples.c_decisions.decisions import is_letter_consonant, logical_op_precedence, num_is_not_in_range_or, number_is_in_range_and, test_config from src.examples.c_decisions.decisions import get_letter_grade from src.examples.c_decisions.decisions import logical_op_precedence from src.examples.c_decisions.decisions import number_is_not_in_range
[ 11748, 555, 715, 395, 198, 198, 6738, 12351, 13, 1069, 12629, 13, 66, 62, 12501, 3279, 13, 12501, 3279, 1330, 318, 62, 9291, 62, 5936, 261, 415, 11, 12219, 62, 404, 62, 3866, 771, 594, 11, 997, 62, 271, 62, 1662, 62, 259, 62, 95...
2.913386
127
from .client import MQTT_Client
[ 6738, 764, 16366, 1330, 337, 48, 15751, 62, 11792, 198 ]
3.2
10
# 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. """ Support for server files. """ from __future__ import absolute_import, print_function import os import yaml import jsonschema from ._server import Server from ._vault_file import VaultFile __all__ = ['ServerFile', 'ServerFileException', 'ServerFileOpenError', 'ServerFileFormatError', 'ServerFileUserDefinedFormatError', 'ServerFileUserDefinedSchemaError', 'ServerFileGroupUserDefinedFormatError', 'ServerFileGroupUserDefinedSchemaError'] # JSON schema describing the structure of the server files SERVER_FILE_SCHEMA = { "$schema": "http://json-schema.org/draft-07/schema#", "title": "JSON schema for easy-server server files", "definitions": {}, "type": "object", "required": [ "servers", ], "additionalProperties": False, "properties": { "vault_file": { "type": "string", "description": "Path name of vault file. Relative path names are relative to " "the directory of the server file", }, "servers": { "type": "object", "description": "The servers in the server file", "additionalProperties": False, "patternProperties": { "^[a-zA-Z0-9_]+$": { "type": "object", "description": "Nickname of the server", "required": [ "description", ], "additionalProperties": False, "properties": { "description": { "type": "string", "description": "Short description of the server", }, "contact_name": { "type": "string", "description": "Name of technical contact for the server", }, "access_via": { "type": "string", "description": "Short reminder on the " "network/firewall/proxy/vpn used to access the " "server", }, "user_defined": { "type": "object", "description": "User-defined properties of the server. " "This object can have an arbitrary " "user-defined structure", }, }, }, }, }, "server_groups": { "type": "object", "description": "The server groups in the server file", "additionalProperties": False, "patternProperties": { "^[a-zA-Z0-9_]+$": { "type": "object", "description": "Nickname of the server group", "required": [ "description", "members", ], "additionalProperties": False, "properties": { "description": { "type": "string", "description": "Short description of the server group", }, "members": { "type": "array", "description": "List of members of the server group. " "Those can be servers or other server groups.", "items": { "type": "string", "description": "Nickname of server or server group in " "this file", }, }, "user_defined": { "type": "object", "description": "User-defined properties of the server group. " "This object can have an arbitrary " "user-defined structure", }, }, }, }, }, "default": { "type": "string", "description": "Nickname of default server or server group", }, }, } def get_server(self, nickname): """ Get server for a given server nickname. Parameters: nickname (:term:`unicode string`): Server nickname. Returns: :class:`~easy_server.Server`: Server with the specified nickname. Raises: :exc:`py:KeyError`: Nickname not found """ try: server_dict = self._servers[nickname] except KeyError: new_exc = KeyError( "Server with nickname {!r} not found in server " "file {!r}". format(nickname, self._filepath)) new_exc.__cause__ = None raise new_exc # KeyError if self._vault: try: secrets_dict = self._vault.get_secrets(nickname) except KeyError: secrets_dict = None else: secrets_dict = None return Server(nickname, server_dict, secrets_dict) def list_servers(self, nickname): """ List the servers for a given server or server group nickname. Parameters: nickname (:term:`unicode string`): Server or server group nickname. Returns: list of :class:`~easy_server.Server`: List of servers. Raises: :exc:`py:KeyError`: Nickname not found """ if nickname in self._servers: return [self.get_server(nickname)] if nickname in self._server_groups: sd_list = list() # of Server objects sd_nick_list = list() # of server nicknames sg_item = self._server_groups[nickname] for member_nick in sg_item['members']: member_sds = self.list_servers(member_nick) for sd in member_sds: if sd.nickname not in sd_nick_list: sd_nick_list.append(sd.nickname) sd_list.append(sd) return sd_list raise KeyError( "Server or server group with nickname {!r} not found in server " "definition file {!r}". format(nickname, self._filepath)) def list_default_servers(self): """ List the servers for the default server or group. An omitted 'default' element in the server file results in an empty list. Returns: list of :class:`~easy_server.Server`: List of servers. """ if self._default is None: return [] return self.list_servers(self._default) def list_all_servers(self): """ List all servers. Returns: list of :class:`~easy_server.Server`: List of servers. """ return [self.get_server(nickname) for nickname in self._servers] def _load_server_file( filepath, user_defined_schema=None, group_user_defined_schema=None): """ Load the server file, validate its format and default some optional elements. Returns: dict: Python dict representing the file content. Raises: ServerFileOpenError: Error opening server file ServerFileFormatError: Invalid server file content ServerFileUserDefinedFormatError: Invalid format of user-defined portion of server items in the server file ServerFileUserDefinedSchemaError: Invalid JSON schema for validating user-defined portion of server items in the server file ServerFileGroupUserDefinedFormatError: Invalid format of user-defined portion of group items in the server file ServerFileGroupUserDefinedSchemaError: Invalid JSON schema for validating user-defined portion of group items in the server file """ # Load the server file (YAML) try: with open(filepath, 'r') as fp: data = yaml.safe_load(fp) except (OSError, IOError) as exc: new_exc = ServerFileOpenError( "Cannot open server file: {fn}: {exc}". format(fn=filepath, exc=exc)) new_exc.__cause__ = None raise new_exc # ServerFileOpenError except yaml.YAMLError as exc: new_exc = ServerFileFormatError( "Invalid YAML syntax in server file {fn}: {exc}". format(fn=filepath, exc=exc)) new_exc.__cause__ = None raise new_exc # ServerFileFormatError # Schema validation of server file content try: jsonschema.validate(data, SERVER_FILE_SCHEMA) # Raises jsonschema.exceptions.SchemaError if JSON schema is invalid except jsonschema.exceptions.ValidationError as exc: if exc.absolute_path: elem_str = "element '{}'". \ format('.'.join(str(e) for e in exc.absolute_path)) else: elem_str = 'top-level element' new_exc = ServerFileFormatError( "Invalid format in server file {fn}: Validation " "failed on {elem}: {exc}". format(fn=filepath, elem=elem_str, exc=exc)) new_exc.__cause__ = None raise new_exc # ServerFileFormatError # Establish defaults for optional top-level elements if 'server_groups' not in data: data['server_groups'] = {} if 'default' not in data: data['default'] = None if 'vault_file' not in data: data['vault_file'] = None # Schema validation of user-defined portion of server items if user_defined_schema: for server_nick, server_item in data['servers'].items(): user_defined = server_item.get('user_defined', None) if user_defined is None: new_exc = ServerFileUserDefinedFormatError( "Missing user_defined element for server {srv} " "in server file {fn}". format(srv=server_nick, fn=filepath)) new_exc.__cause__ = None raise new_exc # ServerFileUserDefinedFormatError try: jsonschema.validate(user_defined, user_defined_schema) except jsonschema.exceptions.SchemaError as exc: new_exc = ServerFileUserDefinedSchemaError( "Invalid JSON schema for validating user-defined portion " "of server items in server file: {exc}". format(exc=exc)) new_exc.__cause__ = None raise new_exc # ServerFileUserDefinedSchemaError except jsonschema.exceptions.ValidationError as exc: if exc.absolute_path: elem_str = "element '{}'". \ format('.'.join(str(e) for e in exc.absolute_path)) else: elem_str = "top-level of user-defined item" new_exc = ServerFileUserDefinedFormatError( "Invalid format in user-defined portion of item for " "server {srv} in server file {fn}: " "Validation failed on {elem}: {exc}". format(srv=server_nick, fn=filepath, elem=elem_str, exc=exc)) new_exc.__cause__ = None raise new_exc # ServerFileUserDefinedFormatError # Schema validation of user-defined portion of group items if group_user_defined_schema: for group_nick, group_item in data['server_groups'].items(): user_defined = group_item.get('user_defined', None) if user_defined is None: new_exc = ServerFileGroupUserDefinedFormatError( "Missing user_defined element for group {grp} " "in server file {fn}". format(grp=group_nick, fn=filepath)) new_exc.__cause__ = None raise new_exc # ServerFileGroupUserDefinedFormatError try: jsonschema.validate(user_defined, group_user_defined_schema) except jsonschema.exceptions.SchemaError as exc: new_exc = ServerFileGroupUserDefinedSchemaError( "Invalid JSON schema for validating user-defined portion " "of group items in server file: {exc}". format(exc=exc)) new_exc.__cause__ = None raise new_exc # ServerFileGroupUserDefinedSchemaError except jsonschema.exceptions.ValidationError as exc: if exc.absolute_path: elem_str = "element '{}'". \ format('.'.join(str(e) for e in exc.absolute_path)) else: elem_str = "top-level of user-defined item" new_exc = ServerFileGroupUserDefinedFormatError( "Invalid format in user-defined portion of item for " "group {grp} in server file {fn}: " "Validation failed on {elem}: {exc}". format(grp=group_nick, fn=filepath, elem=elem_str, exc=exc)) new_exc.__cause__ = None raise new_exc # ServerFileGroupUserDefinedFormatError # Check dependencies in the file server_nicks = list(data['servers'].keys()) group_nicks = list(data['server_groups'].keys()) all_nicks = server_nicks + group_nicks default_nick = data['default'] if default_nick and default_nick not in all_nicks: new_exc = ServerFileFormatError( "Default nickname '{n}' not found in servers or groups in " "server file {fn}". format(n=default_nick, fn=filepath)) new_exc.__cause__ = None raise new_exc # ServerFileFormatError for group_nick in group_nicks: sg_item = data['server_groups'][group_nick] for member_nick in sg_item['members']: if member_nick not in all_nicks: new_exc = ServerFileFormatError( "Nickname '{n}' in server group '{g}' not found in " "servers or groups in server file {fn}". format(n=member_nick, g=group_nick, fn=filepath)) new_exc.__cause__ = None raise new_exc # ServerFileFormatError return data
[ 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, 257, 4866, 286, 262, 13789, 379, 198, 2,...
1.989873
7,801
from mezzanine.conf import register_setting register_setting( name="PAGEDOWN_SERVER_SIDE_PREVIEW", description="Render previews on the server using the same " "converter that generates the actual pages.", editable=False, default=False, ) register_setting( name="PAGEDOWN_MARKDOWN_EXTENSIONS", description="A tuple specifying enabled python-markdown extensions.", editable=False, default=(), )
[ 6738, 502, 3019, 272, 500, 13, 10414, 1330, 7881, 62, 33990, 628, 198, 30238, 62, 33990, 7, 198, 220, 220, 220, 1438, 2625, 4537, 38, 1961, 14165, 62, 35009, 5959, 62, 50, 14114, 62, 46437, 28206, 1600, 198, 220, 220, 220, 6764, 262...
2.828025
157
""" --- Day 5: Hydrothermal Venture --- You come across a field of hydrothermal vents on the ocean floor! These vents constantly produce large, opaque clouds, so it would be best to avoid them if possible. They tend to form in lines; the submarine helpfully produces a list of nearby lines of vents (your puzzle input) for you to review. For example: 0,9 -> 5,9 8,0 -> 0,8 9,4 -> 3,4 2,2 -> 2,1 7,0 -> 7,4 6,4 -> 2,0 0,9 -> 2,9 3,4 -> 1,4 0,0 -> 8,8 5,5 -> 8,2 Each line of vents is given as a line segment in the format x1,y1 -> x2,y2 where x1,y1 are the coordinates of one end the line segment and x2,y2 are the coordinates of the other end. These line segments include the points at both ends. In other words: An entry like 1,1 -> 1,3 covers points 1,1, 1,2, and 1,3. An entry like 9,7 -> 7,7 covers points 9,7, 8,7, and 7,7. For now, only consider horizontal and vertical lines: lines where either x1 = x2 or y1 = y2. So, the horizontal and vertical lines from the above list would produce the following diagram: .......1.. ..1....1.. ..1....1.. .......1.. .112111211 .......... .......... .......... .......... 222111.... In this diagram, the top left corner is 0,0 and the bottom right corner is 9,9. Each position is shown as the number of lines which cover that point or . if no line covers that point. The top-left pair of 1s, for example, comes from 2,2 -> 2,1; the very bottom row is formed by the overlapping lines 0,9 -> 5,9 and 0,9 -> 2,9. To avoid the most dangerous areas, you need to determine the number of points where at least two lines overlap. In the above example, this is anywhere in the diagram with a 2 or larger - a total of 5 points. Consider only horizontal and vertical lines. At how many points do at least two lines overlap? --- Part Two --- Unfortunately, considering only horizontal and vertical lines doesn't give you the full picture; you need to also consider diagonal lines. Because of the limits of the hydrothermal vent mapping system, the lines in your list will only ever be horizontal, vertical, or a diagonal line at exactly 45 degrees. In other words: An entry like 1,1 -> 3,3 covers points 1,1, 2,2, and 3,3. An entry like 9,7 -> 7,9 covers points 9,7, 8,8, and 7,9. Considering all lines from the above example would now produce the following diagram: 1.1....11. .111...2.. ..2.1.111. ...1.2.2.. .112313211 ...1.2.... ..1...1... .1.....1.. 1.......1. 222111.... You still need to determine the number of points where at least two lines overlap. In the above example, this is still anywhere in the diagram with a 2 or larger - now a total of 12 points. Consider all of the lines. At how many points do at least two lines overlap? """ import numpy as np if __name__ == "__main__": with open("solutions/2021/day5/input.txt", "r") as f: lines = [Line.from_puzzle_input(line) for line in f.readlines()] straight_field = np.zeros((1000, 1000), dtype=int) diagonal_field = straight_field.copy() for line in lines: field_index = (slice(line.ymin, line.ymax + 1), slice(line.xmin, line.xmax + 1)) if line.x1 == line.x2 or line.y1 == line.y2: straight_field[field_index] += 1 else: is_identity = (line.x2 - line.x1 > 0) == (line.y2 - line.y1 > 0) diag_slice = slice(None, None, None if is_identity else -1) diagonal_field[field_index] += np.diag(np.ones((line.xmax - line.xmin + 1), dtype=int))[diag_slice] field = straight_field + diagonal_field print(f"Answer 1: {np.sum(straight_field > 1)}") print(f"Answer 2: {np.sum(field > 1)}")
[ 37811, 198, 6329, 3596, 642, 25, 32116, 490, 7617, 35686, 11420, 198, 198, 1639, 1282, 1973, 257, 2214, 286, 17173, 490, 7617, 42777, 319, 262, 9151, 4314, 0, 2312, 42777, 7558, 4439, 198, 11664, 11, 32191, 15114, 11, 523, 340, 561, 3...
2.91942
1,241
from typing import Callable tests = [ ( ([4, 2, 5, 7],), [4, 5, 2, 7], ), ( ([2, 3],), [2, 3], ), ( ([2, 3, 1, 1, 4, 0, 0, 4, 3, 3],), [2, 3, 4, 1, 4, 3, 0, 1, 0, 3], ), ]
[ 6738, 19720, 1330, 4889, 540, 628, 198, 198, 41989, 796, 685, 198, 220, 220, 220, 357, 198, 220, 220, 220, 220, 220, 220, 220, 29565, 19, 11, 362, 11, 642, 11, 767, 4357, 828, 198, 220, 220, 220, 220, 220, 220, 220, 685, 19, 11,...
1.50303
165
from flask_sqlalchemy import SQLAlchemy # Initialize the Flask-SQLAlchemy extension instance db = SQLAlchemy()
[ 6738, 42903, 62, 25410, 282, 26599, 1330, 16363, 2348, 26599, 198, 198, 2, 20768, 1096, 262, 46947, 12, 17861, 2348, 26599, 7552, 4554, 198, 9945, 796, 16363, 2348, 26599, 3419, 198 ]
3.612903
31
import re UNITS_XML_FILE = 'poscUnits22.xml' UNITS_PICKLE_FILE = 'units.pickle' OUTPUT_DECIMALS = 6 SOURCE_PATTERN = r'^(?P<quantity>.*[\d.]+)\s*(?P<from>[^\d\s]([^\s]*|.+?))' SOURCE_RE = re.compile(SOURCE_PATTERN + '$', re.IGNORECASE | re.VERBOSE) FULL_PATTERN = r'(\s+as|\s+to|\s+in|\s*>|\s*=)\s(?P<to>[^\d\s][^\s]*)$' FULL_RE = re.compile(SOURCE_PATTERN + FULL_PATTERN + '$', re.IGNORECASE | re.VERBOSE) ICONS = { 'length': 'scale6.png', 'height': 'scale6.png', 'distance': 'scale6.png', 'area': 'scaling1.png', 'time': 'round27.png', 'thermodynamic temperature': 'thermometer19.png', 'volume': 'measuring3.png', 'mass': 'weight4.png', 'velocity': 'timer18.png', 'level of power intensity': 'treble2.png', 'digital storage': 'binary9.png', } DEFAULT_ICON = 'ruler9.png' ANNOTATION_REPLACEMENTS = { 'litre': ('liter', 'liters', 'l'), 'metre': ('meter', 'm'), 'm2': ('meter^3',), 'dm': ('decimeter',), 'dm2': ('dm^2', 'decimeter^2',), 'dm3': ('dm^3', 'decimeter^3',), 'cm': ('centimeter',), 'cm2': ('cm^2', 'centimeter^2',), 'cm3': ('cm^3', 'centimeter^3',), 'mm': ('milimeter',), 'mm2': ('mm^2', 'milimeter^2'), 'mm3': ('mm^3', 'milimeter^3'), 'degF': ('f', 'fahrenheit', 'farhenheit', 'farenheit'), 'degC': ('c', 'celsius', 'celcius'), 'byte': ('B', 'bytes',), 'bit': ('b', 'bits',), 'kbyte': ('KB', 'kB', 'kb', 'kilobyte',), 'Mbyte': ('MB', 'megabyte',), 'ozm': ('oz', 'ounce', 'ounces'), 'lbm': ('lb', 'lbs', 'pound', 'pounds'), 'miPh': ('mph',), 'ftPh': ('fps',), 'foot': ("'",), 'square': ('sq',), 'ft2': ('ft^2', 'foot^2'), 'ft3': ('ft^3', 'foot^3'), 'inch': ('inches', '"'), 'inch2': ('inch^2', 'square inch'), 'inch3': ('inch^3', 'cube inch'), 'flozUS': ('flus', 'floz', 'fl', 'fl oz', 'fl oz uk'), 'flozUK': ('fluk', 'fl oz uk', 'fl uk'), } EXPANSIONS = { 'foot': ('feet', 'ft'), 'mili': ('milli',), 'meter': ('metres', 'meter', 'meters'), '^2': ('sq', 'square'), '^3': ('cube', 'cubed'), } for annotation, items in ANNOTATION_REPLACEMENTS.items(): items = set(items) items.add(annotation) for key, expansions in EXPANSIONS.iteritems(): for expansion in expansions: for item in set(items): items.add(item.replace(key, expansion)) ANNOTATION_REPLACEMENTS[annotation] = sorted(items) # Mostly for language specific stuff, defaulting to US for now since I'm not # easily able to detect the language in a fast way from within alfred LOCALIZED_UNITS = ( ('metre', 'meter'), ('litre', 'liter'), ) RIGHT_TRIMABLE_OPERATORS = '/+*- (.^' FUNCTION_ALIASES = { 'deg': 'degrees', 'rad': 'radians', 'ln': 'log', 'arccos': 'acos', 'arcsin': 'asin', 'arctan': 'atan', } FUNCTION_ALIASES_RE = re.compile(r'\b(%s)\(' % '|'.join(FUNCTION_ALIASES)) FOOT_INCH_RE = re.compile(r'''(\d+)'(\d+)"?''') FOOT_INCH_REPLACE = r'(\1*12)+\2 inch' POWER_UNIT_RE = re.compile(r'([a-z])\^([23])\b') POWER_UNIT_REPLACEMENT = r'\g<1>\g<2>' PRE_EVAL_REPLACEMENTS = { '^': '**', } # Known safe math functions MATH_FUNCTIONS = [ # Number theoretic and representation functions 'ceil', 'copysign', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'isinf', 'isnan', 'ldexp', 'modf', 'trunc', # Power and logarithmic functions 'exp', 'expm1', 'log', 'log1p', 'log10', 'pow', 'sqrt', # Trigonometric functions 'acos', 'asin', 'atan', 'atan2', 'cos', 'hypot', 'sin', 'tan', # Angular conversion functions 'degrees', 'radians', # Hyperbolic functions 'acosh', 'asinh', 'atanh', 'cosh', 'sinh', 'tanh', # Special functions 'erf', 'erfc', 'gamma', 'lgamma', # Missing functions won't break anything but won't do anything either 'this_function_definitely_does_not_exist', ]
[ 11748, 302, 198, 198, 4944, 29722, 62, 55, 5805, 62, 25664, 796, 705, 1930, 66, 3118, 896, 1828, 13, 19875, 6, 198, 4944, 29722, 62, 47, 11860, 2538, 62, 25664, 796, 705, 41667, 13, 27729, 293, 6, 198, 198, 2606, 7250, 3843, 62, 4...
2.073108
1,956
print('----- or -----') RetT() or RetF() RetF() or RetT() # print('----- and -----') RetT() and RetF() # RetF() and RetT() # print('----- not -----') print(not True and True) print(False or not True) print(not True == True) #print(True == not True) #SyntaxError: invalid syntax print(True == (not True))
[ 198, 4798, 10786, 30934, 393, 37404, 11537, 198, 9781, 51, 3419, 393, 4990, 37, 3419, 198, 9781, 37, 3419, 393, 4990, 51, 3419, 1303, 198, 198, 4798, 10786, 30934, 290, 37404, 11537, 198, 9781, 51, 3419, 290, 4990, 37, 3419, 1303, 198...
2.842593
108
from enum import Enum from pathlib import Path import click from mbox.click import EnumChoice, ParsedDate, PathParam
[ 6738, 33829, 1330, 2039, 388, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 3904, 198, 198, 6738, 285, 3524, 13, 12976, 1330, 2039, 388, 46770, 11, 23042, 276, 10430, 11, 10644, 22973, 628, 628, 198 ]
3.416667
36
import math import matplotlib.pyplot as plt import json import os import warnings warnings.filterwarnings("ignore") if __name__ == "__main__": plotPBT('/home/kreitnerl/mrs-gan/ray_results/test_feat/')
[ 11748, 10688, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 14601, 198, 40539, 654, 13, 24455, 40539, 654, 7203, 46430, 4943, 198, 198, 361, 11593, 3672, 834, 6624, 366, ...
2.710526
76
import agenda23 agenda23.le('Agenda.txt') while True: opcao = agenda23.menu() if opcao == 0: break elif opcao == 1: agenda23.novo() elif opcao == 2: agenda23.altera() elif opcao == 3: agenda23.apaga() elif opcao == 4: agenda23.lista() elif opcao == 5: agenda23.grava() elif opcao == 6: agenda23.le() elif opcao == 7: agenda23.ordena() else: print('Opo invlida! Digite novamente.')
[ 11748, 8666, 1954, 198, 198, 363, 7438, 1954, 13, 293, 10786, 10262, 7438, 13, 14116, 11537, 198, 4514, 6407, 25, 198, 220, 220, 220, 1034, 66, 5488, 796, 8666, 1954, 13, 26272, 3419, 198, 220, 220, 220, 611, 1034, 66, 5488, 6624, 6...
1.857143
266
try: import os import pkg_resources # part of setuptools __version__ = pkg_resources.get_distribution(os.path.dirname(__file__)).version except: pass from .qualtrics import *
[ 28311, 25, 198, 220, 220, 220, 1330, 28686, 198, 220, 220, 220, 1330, 279, 10025, 62, 37540, 220, 1303, 636, 286, 900, 37623, 10141, 198, 220, 220, 220, 11593, 9641, 834, 796, 279, 10025, 62, 37540, 13, 1136, 62, 17080, 3890, 7, 418...
2.704225
71
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 201, 198, 201, 198 ]
3.083333
12
import time import requests import xml.dom.minidom from lxml import etree from django.shortcuts import render from django.http import HttpResponse from django.contrib import messages from django.core.urlresolvers import reverse_lazy from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.template import RequestContext, loader from .models import Project, Target, Header, Argument, Task, History from django.shortcuts import render, render_to_response, RequestContext, HttpResponseRedirect from .forms import TaskForm, ProjectForm, ArgumentForm, HeaderForm, TargetForm from django.views.generic.edit import FormView from django.db.models import Count from jsonrpc import jsonrpc_method from django.views.generic.edit import CreateView, UpdateView, DeleteView # Create your views here. class ProjectDeleteView(DeleteView): model = Project success_url = reverse_lazy('project-list') class ProjectListView(ListView): model = Project template_name_suffix = '_list' class ProjectCreateView(CreateView): template_name_suffix = '_create' model = Project form_class = ProjectForm class ProjectDetailView(DetailView): model = Project class ProjectUpdateView(UpdateView): template_name_suffix = '_create' model = Project form_class = ProjectForm def all_projects(request): projects = Project.objects.all() return render_to_response('all_projects.html', locals(), context_instance=RequestContext(request)) def addTask(request): form = TasksForm(request.POST or None) if form.is_valid(): save_it = form.save(commit=False) save_it.save() message = 'Add a new task' messages.success(request, 'Your task has been added.') return HttpResponseRedirect('/') return render_to_response('addtask.html', locals(), context_instance=RequestContext(request)) def addArguments(request): form = ArgumentsForm(request.POST or None) if form.is_valid(): save_it = form.save(commit=False) save_it.save() message = 'Add a new argument' messages.success(request, 'Your argument has been added.') return HttpResponseRedirect('/') return render_to_response('addargs.html', locals(), context_instance=RequestContext(request)) class HeaderDeleteView(DeleteView): model = Header success_url = reverse_lazy('header-list') class HeaderListView(ListView): model = Header template_name_suffix = '_list' class HeaderCreateView(CreateView): template_name_suffix = '_create' model = Header form_class = HeaderForm class HeaderDetailView(DetailView): model = Header class HeaderUpdateView(UpdateView): template_name_suffix = '_create' model = Header form_class = HeaderForm # Target Views # Argument Views # Task Views
[ 11748, 640, 198, 11748, 7007, 198, 11748, 35555, 13, 3438, 13, 1084, 312, 296, 198, 6738, 300, 19875, 1330, 2123, 631, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 19...
3.079449
944
from amlb.utils import call_script_in_same_dir
[ 6738, 716, 23160, 13, 26791, 1330, 869, 62, 12048, 62, 259, 62, 31642, 62, 15908, 628, 198 ]
2.882353
17
from itunes_app_scraper.util import AppStoreException, AppStoreCollections, AppStoreCategories, AppStoreUtils import json import pytest import os
[ 6738, 340, 4015, 62, 1324, 62, 1416, 38545, 13, 22602, 1330, 2034, 22658, 16922, 11, 2034, 22658, 5216, 26448, 11, 2034, 22658, 34, 26129, 11, 2034, 22658, 18274, 4487, 198, 198, 11748, 33918, 198, 11748, 12972, 9288, 198, 11748, 28686 ]
3.65
40
from .record import Record
[ 198, 6738, 764, 22105, 1330, 13266, 628, 628, 198 ]
3.555556
9
from __future__ import print_function from bingads.service_client import _CAMPAIGN_OBJECT_FACTORY_V13 from bingads.v13.internal.bulk.string_table import _StringTable from bingads.v13.internal.bulk.entities.single_record_bulk_entity import _SingleRecordBulkEntity from bingads.v13.internal.bulk.mappings import _SimpleBulkMapping from bingads.v13.internal.extensions import *
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 275, 278, 5643, 13, 15271, 62, 16366, 1330, 4808, 34, 2390, 4537, 16284, 62, 9864, 23680, 62, 37, 10659, 15513, 62, 53, 1485, 198, 6738, 275, 278, 5643, 13, 85, 1485, 13, 325...
3.008
125
""" Tests for the LTI outcome service handlers, both in outcomes.py and in tasks.py """ from unittest.mock import MagicMock, patch import ddt from django.test import TestCase from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator import lms.djangoapps.lti_provider.tasks as tasks from common.djangoapps.student.tests.factories import UserFactory from lms.djangoapps.lti_provider.models import GradedAssignment, LtiConsumer, OutcomeService
[ 37811, 198, 51, 3558, 329, 262, 406, 25621, 8055, 2139, 32847, 11, 1111, 287, 10906, 13, 9078, 290, 287, 8861, 13, 9078, 198, 37811, 628, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 6139, 44, 735, 11, 8529, 198, 198, 11748, 288, ...
3.262411
141
from loser_agent import * if __name__ == '__main__': main()
[ 6738, 30256, 62, 25781, 1330, 1635, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198 ]
2.64
25
from .base.api_handler import APIBaseHandler
[ 6738, 764, 8692, 13, 15042, 62, 30281, 1330, 7824, 14881, 25060, 628 ]
3.833333
12
import random if __name__ == '__main__': main()
[ 11748, 4738, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198 ]
2.5
22
# Problem Reduction: variation of n-th staircase with n = [1, 2] steps. # Approach: We generate a bottom up DP table. # The tricky part is handling the corner cases (e.g. s = "30"). # Most elegant way to deal with those error/corner cases, is to allocate an extra space, dp[0]. # Let dp[ i ] = the number of ways to parse the string s[1: i + 1] # For example: # s = "231" # index 0: extra base offset. dp[0] = 1 # index 1: # of ways to parse "2" => dp[1] = 1 # index 2: # of ways to parse "23" => "2" and "23", dp[2] = 2 # index 3: # of ways to parse "231" => "2 3 1" and "23 1" => dp[3] = 2
[ 2, 20647, 33396, 25, 12291, 286, 299, 12, 400, 27656, 351, 299, 796, 685, 16, 11, 362, 60, 4831, 13, 198, 198, 2, 38066, 25, 775, 7716, 257, 4220, 510, 27704, 3084, 13, 198, 198, 2, 383, 17198, 636, 318, 9041, 262, 5228, 2663, 3...
2.722727
220
""" Tile svs/scn files Created on 11/01/2018 @author: RH """ import time import matplotlib import os import shutil import pandas as pd matplotlib.use('Agg') import Slicer import staintools import re # Get all images in the root directory # cut; each level is 2 times difference (20x, 10x, 5x) # Run as main if __name__ == "__main__": if not os.path.isdir('../tiles'): os.mkdir('../tiles') cut()
[ 37811, 198, 35103, 264, 14259, 14, 1416, 77, 3696, 198, 198, 41972, 319, 1367, 14, 486, 14, 7908, 198, 198, 31, 9800, 25, 35662, 198, 37811, 198, 198, 11748, 640, 198, 11748, 2603, 29487, 8019, 198, 11748, 28686, 198, 11748, 4423, 346...
2.614907
161
from __future__ import division import numpy as np import matplotlib.pyplot as plt m = 4 b = -.2 bl = -.1 br = -.1 sh = .13 from visualizations import show_bboxes
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 76, 796, 604, 198, 65, 796, 532, 13, 17, 198, 2436, 796, 532, 13, 16, 198, 1671, 796, ...
2.677419
62
# # PySNMP MIB module DPS-MIB-V38 (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DPS-MIB-V38 # Produced by pysmi-0.3.4 at Mon Apr 29 18:39:21 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") iso, ModuleIdentity, Unsigned32, Counter64, Gauge32, ObjectIdentity, IpAddress, enterprises, NotificationType, Integer32, Bits, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "ModuleIdentity", "Unsigned32", "Counter64", "Gauge32", "ObjectIdentity", "IpAddress", "enterprises", "NotificationType", "Integer32", "Bits", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "Counter32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") dpsInc = MibIdentifier((1, 3, 6, 1, 4, 1, 2682)) dpsAlarmControl = MibIdentifier((1, 3, 6, 1, 4, 1, 2682, 1)) tmonXM = MibIdentifier((1, 3, 6, 1, 4, 1, 2682, 1, 1)) tmonIdent = MibIdentifier((1, 3, 6, 1, 4, 1, 2682, 1, 1, 1)) tmonIdentManufacturer = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 1, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: tmonIdentManufacturer.setStatus('mandatory') tmonIdentModel = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 1, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: tmonIdentModel.setStatus('mandatory') tmonIdentSoftwareVersion = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 1, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: tmonIdentSoftwareVersion.setStatus('mandatory') tmonAlarmTable = MibTable((1, 3, 6, 1, 4, 1, 2682, 1, 1, 2), ) if mibBuilder.loadTexts: tmonAlarmTable.setStatus('mandatory') tmonAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2682, 1, 1, 2, 1), ).setIndexNames((0, "DPS-MIB-V38", "tmonAIndex")) if mibBuilder.loadTexts: tmonAlarmEntry.setStatus('mandatory') tmonAIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 1, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tmonAIndex.setStatus('mandatory') tmonASite = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 1, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(30, 30)).setFixedLength(30)).setMaxAccess("readonly") if mibBuilder.loadTexts: tmonASite.setStatus('mandatory') tmonADesc = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 1, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(40, 40)).setFixedLength(40)).setMaxAccess("readonly") if mibBuilder.loadTexts: tmonADesc.setStatus('mandatory') tmonAState = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 1, 2, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(8, 8)).setFixedLength(8)).setMaxAccess("readonly") if mibBuilder.loadTexts: tmonAState.setStatus('mandatory') tmonASeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 1, 2, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(8, 8)).setFixedLength(8)).setMaxAccess("readonly") if mibBuilder.loadTexts: tmonASeverity.setStatus('mandatory') tmonAChgDate = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 1, 2, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(8, 8)).setFixedLength(8)).setMaxAccess("readonly") if mibBuilder.loadTexts: tmonAChgDate.setStatus('mandatory') tmonAChgTime = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 1, 2, 1, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(8, 8)).setFixedLength(8)).setMaxAccess("readonly") if mibBuilder.loadTexts: tmonAChgTime.setStatus('mandatory') tmonAAuxDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 1, 2, 1, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(30, 30)).setFixedLength(30)).setMaxAccess("readonly") if mibBuilder.loadTexts: tmonAAuxDesc.setStatus('mandatory') tmonADispDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 1, 2, 1, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(14, 14)).setFixedLength(14)).setMaxAccess("readonly") if mibBuilder.loadTexts: tmonADispDesc.setStatus('mandatory') tmonAPntType = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 1, 2, 1, 10), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tmonAPntType.setStatus('mandatory') tmonAPort = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 1, 2, 1, 11), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tmonAPort.setStatus('mandatory') tmonAAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 1, 2, 1, 12), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tmonAAddress.setStatus('mandatory') tmonADisplay = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 1, 2, 1, 13), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tmonADisplay.setStatus('mandatory') tmonAPoint = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 1, 2, 1, 14), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tmonAPoint.setStatus('mandatory') tmonCommandGrid = MibIdentifier((1, 3, 6, 1, 4, 1, 2682, 1, 1, 3)) tmonCPType = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 1, 3, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: tmonCPType.setStatus('mandatory') tmonCPort = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 1, 3, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: tmonCPort.setStatus('mandatory') tmonCAddress = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 1, 3, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: tmonCAddress.setStatus('mandatory') tmonCDisplay = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 1, 3, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: tmonCDisplay.setStatus('mandatory') tmonCPoint = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 1, 3, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 64))).setMaxAccess("readwrite") if mibBuilder.loadTexts: tmonCPoint.setStatus('mandatory') tmonCEvent = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 1, 3, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: tmonCEvent.setStatus('mandatory') tmonCAction = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 1, 3, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 17, 18, 19))).clone(namedValues=NamedValues(("latch", 1), ("release", 2), ("momentary", 3), ("ack", 17), ("tag", 18), ("untag", 19)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: tmonCAction.setStatus('mandatory') tmonCAuxText = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 1, 3, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(30, 30)).setFixedLength(30)).setMaxAccess("readwrite") if mibBuilder.loadTexts: tmonCAuxText.setStatus('mandatory') tmonCResult = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 1, 3, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("success", 1), ("failure", 2), ("pending", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: tmonCResult.setStatus('mandatory') dpsRTU = MibIdentifier((1, 3, 6, 1, 4, 1, 2682, 1, 2)) dpsRTUIdent = MibIdentifier((1, 3, 6, 1, 4, 1, 2682, 1, 2, 1)) dpsRTUManufacturer = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 2, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(30, 30)).setFixedLength(30)).setMaxAccess("readonly") if mibBuilder.loadTexts: dpsRTUManufacturer.setStatus('mandatory') dpsRTUModel = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(30, 30)).setFixedLength(30)).setMaxAccess("readonly") if mibBuilder.loadTexts: dpsRTUModel.setStatus('mandatory') dpsRTUFirmwareVersion = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(20, 20)).setFixedLength(20)).setMaxAccess("readonly") if mibBuilder.loadTexts: dpsRTUFirmwareVersion.setStatus('mandatory') dpsRTUDateTime = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 2, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(23, 23)).setFixedLength(23)).setMaxAccess("readwrite") if mibBuilder.loadTexts: dpsRTUDateTime.setStatus('mandatory') dpsRTUSyncReq = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1))).clone(namedValues=NamedValues(("sync", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: dpsRTUSyncReq.setStatus('mandatory') dpsRTUDisplayGrid = MibTable((1, 3, 6, 1, 4, 1, 2682, 1, 2, 2), ) if mibBuilder.loadTexts: dpsRTUDisplayGrid.setStatus('mandatory') dpsRTUDisplayEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2682, 1, 2, 2, 1), ).setIndexNames((0, "DPS-MIB-V38", "dpsRTUPort"), (0, "DPS-MIB-V38", "dpsRTUAddress"), (0, "DPS-MIB-V38", "dpsRTUDisplay")) if mibBuilder.loadTexts: dpsRTUDisplayEntry.setStatus('mandatory') dpsRTUPort = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 2, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dpsRTUPort.setStatus('mandatory') dpsRTUAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 2, 2, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dpsRTUAddress.setStatus('mandatory') dpsRTUDisplay = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 2, 2, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dpsRTUDisplay.setStatus('mandatory') dpsRTUDispDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 2, 2, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(20, 20)).setFixedLength(20)).setMaxAccess("readonly") if mibBuilder.loadTexts: dpsRTUDispDesc.setStatus('mandatory') dpsRTUPntMap = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 2, 2, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(71, 71)).setFixedLength(71)).setMaxAccess("readonly") if mibBuilder.loadTexts: dpsRTUPntMap.setStatus('mandatory') dpsRTUControlGrid = MibIdentifier((1, 3, 6, 1, 4, 1, 2682, 1, 2, 3)) dpsRTUCPort = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 2, 3, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: dpsRTUCPort.setStatus('mandatory') dpsRTUCAddress = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 2, 3, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: dpsRTUCAddress.setStatus('mandatory') dpsRTUCDisplay = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 2, 3, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: dpsRTUCDisplay.setStatus('mandatory') dpsRTUCPoint = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 2, 3, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 64))).setMaxAccess("readwrite") if mibBuilder.loadTexts: dpsRTUCPoint.setStatus('mandatory') dpsRTUCAction = MibScalar((1, 3, 6, 1, 4, 1, 2682, 1, 2, 3, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("latch", 1), ("release", 2), ("momentary", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: dpsRTUCAction.setStatus('mandatory') dpsRTUAlarmGrid = MibTable((1, 3, 6, 1, 4, 1, 2682, 1, 2, 5), ) if mibBuilder.loadTexts: dpsRTUAlarmGrid.setStatus('mandatory') dpsRTUAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2682, 1, 2, 5, 1), ).setIndexNames((0, "DPS-MIB-V38", "dpsRTUAPort"), (0, "DPS-MIB-V38", "dpsRTUAAddress"), (0, "DPS-MIB-V38", "dpsRTUADisplay"), (0, "DPS-MIB-V38", "dpsRTUAPoint")) if mibBuilder.loadTexts: dpsRTUAlarmEntry.setStatus('mandatory') dpsRTUAPort = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 2, 5, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dpsRTUAPort.setStatus('mandatory') dpsRTUAAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 2, 5, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dpsRTUAAddress.setStatus('mandatory') dpsRTUADisplay = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 2, 5, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dpsRTUADisplay.setStatus('mandatory') dpsRTUAPoint = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 2, 5, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dpsRTUAPoint.setStatus('mandatory') dpsRTUAPntDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 2, 5, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(21, 21)).setFixedLength(21)).setMaxAccess("readonly") if mibBuilder.loadTexts: dpsRTUAPntDesc.setStatus('mandatory') dpsRTUAState = MibTableColumn((1, 3, 6, 1, 4, 1, 2682, 1, 2, 5, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(8, 8)).setFixedLength(8)).setMaxAccess("readonly") if mibBuilder.loadTexts: dpsRTUAState.setStatus('mandatory') tmonCRalarmSet = NotificationType((1, 3, 6, 1, 4, 1, 2682, 1, 1) + (0,10)).setObjects(("DPS-MIB-V38", "tmonASite"), ("DPS-MIB-V38", "tmonADesc"), ("DPS-MIB-V38", "tmonAState"), ("DPS-MIB-V38", "tmonASeverity"), ("DPS-MIB-V38", "tmonAChgDate"), ("DPS-MIB-V38", "tmonAChgTime"), ("DPS-MIB-V38", "tmonAAuxDesc"), ("DPS-MIB-V38", "tmonADispDesc"), ("DPS-MIB-V38", "tmonAPntType"), ("DPS-MIB-V38", "tmonAPort"), ("DPS-MIB-V38", "tmonAAddress"), ("DPS-MIB-V38", "tmonADisplay"), ("DPS-MIB-V38", "tmonAPoint"), ("DPS-MIB-V38", "tmonCEvent")) tmonCRalarmClr = NotificationType((1, 3, 6, 1, 4, 1, 2682, 1, 1) + (0,11)).setObjects(("DPS-MIB-V38", "tmonASite"), ("DPS-MIB-V38", "tmonADesc"), ("DPS-MIB-V38", "tmonAState"), ("DPS-MIB-V38", "tmonASeverity"), ("DPS-MIB-V38", "tmonAChgDate"), ("DPS-MIB-V38", "tmonAChgTime"), ("DPS-MIB-V38", "tmonAAuxDesc"), ("DPS-MIB-V38", "tmonADispDesc"), ("DPS-MIB-V38", "tmonAPntType"), ("DPS-MIB-V38", "tmonAPort"), ("DPS-MIB-V38", "tmonAAddress"), ("DPS-MIB-V38", "tmonADisplay"), ("DPS-MIB-V38", "tmonAPoint"), ("DPS-MIB-V38", "tmonCEvent")) tmonMJalarmSet = NotificationType((1, 3, 6, 1, 4, 1, 2682, 1, 1) + (0,12)).setObjects(("DPS-MIB-V38", "tmonASite"), ("DPS-MIB-V38", "tmonADesc"), ("DPS-MIB-V38", "tmonAState"), ("DPS-MIB-V38", "tmonASeverity"), ("DPS-MIB-V38", "tmonAChgDate"), ("DPS-MIB-V38", "tmonAChgTime"), ("DPS-MIB-V38", "tmonAAuxDesc"), ("DPS-MIB-V38", "tmonADispDesc"), ("DPS-MIB-V38", "tmonAPntType"), ("DPS-MIB-V38", "tmonAPort"), ("DPS-MIB-V38", "tmonAAddress"), ("DPS-MIB-V38", "tmonADisplay"), ("DPS-MIB-V38", "tmonAPoint"), ("DPS-MIB-V38", "tmonCEvent")) tmonMJalarmClr = NotificationType((1, 3, 6, 1, 4, 1, 2682, 1, 1) + (0,13)).setObjects(("DPS-MIB-V38", "tmonASite"), ("DPS-MIB-V38", "tmonADesc"), ("DPS-MIB-V38", "tmonAState"), ("DPS-MIB-V38", "tmonASeverity"), ("DPS-MIB-V38", "tmonAChgDate"), ("DPS-MIB-V38", "tmonAChgTime"), ("DPS-MIB-V38", "tmonAAuxDesc"), ("DPS-MIB-V38", "tmonADispDesc"), ("DPS-MIB-V38", "tmonAPntType"), ("DPS-MIB-V38", "tmonAPort"), ("DPS-MIB-V38", "tmonAAddress"), ("DPS-MIB-V38", "tmonADisplay"), ("DPS-MIB-V38", "tmonAPoint"), ("DPS-MIB-V38", "tmonCEvent")) tmonMNalarmSet = NotificationType((1, 3, 6, 1, 4, 1, 2682, 1, 1) + (0,14)).setObjects(("DPS-MIB-V38", "tmonASite"), ("DPS-MIB-V38", "tmonADesc"), ("DPS-MIB-V38", "tmonAState"), ("DPS-MIB-V38", "tmonASeverity"), ("DPS-MIB-V38", "tmonAChgDate"), ("DPS-MIB-V38", "tmonAChgTime"), ("DPS-MIB-V38", "tmonAAuxDesc"), ("DPS-MIB-V38", "tmonADispDesc"), ("DPS-MIB-V38", "tmonAPntType"), ("DPS-MIB-V38", "tmonAPort"), ("DPS-MIB-V38", "tmonAAddress"), ("DPS-MIB-V38", "tmonADisplay"), ("DPS-MIB-V38", "tmonAPoint"), ("DPS-MIB-V38", "tmonCEvent")) tmonMNalarmClr = NotificationType((1, 3, 6, 1, 4, 1, 2682, 1, 1) + (0,15)).setObjects(("DPS-MIB-V38", "tmonASite"), ("DPS-MIB-V38", "tmonADesc"), ("DPS-MIB-V38", "tmonAState"), ("DPS-MIB-V38", "tmonASeverity"), ("DPS-MIB-V38", "tmonAChgDate"), ("DPS-MIB-V38", "tmonAChgTime"), ("DPS-MIB-V38", "tmonAAuxDesc"), ("DPS-MIB-V38", "tmonADispDesc"), ("DPS-MIB-V38", "tmonAPntType"), ("DPS-MIB-V38", "tmonAPort"), ("DPS-MIB-V38", "tmonAAddress"), ("DPS-MIB-V38", "tmonADisplay"), ("DPS-MIB-V38", "tmonAPoint"), ("DPS-MIB-V38", "tmonCEvent")) tmonSTalarmSet = NotificationType((1, 3, 6, 1, 4, 1, 2682, 1, 1) + (0,16)).setObjects(("DPS-MIB-V38", "tmonASite"), ("DPS-MIB-V38", "tmonADesc"), ("DPS-MIB-V38", "tmonAState"), ("DPS-MIB-V38", "tmonASeverity"), ("DPS-MIB-V38", "tmonAChgDate"), ("DPS-MIB-V38", "tmonAChgTime"), ("DPS-MIB-V38", "tmonAAuxDesc"), ("DPS-MIB-V38", "tmonADispDesc"), ("DPS-MIB-V38", "tmonAPntType"), ("DPS-MIB-V38", "tmonAPort"), ("DPS-MIB-V38", "tmonAAddress"), ("DPS-MIB-V38", "tmonADisplay"), ("DPS-MIB-V38", "tmonAPoint"), ("DPS-MIB-V38", "tmonCEvent")) tmonSTalarmClr = NotificationType((1, 3, 6, 1, 4, 1, 2682, 1, 1) + (0,17)).setObjects(("DPS-MIB-V38", "tmonASite"), ("DPS-MIB-V38", "tmonADesc"), ("DPS-MIB-V38", "tmonAState"), ("DPS-MIB-V38", "tmonASeverity"), ("DPS-MIB-V38", "tmonAChgDate"), ("DPS-MIB-V38", "tmonAChgTime"), ("DPS-MIB-V38", "tmonAAuxDesc"), ("DPS-MIB-V38", "tmonADispDesc"), ("DPS-MIB-V38", "tmonAPntType"), ("DPS-MIB-V38", "tmonAPort"), ("DPS-MIB-V38", "tmonAAddress"), ("DPS-MIB-V38", "tmonADisplay"), ("DPS-MIB-V38", "tmonAPoint"), ("DPS-MIB-V38", "tmonCEvent")) dpsRTUPointSet = NotificationType((1, 3, 6, 1, 4, 1, 2682, 1, 2) + (0,20)).setObjects(("DPS-MIB-V38", "sysDescr"), ("DPS-MIB-V38", "sysLocation"), ("DPS-MIB-V38", "dpsRTUDateTime"), ("DPS-MIB-V38", "dpsRTUAPort"), ("DPS-MIB-V38", "dpsRTUAAddress"), ("DPS-MIB-V38", "dpsRTUADisplay"), ("DPS-MIB-V38", "dpsRTUAPoint"), ("DPS-MIB-V38", "dpsRTUAPntDesc"), ("DPS-MIB-V38", "dpsRTUAState")) dpsRTUPointClr = NotificationType((1, 3, 6, 1, 4, 1, 2682, 1, 2) + (0,21)).setObjects(("DPS-MIB-V38", "sysDescr"), ("DPS-MIB-V38", "sysLocation"), ("DPS-MIB-V38", "dpsRTUDateTime"), ("DPS-MIB-V38", "dpsRTUAPort"), ("DPS-MIB-V38", "dpsRTUCAddress"), ("DPS-MIB-V38", "dpsRTUADisplay"), ("DPS-MIB-V38", "dpsRTUAPoint"), ("DPS-MIB-V38", "dpsRTUAPntDesc"), ("DPS-MIB-V38", "dpsRTUAState")) dpsRTUsumPSet = NotificationType((1, 3, 6, 1, 4, 1, 2682, 1, 2) + (0,101)).setObjects(("DPS-MIB-V38", "sysDescr"), ("DPS-MIB-V38", "sysLocation"), ("DPS-MIB-V38", "dpsRTUDateTime")) dpsRTUsumPClr = NotificationType((1, 3, 6, 1, 4, 1, 2682, 1, 2) + (0,102)).setObjects(("DPS-MIB-V38", "sysDescr"), ("DPS-MIB-V38", "sysLocation"), ("DPS-MIB-V38", "dpsRTUDateTime")) dpsRTUcomFailed = NotificationType((1, 3, 6, 1, 4, 1, 2682, 1, 2) + (0,103)).setObjects(("DPS-MIB-V38", "sysDescr"), ("DPS-MIB-V38", "sysLocation"), ("DPS-MIB-V38", "dpsRTUDateTime")) dpsRTUcomRestored = NotificationType((1, 3, 6, 1, 4, 1, 2682, 1, 2) + (0,104)).setObjects(("DPS-MIB-V38", "sysDescr"), ("DPS-MIB-V38", "sysLocation"), ("DPS-MIB-V38", "dpsRTUDateTime")) mibBuilder.exportSymbols("DPS-MIB-V38", tmonAlarmEntry=tmonAlarmEntry, tmonAIndex=tmonAIndex, tmonAChgDate=tmonAChgDate, tmonCAddress=tmonCAddress, tmonSTalarmClr=tmonSTalarmClr, dpsRTUFirmwareVersion=dpsRTUFirmwareVersion, tmonAChgTime=tmonAChgTime, dpsRTUCPoint=dpsRTUCPoint, dpsRTU=dpsRTU, dpsRTUPntMap=dpsRTUPntMap, dpsRTUsumPSet=dpsRTUsumPSet, tmonASite=tmonASite, tmonAlarmTable=tmonAlarmTable, dpsRTUcomFailed=dpsRTUcomFailed, tmonCRalarmSet=tmonCRalarmSet, dpsRTUDisplayEntry=dpsRTUDisplayEntry, dpsRTUAlarmGrid=dpsRTUAlarmGrid, tmonAAddress=tmonAAddress, dpsRTUADisplay=dpsRTUADisplay, dpsRTUDisplayGrid=dpsRTUDisplayGrid, tmonADispDesc=tmonADispDesc, dpsRTUManufacturer=dpsRTUManufacturer, dpsRTUModel=dpsRTUModel, dpsRTUDispDesc=dpsRTUDispDesc, tmonCPoint=tmonCPoint, tmonMJalarmSet=tmonMJalarmSet, dpsRTUAPntDesc=dpsRTUAPntDesc, dpsInc=dpsInc, dpsAlarmControl=dpsAlarmControl, tmonAPort=tmonAPort, dpsRTUAlarmEntry=dpsRTUAlarmEntry, dpsRTUSyncReq=dpsRTUSyncReq, tmonIdent=tmonIdent, tmonASeverity=tmonASeverity, tmonMNalarmClr=tmonMNalarmClr, dpsRTUcomRestored=dpsRTUcomRestored, tmonCAction=tmonCAction, tmonIdentSoftwareVersion=tmonIdentSoftwareVersion, tmonIdentModel=tmonIdentModel, dpsRTUCAction=dpsRTUCAction, tmonMNalarmSet=tmonMNalarmSet, tmonADesc=tmonADesc, tmonCEvent=tmonCEvent, tmonSTalarmSet=tmonSTalarmSet, tmonADisplay=tmonADisplay, dpsRTUIdent=dpsRTUIdent, dpsRTUAPort=dpsRTUAPort, dpsRTUAAddress=dpsRTUAAddress, dpsRTUAddress=dpsRTUAddress, dpsRTUCPort=dpsRTUCPort, tmonAPntType=tmonAPntType, dpsRTUCAddress=dpsRTUCAddress, dpsRTUCDisplay=dpsRTUCDisplay, dpsRTUAState=dpsRTUAState, tmonCResult=tmonCResult, tmonXM=tmonXM, dpsRTUDateTime=dpsRTUDateTime, dpsRTUAPoint=dpsRTUAPoint, dpsRTUsumPClr=dpsRTUsumPClr, tmonCommandGrid=tmonCommandGrid, tmonCPType=tmonCPType, tmonAState=tmonAState, dpsRTUPort=dpsRTUPort, tmonMJalarmClr=tmonMJalarmClr, dpsRTUDisplay=dpsRTUDisplay, dpsRTUPointSet=dpsRTUPointSet, dpsRTUPointClr=dpsRTUPointClr, tmonAPoint=tmonAPoint, tmonCRalarmClr=tmonCRalarmClr, tmonIdentManufacturer=tmonIdentManufacturer, tmonCAuxText=tmonCAuxText, dpsRTUControlGrid=dpsRTUControlGrid, tmonAAuxDesc=tmonAAuxDesc, tmonCPort=tmonCPort, tmonCDisplay=tmonCDisplay)
[ 2, 198, 2, 9485, 15571, 7378, 337, 9865, 8265, 25366, 12, 8895, 33, 12, 53, 2548, 357, 4023, 1378, 16184, 76, 489, 8937, 13, 785, 14, 79, 893, 11632, 8, 198, 2, 7054, 45, 13, 16, 2723, 2393, 1378, 14, 14490, 14, 67, 615, 47562, ...
2.293396
9,131
import numpy as np
[ 11748, 299, 32152, 355, 45941, 198 ]
3.166667
6
import time from smqtk.utils import SmqtkObject
[ 11748, 640, 198, 198, 6738, 895, 80, 30488, 13, 26791, 1330, 2439, 80, 30488, 10267, 628 ]
3.125
16
arr = ['', 'Rolien', 'Naej', 'Elehcim', 'Odranoel'] n = int(input()) while n != 0: n -= 1 k = int(input()) while k != 0: k -= 1 num = int(input()) print(arr[num])
[ 3258, 796, 37250, 3256, 705, 49, 349, 2013, 3256, 705, 45, 3609, 73, 3256, 705, 28827, 71, 66, 320, 3256, 705, 46, 67, 35823, 417, 20520, 201, 198, 77, 796, 493, 7, 15414, 28955, 201, 198, 4514, 299, 14512, 657, 25, 201, 198, 220,...
1.839286
112
import socket, time, sys import argparse __version__="0.1" min_port=0 #max_port=65535 max_port=10000 parser = argparse.ArgumentParser(description="a simple python port scanner",epilog="author: blackc8") parser.add_argument("hostname",metavar="<hostname>",help="host to scan") parser.add_argument("-dp","--ddport",help="do not display port",action="store_true") parser.add_argument("-sF","--show_filtered",help="show filtered ports",action="store_true") parser.add_argument("-b","--banner",help="grab the banners of ports",action="store_true") parser.add_argument("-v","--version",help="dispaly version",action="version",version="%(prog)s ("+__version__+")") args=parser.parse_args() if __name__ == "__main__": scan(args.hostname,args.ddport,args.banner,args.show_filtered)
[ 11748, 17802, 11, 640, 11, 25064, 198, 11748, 1822, 29572, 198, 198, 834, 9641, 834, 2625, 15, 13, 16, 1, 198, 1084, 62, 634, 28, 15, 198, 2, 9806, 62, 634, 28, 35916, 2327, 198, 9806, 62, 634, 28, 49388, 198, 198, 48610, 796, 1...
2.903346
269
# -*- coding: utf-8 -*- """ Created on Mon Sep 16 20:15:55 2019 @author: Shinelon """ import numpy as np import pandas as pd import matplotlib.pyplot as plt path='ex2data1.txt' data=pd.read_csv(path,header=None,names=['Exam1','Exam2','Admitted']) data.head() # positive=data[data['Admitted'].isin([1])] negative=data[data['Admitted'].isin([0])] fig,ax=plt.subplots(figsize=(12,8)) #c=colors20 ax.scatter(positive['Exam1'],positive['Exam2'],c='b',marker='o',label='Admitted') ax.scatter(negative['Exam1'],negative['Exam2'],c='r',marker='o',label='Unadimitted') ax.legend(loc=4) ax.set_xlabel('Exam1 Score');ax.set_ylabel('Exam2 Score') plt.show()# #sigmoid #/sigmoid nums=np.arange(-10,10,1) fig,ax=plt.subplots(figsize=(12,8)) ax.plot(nums,sigmoid(nums),'r') plt.show() data.insert(0,'ones',1)#011 cols=data.shape[1] X=data.iloc[:,0:cols-1] y=data.iloc[:,cols-1:cols] X=np.array(X.values) y=np.array(y.values) theta=np.zeros(3) cost(theta,X,y) gradientDescent(theta,X,y)#theta #SciPyTruncatedNewton import scipy.optimize as opt result=opt.fmin_tnc(func=cost,x0=theta,fprime=gradientDescent,args=(X,y)) result#theta cost(result[0],X,y) # theta_min=np.matrix(result[0])#theta_min1x3 predictions=predict(theta_min,X) correct=[1 if((a==1 and b==1) or (a==0 and b==0))\ else 0 for (a,b) in zip(predictions,y)] accuracy=(sum(map(int,correct))/len(correct)) print('accuracy={}'.format(accuracy))# path2='ex2data2.txt' data2=pd.read_csv(path2,header=None,names=['Test1','Test2','Accepted']) data2.head() positive=data2[data2['Accepted'].isin([1])] negative=data2[data2['Accepted'].isin([0])] fig,ax=plt.subplots(figsize=(12,8)) ax.scatter(positive['Test1'],positive['Test2'],s=50,c='b',\ marker='o',label='Accepted') ax.scatter(negative['Test1'],negative['Test2'],s=50,c='r',\ marker='x',label='Rejected') ax.legend() ax.set_xlabel('Test1 Score') ax.set_ylabel('Test2 Score') plt.show() # degree=5 x1=data2['Test1'] x2=data2['Test2'] data2.insert(3,'ones',1) for i in range(1,degree): for j in range(0,i): data2['F'+str(i)+str(j)]=np.power(x1,i-j)*np.power(x2,j) data2.drop('Test1',axis=1,inplace=True)#axis=01TRUE data2.drop('Test2',axis=1,inplace=True) data2.head() # #theta cols=data2.shape[1] X2=data2.iloc[:,1:cols] y2=data2.iloc[:,0:1] X2=np.array(X2.values) y2=np.array(y2.values) theta2=np.zeros(11) learningRate=1 costReg(theta2,X2,y2,learningRate) gradientReg(theta2,X2,y2,learningRate) result2=opt.fmin_tnc(func=costReg,x0=theta2,fprime=gradientReg,\ args=(X2,y2,learningRate)) result2 # theta_min=np.matrix(result2[0]) predictions=predict(theta_min,X2) correct=[1 if ((a==1 and b==1) or (a==0 and b==0))\ else 0 for (a,b) in zip(predictions,y2)] accuracy=(sum(map(int,correct))/len(correct)) print('accuracy2={}%'.format(accuracy*100)) #sklearn from sklearn import linear_model model=linear_model.LogisticRegression(penalty='l2',\ C=1.0,solver='liblinear') model.fit(X2,y2.ravel()) model.score(X2,y2)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 8621, 1467, 1160, 25, 1314, 25, 2816, 13130, 198, 198, 31, 9800, 25, 11466, 417, 261, 198, 37811, 198, 11748, 299, 32152, 355, 45941, 198, ...
2.076132
1,458
# Generated by Django 2.1.9 on 2019-09-01 09:10 from django.conf import settings from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 24, 319, 13130, 12, 2931, 12, 486, 7769, 25, 940, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 1420...
3.019231
52
# Code from Chapter 5 of Machine Learning: An Algorithmic Perspective (2nd Edition) # by Stephen Marsland (http://stephenmonika.net) # You are free to use, change, or redistribute the code in any way you wish for # non-commercial purposes, but please maintain the name of the original author. # This code comes with no warranty of any kind. # Stephen Marsland, 2008, 2014 import numpy as np import pcn import kmeans
[ 198, 2, 6127, 422, 7006, 642, 286, 10850, 18252, 25, 1052, 978, 7727, 9383, 42051, 357, 17, 358, 5061, 8, 198, 2, 416, 7970, 8706, 1044, 357, 4023, 1378, 9662, 831, 2144, 9232, 13, 3262, 8, 198, 198, 2, 921, 389, 1479, 284, 779, ...
3.684211
114
#!/usr/bin/env python3 """ Gradients for inner product. """ import tensorflow as tf from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import sparse_ops correlation_grad_module = tf.load_op_library('./build/libcorrelation_grad.so')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 198, 42731, 2334, 329, 8434, 1720, 13, 198, 37811, 198, 220, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11192, 273, 11125, 13, 29412, 13, 30604, 1330, 39628, 198, ...
3.136842
95
from ._scorer import make_ts_scorer from ._scorer import get_scorer __all__ = [ "get_scorer", "make_ts_scorer", ]
[ 6738, 47540, 1416, 11934, 1330, 787, 62, 912, 62, 1416, 11934, 198, 6738, 47540, 1416, 11934, 1330, 651, 62, 1416, 11934, 198, 198, 834, 439, 834, 796, 685, 198, 220, 220, 220, 366, 1136, 62, 1416, 11934, 1600, 198, 220, 220, 220, 3...
2.320755
53
# This file is part of sner4 project governed by MIT license, see the LICENSE.txt file. """ auth.views.user selenium tests """ from flask import url_for from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from sner.server.auth.models import User from sner.server.extensions import db from tests.selenium import dt_inrow_delete, dt_rendered, webdriver_waituntil def test_user_list_route(live_server, sl_admin, user): # pylint: disable=unused-argument """simple test ajaxed datatable rendering""" sl_admin.get(url_for('auth.user_list_route', _external=True)) dt_rendered(sl_admin, 'user_list_table', user.username) def test_user_list_route_inrow_delete(live_server, sl_admin, user): # pylint: disable=unused-argument """delete user inrow button""" user_id = user.id db.session.expunge(user) sl_admin.get(url_for('auth.user_list_route', _external=True)) # in this test-case there are multiple items in the table (current_user, test_user), hence index which to delete has to be used dt_inrow_delete(sl_admin, 'user_list_table', 1) assert not User.query.get(user_id) def test_user_apikey_route(live_server, sl_admin, user): # pylint: disable=unused-argument """apikey generation/revoking feature tests""" sl_admin.get(url_for('auth.user_list_route', _external=True)) dt_rendered(sl_admin, 'user_list_table', user.username) # disable fade, the timing interferes with the test sl_admin.execute_script('$("div#modal-global").toggleClass("fade")') sl_admin.find_element_by_xpath('//a[@data-url="%s"]' % url_for('auth.user_apikey_route', user_id=user.id, action='generate')).click() webdriver_waituntil(sl_admin, EC.visibility_of_element_located((By.XPATH, '//h4[@class="modal-title" and text()="Apikey operation"]'))) sl_admin.find_element_by_xpath('//div[@id="modal-global"]//button[@class="close"]').click() webdriver_waituntil(sl_admin, EC.invisibility_of_element_located((By.XPATH, '//div[@class="modal-global"'))) dt_rendered(sl_admin, 'user_list_table', user.username) db.session.refresh(user) assert user.apikey sl_admin.find_element_by_xpath('//a[@data-url="%s"]' % url_for('auth.user_apikey_route', user_id=user.id, action='revoke')).click() webdriver_waituntil(sl_admin, EC.visibility_of_element_located((By.XPATH, '//h4[@class="modal-title" and text()="Apikey operation"]'))) sl_admin.find_element_by_xpath('//div[@id="modal-global"]//button[@class="close"]').click() webdriver_waituntil(sl_admin, EC.invisibility_of_element_located((By.XPATH, '//div[@class="modal-global"'))) dt_rendered(sl_admin, 'user_list_table', user.username) db.session.refresh(user) assert not user.apikey
[ 2, 770, 2393, 318, 636, 286, 264, 1008, 19, 1628, 21825, 416, 17168, 5964, 11, 766, 262, 38559, 24290, 13, 14116, 2393, 13, 198, 37811, 198, 18439, 13, 33571, 13, 7220, 384, 11925, 1505, 5254, 198, 37811, 198, 198, 6738, 42903, 1330, ...
2.669231
1,040
# -*- coding: utf-8 -*- from .box import indent from .box import read_box
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 6738, 764, 3524, 1330, 33793, 201, 198, 6738, 764, 3524, 1330, 1100, 62, 3524, 201, 198, 201, 198 ]
2.393939
33
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> ================================ RESTART ================================ >>> >>> ================================ RESTART ================================ >>> What is your favorite color?blue I like that color too >>> ================================ RESTART ================================ >>> What is your favorite color?black I do not care too much for that color >>> ================================ RESTART ================================ >>> What is your favorite color?green That is my favorite color. >>> ================================ RESTART ================================ >>> What is your favorite color?green That is my 2nd favorite color. >>> ================================ RESTART ================================ >>> What is your favorite color?violet Traceback (most recent call last): File "C:/Users/P/Desktop/two_b.py", line 7, in <module> rank = color.index(pick) + 1 ValueError: 'violet' is not in list >>> ================================ RESTART ================================ >>> What is your favorite color?violet I do not care too much for that color >>> ================================ RESTART ================================ >>> What is your favorite color?yello I do not care too much for that color >>> ================================ RESTART ================================ >>> What is your favorite color?yellow That is my 6th favorite color. >>> ================================ RESTART ================================ >>> Bach Antheil Chopin Mozart Handel >>> ================================ RESTART ================================ >>> Please enter a lower bound: 4 Please enter an upper bound: 23 2**4=16 2**5=32 2**6=64 2**7=128 2**8=256 2**9=512 2**10=1024 2**11=2048 2**12=4096 2**13=8192 2**14=16384 2**15=32768 2**16=65536 2**17=131072 2**18=262144 2**19=524288 2**20=1048576 2**21=2097152 2**22=4194304 >>> ================================ RESTART ================================ >>> Please enter a lower bound: 0 Please enter an upper bound: 6 2**0 = 1 2**1 = 2 2**2 = 4 2**3 = 8 2**4 = 16 2**5 = 32 2**6 = 64 >>>
[ 37906, 513, 13, 19, 13, 16, 357, 85, 18, 13, 19, 13, 16, 25, 66, 15, 68, 36244, 68, 20943, 16072, 11, 1737, 1248, 1946, 11, 838, 25, 2548, 25, 1828, 8, 685, 5653, 34, 410, 13, 36150, 3933, 1643, 357, 24123, 15437, 319, 1592, 2...
3.548742
636
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from glob import glob import logging import os from os.path import abspath, dirname, normpath import re from shutil import rmtree import sqlite3 import sys import folium from folium.plugins import FastMarkerCluster from zipfile import ZipFile import pandas as pd import requests from config import db from models import MarinaLitterWatch CLEAN_FILES = ('./CSV_1', './CSV_2') ZIP_FILE = 'fme.zip' DB_FILE = 'mlw.db' MAP_FILE = 'locations.html' # Set Logging logging.basicConfig(format="%(asctime)s %(levelname)s: %(message)s", datefmt="%d-%b-%y %H:%M:%S", stream=sys.stdout, level=logging.INFO) # Set local path here = normpath(abspath(dirname(__file__))) # Download data logging.info("Downloading data...") response = requests.get( 'http://fme.discomap.eea.europa.eu/fmedatadownload/MarineLitter/MLWPivotExport.fmw' '?CommunityCode=&FromDate=2010-01-01&ToDate=2022-12-31' '&opt_showresult=false&opt_servicemode=sync') downloadlink = re.search( r"<a\s+(?:[^>]*?\s+)?href=([\"'])(.*?)\1>", response.content.decode()).group(2) logging.info("Saving data...") zipfile = requests.get(downloadlink) open(f'{here}/{ZIP_FILE}', 'wb').write(zipfile.content) logging.info("Uzipping data...") zipObject = ZipFile(f'{here}/{ZIP_FILE}', 'r') zipObject.extractall(path=here) logging.info("Loading data...") # Data to initialize database with data = pd.read_csv( f'{here}/CSV_1/MLW_PivotExport/MLW_Data.csv', encoding="ISO-8859-1") # Delete database file if it exists currently if os.path.exists(f'{here}/{DB_FILE}'): os.remove(f'{here}/{DB_FILE}') # Create the database db.create_all() # populate the database conn = sqlite3.connect(f'{here}/{DB_FILE}') data.to_sql('mlw', conn, if_exists='append') db.session.commit() # Create Map folium_map = folium.Map(location=[40.416729, -3.703339], zoom_start=3, min_zoom=3, tiles='Stamen Terrain') callback = ('function (row) {' 'var marker = L.marker(new L.LatLng(row[0], row[1]), {color: "red"});' 'var icon = L.AwesomeMarkers.icon({' "icon: 'info-sign'," "iconColor: 'white'," "markerColor: 'red'," "prefix: 'glyphicon'," "extraClasses: 'fa-rotate-0'" '});' 'marker.setIcon(icon);' "var popup = L.popup({maxWidth: '300'});" "const display_text = {text: row[2]};" "var mytext = $(`<div id='mytext' class='display_text' style='width: 100.0%; height: 100.0%;'> ${display_text.text}</div>`)[0];" "popup.setContent(mytext);" "marker.bindPopup(popup);" 'return marker};') FastMarkerCluster(data=list( zip(data['lat_y1'].values, data['lon_x1'].values, data['BeachName'].values)), callback=callback).add_to(folium_map) folium.LayerControl().add_to(folium_map) folium_map.save(f'{here}/templates/{MAP_FILE}') # Clean files logging.info("Cleaning files...") for path_spec in CLEAN_FILES: # Make paths absolute and relative to this path abs_paths = glob(os.path.normpath( os.path.join(here, path_spec))) for path in [str(p) for p in abs_paths]: if not path.startswith(here): # Die if path in CLEAN_FILES is absolute + outside this directory raise ValueError( "%s is not a path inside %s" % (path, here)) logging.info(f'removing {os.path.relpath(path)}') rmtree(path) logging.info(f'removing {ZIP_FILE}') os.remove(f'{here}/{ZIP_FILE}')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 11593, 37443, 834, 1330, 357, 21426, 11, 4112, 62, 11748, 11, 3601, 62, 8818, 11, 198, 220, 220, 220, 220,...
2.229607
1,655
# -*- coding: utf-8 -*- from __future__ import unicode_literals TIPO = 'selectable' # 'basic' or 'selectable'. 'basic': necesario para el funcionamiento del programa # 'selectable': No necesario. Aade nuevas funcionalidades al programa # Por ejemplo autenticar es 'basic', pero actas es prescindible # El code_menu debe ser nico y se configurar como un permiso del sistema MENU_DEFAULT = [ {'code_menu': 'acceso_domotica', 'texto_menu': 'Domtica', 'href': '', 'nivel': 1, 'tipo': 'Accesible', 'pos': 1, }, {'code_menu': 'acceso_grupos_domotica', 'texto_menu': 'Agrupaciones de dispositivos', 'href': 'grupos_domotica', 'nivel': 2, 'tipo': 'Accesible', 'pos': 1, 'parent': 'acceso_domotica' }, {'code_menu': 'acceso_configura_domotica', 'texto_menu': 'Configurar domtica', 'href': 'configura_domotica', 'nivel': 2, 'tipo': 'Accesible', 'pos': 2, 'parent': 'acceso_domotica' } ] # Se aaden otros permisos para el usuario PERMISOS = [{'code_nombre': 'crea_grupos_domotica', 'nombre': 'Permiso para crear un grupo de dispositivos domticos', 'menu': 'acceso_grupos_domotica' }, {'code_nombre': 'borra_grupos_domotica', 'nombre': 'Permiso para borrar cualquier grupo que contiene domtica', 'menu': 'acceso_grupos_domotica' }, {'code_nombre': 'edita_grupos_domotica', 'nombre': 'Permiso para modificar cualquier grupo que contiene domtica', 'menu': 'acceso_grupos_domotica' }, {'code_nombre': 'crea_dispositivos_domotica', 'nombre': 'Permiso para crear un dispositivo domtico', 'menu': 'acceso_configura_domotica' }, {'code_nombre': 'borra_dispositivos_domotica', 'nombre': 'Permiso para borrar cualquier dispositivo domtico', 'menu': 'acceso_configura_domotica' }, {'code_nombre': 'edita_dispositivos_domotica', 'nombre': 'Permiso para editar cualquier dispositivo domtico', 'menu': 'acceso_configura_domotica' }, {'code_nombre': 'crea_secuencias_domotica', 'nombre': 'Permiso para crear una secuencia domtica', 'menu': 'acceso_configura_domotica' }, {'code_nombre': 'borra_secuencias_domotica', 'nombre': 'Permiso para borrar cualquier secuencia domtica', 'menu': 'acceso_configura_domotica' }, {'code_nombre': 'edita_secuencias_domotica', 'nombre': 'Permiso para modificar cualquier secuencia domtica', 'menu': 'acceso_configura_domotica' }, {'code_nombre': 'crea_conjuntos_domotica', 'nombre': 'Permiso para crear un conjunto de dispositivos domticos', 'menu': 'acceso_configura_domotica' }, {'code_nombre': 'borra_conjuntos_domotica', 'nombre': 'Permiso para borrar cualquier conjunto de dispositivos domticos', 'menu': 'acceso_configura_domotica' }, {'code_nombre': 'edita_conjuntos_domotica', 'nombre': 'Permiso para modificar cualquier conjunto de dispositivos domticos', 'menu': 'acceso_configura_domotica' } ]
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 51, 4061, 46, 796, 705, 19738, 540, 6, 220, 1303, 705, 35487, 6, 393, 705, 19738, 540, 4458, 220,...
1.855538
1,869
import os import cv2 import fire import time import numpy as np import torch import torch.backends.cudnn as cudnn import torch.nn.functional as F from configs.common import config as cfg from hawkdet.models.build import build_detor from hawkdet.lib.numpy_nms import np_nms from hawkdet.lib.box_utils import decode, decode_landm from hawkdet.lib.prior_box import PriorBox if __name__ == '__main__': fire.Fire({"run": run}) exit()
[ 11748, 28686, 198, 11748, 269, 85, 17, 198, 11748, 2046, 198, 11748, 640, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 1891, 2412, 13, 66, 463, 20471, 355, 269, 463, 20471, 198, 11748, 28034, 13, ...
2.847134
157
name="zhuiyue" num="123456" num=111 num3=333 str="keep going" num4=666 num5=888 num5=777 num6=999
[ 3672, 2625, 89, 13415, 7745, 518, 1, 198, 22510, 2625, 10163, 29228, 1, 198, 22510, 28, 16243, 198, 22510, 18, 28, 20370, 198, 2536, 2625, 14894, 1016, 1, 198, 22510, 19, 28, 27310, 198, 198, 22510, 20, 28, 28011, 198, 22510, 20, 28...
1.980392
51
from keydra.clients.contentful import ContentfulClient from keydra.providers.base import BaseProvider from keydra.providers.base import exponential_backoff_retry from keydra.exceptions import DistributionException from keydra.exceptions import RotationException from keydra.logging import get_logger LOGGER = get_logger() PW_FIELD = 'secret'
[ 6738, 1994, 32491, 13, 565, 2334, 13, 11299, 913, 1330, 14041, 913, 11792, 198, 198, 6738, 1994, 32491, 13, 15234, 4157, 13, 8692, 1330, 7308, 29495, 198, 6738, 1994, 32491, 13, 15234, 4157, 13, 8692, 1330, 39682, 62, 1891, 2364, 62, ...
3.515152
99
# Generated by Django 2.2.13 on 2021-02-11 13:07 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 1485, 319, 33448, 12, 2999, 12, 1157, 1511, 25, 2998, 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
from requests import Session from requests.adapters import HTTPAdapter from urllib3 import Retry from sahyun_bot.utils_logging import HttpDump DEFAULT_RETRY_COUNT = 3 RETRY_ON_METHOD = frozenset([ 'HEAD', 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'TRACE' ]) RETRY_ON_STATUS = frozenset([ 403, 429, 500, 502, 503, 504 ])
[ 6738, 7007, 1330, 23575, 198, 6738, 7007, 13, 324, 12126, 1330, 14626, 47307, 198, 6738, 2956, 297, 571, 18, 1330, 4990, 563, 198, 198, 6738, 473, 12114, 403, 62, 13645, 13, 26791, 62, 6404, 2667, 1330, 367, 29281, 35, 931, 198, 198, ...
2.589147
129
import json import requests from datetime import datetime, timedelta from BookCirculation import BookCirculation from DAO.AbstractDAO import AbstractDAO from DAO.BookDAO import BookDAO from DAO.UserDAO import UserDAO from constant import * from datetime import datetime if __name__ == "__main__": bookCirculationDAO = BookCirculationDAO() for circulation in bookCirculationDAO.getAllCirculations(): print(str(circulation))
[ 11748, 33918, 198, 11748, 7007, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 198, 6738, 4897, 31560, 1741, 1330, 4897, 31560, 1741, 198, 6738, 17051, 46, 13, 23839, 5631, 46, 1330, 27741, 5631, 46, 198, 6738, 17051, 46, 13...
3.300752
133
#!/usr/bin/env python # -*- coding: utf-8 -*- # Common Python library imports import os # Pip package imports from six.moves.urllib.parse import urljoin from flask import url_for, request, abort from werkzeug import secure_filename, FileStorage, cached_property # Internal package imports from flask_mm.utils import UuidNameGen from flask_mm.files import extension, lower_extension from flask_mm.storages import BaseStorage DEFAULT_MANAGER = 'file'
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 8070, 11361, 5888, 17944, 198, 11748, 28686, 198, 198, 2, 25149, 5301, 17944, 198, 6738, 2237, 13, 76, 5241, ...
3.266187
139
from functools import partial from marshmallow import ValidationError from web.extensions import db from .validators import validate_user_token from .serializers import SuperUserSchema from .exceptions import InvalidUsage from .user import SuperUser def delete_superuser(id, created_at_timestamp): """ Delete a user record from the SuperUser table For added security, must provide exact creation datetime of the user, in timestamp format """ s_user = SuperUser.get_by_id(id) validate_user_token(s_user, created_at_timestamp) s_user.delete() db.session.commit() return s_user.email, True
[ 6738, 1257, 310, 10141, 1330, 13027, 198, 6738, 22397, 42725, 1330, 3254, 24765, 12331, 198, 6738, 3992, 13, 2302, 5736, 1330, 20613, 198, 6738, 764, 12102, 2024, 1330, 26571, 62, 7220, 62, 30001, 198, 6738, 764, 46911, 11341, 1330, 3115,...
3.214286
196
''' Registers auxillary encodings in the codecs module. >>> 'x\x9cK\xc9L/N\xaa\x04\x00\x08\x9d\x02\x83'.decode('zip') 'digsby' ''' from peak.util.imports import lazyModule sys = lazyModule('sys') warnings = lazyModule('warnings') locale = lazyModule('locale') collections = lazyModule('collections') urllib = lazyModule('urllib') urllib2 = lazyModule('urllib2') codecs = lazyModule('codecs') StringIO = lazyModule('StringIO') zipfile = lazyModule('zipfile') gzip = lazyModule('gzip') htmlentitydefs = lazyModule('htmlentitydefs') base64 = lazyModule('base64') #pylzma = lazyModule('pylzma') HAVE_LZMA = False #until proven otherwise ENCODE_LZMA = False __simplechars_enc = { ord('<') : 'lt', ord('>') : 'gt', #ord("'") : 'apos', ord('"') : 'quot', ord('&') : 'amp', } __simplechars_dec = dict((v, unichr(k)) for k,v in __simplechars_enc.items()) __simplechars_dec['apos'] = unichr(ord("'")) _encodings = [ lambda: locale.getpreferredencoding(), lambda: sys.getfilesystemencoding(), lambda: sys.getdefaultencoding(), ] _to_register = [ ] def register_codec(name, encode, decode): 'An easy way to register a pair of encode/decode functions with a name.' global _to_register _to_register.append(_search) def fuzzydecode(s, encoding = None, errors = 'strict'): ''' Try decoding the string using several encodings, in this order. - the one(s) you give as "encoding" - the system's "preferred" encoding ''' if isinstance(s, unicode): import warnings; warnings.warn('decoding unicode is not supported!') return s encodings = [enc() for enc in _encodings] if isinstance(encoding, basestring): encodings.insert(0, encoding) elif encoding is None: pass else: encodings = list(encoding) + encodings assert all(isinstance(e, basestring) for e in encodings) for e in encodings: try: res = s.decode(e, errors) except (UnicodeDecodeError, LookupError), _ex: # LookupError will catch missing encodings import warnings; warnings.warn("Exception when fuzzydecoding %r: %r" % (s, _ex)) else: return res return s.decode(encoding, 'replace') register_codec('xml', _xml_encode, _xml_decode) _to_register.append(search) del search _to_register.append(search) del search _to_register.append(search) del search __locale_encoding = lambda: locale.getpreferredencoding() register_codec('locale', lambda s, errors = 'strict': (s.encode(__locale_encoding()), len(s)), lambda s, errors = 'strict': (s.decode(__locale_encoding()), len(s))) __filesysencoding = lambda: sys.getfilesystemencoding() register_codec('filesys', _filesys_encode, _filesys_decode) del _filesys_encode del _filesys_decode register_codec('url', _url_encode, _url_decode) # codec: utf8url # encode = utf8 encode -> url encode # decode = url decode -> utf8 decode register_codec('utf8url', _utf8url_encode, _utf8url_decode) b64_codecs = {} b64_names = frozenset(('b64', 'b32', 'b16')) _to_register.append(search_base64) del search_base64 register_codec('binary', _binary_encode, _binary_decode) __all__ = [] if __name__ == '__main__': install() strings = [gen_rand_str() for x in xrange(100)] results1 = [] results2 = [] from time import clock print 'xml', timeit(lambda: foo('xml', results1)) print 'xml2', timeit(lambda: foo('xml2', results2)) assert results1 == results2
[ 7061, 6, 201, 198, 8081, 6223, 27506, 15856, 2207, 375, 654, 287, 262, 40481, 82, 8265, 13, 201, 198, 201, 198, 33409, 705, 87, 59, 87, 24, 66, 42, 59, 25306, 24, 43, 14, 45, 59, 87, 7252, 59, 87, 3023, 59, 87, 405, 59, 87, ...
2.161846
1,798
from ._factor_base import FactorBase from ._factor_stack import FactorStack from ._stacked_factor_graph import StackedFactorGraph from ._storage_metadata import StorageMetadata from ._variable_assignments import VariableAssignments from ._variables import RealVectorVariable, VariableBase __all__ = [ "FactorStack", "FactorBase", "StackedFactorGraph", "StorageMetadata", "VariableAssignments", "RealVectorVariable", "VariableBase", ]
[ 6738, 47540, 31412, 62, 8692, 1330, 27929, 14881, 198, 6738, 47540, 31412, 62, 25558, 1330, 27929, 25896, 198, 6738, 47540, 301, 6021, 62, 31412, 62, 34960, 1330, 520, 6021, 41384, 37065, 198, 6738, 47540, 35350, 62, 38993, 1330, 20514, 9...
3.355072
138
# coding=utf-8 import cyfib
[ 2, 19617, 28, 40477, 12, 23, 198, 11748, 3075, 69, 571, 628 ]
2.416667
12
#!/usr/bin/env python3 from http.server import SimpleHTTPRequestHandler, HTTPServer from urllib.parse import parse_qs import time if __name__ == "__main__": from sys import argv if len(argv) == 3: run(port = int(argv[1]), hostName = str(argv[2])) elif len(argv) == 2: run(port = int(argv[1])) else: run()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 6738, 2638, 13, 15388, 1330, 17427, 40717, 18453, 25060, 11, 38288, 18497, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 21136, 62, 48382, 198, 11748, 640, 198, 198, 361, 11593, ...
2.465116
129
import os from datetime import datetime, timedelta from airflow import DAG from airflow.operators.docker_operator import DockerOperator from docker.types import Mount default_args = { "owner": "airflow", "description": "Use of the DockerOperator", "depend_on_past": False, "start_date": datetime(2021, 5, 1), "email_on_failure": False, "email_on_retry": False, "retries": 1, "retry_delay": timedelta(minutes=5), } BASE_DIR = "/home/baris/PROJECTS/sncf_forecast/" dic_env = { "API_KEY": os.environ["API_KEY"], "API_KEY_SECRET": os.environ["API_KEY_SECRET"], "ACCESS_TOKEN": os.environ["ACCESS_TOKEN"], "ACCESS_TOKEN_SECRET": os.environ["ACCESS_TOKEN_SECRET"], "MONGODB_HOST": os.environ["MONGODB_HOST"], "MONGODB_PORT": os.environ["MONGODB_PORT"], "MONGO_INITDB_ROOT_USERNAME": os.environ["MONGO_INITDB_ROOT_USERNAME"], "MONGO_INITDB_ROOT_PASSWORD": os.environ["MONGO_INITDB_ROOT_PASSWORD"], } with DAG("daily_update_new", default_args=default_args, schedule_interval="0 2 * * *", catchup=False) as dag: update_db = DockerOperator( task_id="task_____daily_update_dbmongo", image="sncf_forecast_update", environment=dic_env, container_name="task_____daily_update_dbmongo", api_version="auto", auto_remove=True, command="python3 /workdir/update.py", docker_url="unix://var/run/docker.sock", working_dir="/workdir", mount_tmp_dir=False, mounts=[ Mount(source=BASE_DIR + "shared", target="/workdir/shared", type="bind"), Mount(source=BASE_DIR + "backend/modeling/src", target="/workdir/src", type="bind"), Mount(source=BASE_DIR + "backend/update", target="/workdir", type="bind"), ], network_mode="sncf_forecast_default", ) update_lstm = DockerOperator( task_id="task_____daily_update_lstm", image="sncf_forecast_modeling", environment=dic_env, container_name="task_____daily_update_lstm", api_version="auto", auto_remove=True, command="python3 /workdir/bin/train_model.py -m lstm", docker_url="unix://var/run/docker.sock", working_dir="/workdir", mount_tmp_dir=False, mounts=[ Mount(source=BASE_DIR + "backend/modeling/bin", target="/workdir/bin", type="bind"), Mount(source=BASE_DIR + "backend/modeling/src", target="/workdir/src", type="bind"), Mount(source=BASE_DIR + "shared", target="/workdir/shared", type="bind"), Mount(source=BASE_DIR + "mlflow/db", target="/workdir/data", type="bind"), Mount(source=BASE_DIR + "mlflow/artifacts", target="/workdir/artifacts", type="bind"), ], network_mode="sncf_forecast_default", ) update_baseline = DockerOperator( task_id="task_____daily_update_baseline", image="sncf_forecast_modeling", environment=dic_env, container_name="task_____daily_update_baseline", api_version="auto", auto_remove=True, command="python3 /workdir/bin/train_model.py -m baseline", docker_url="unix://var/run/docker.sock", working_dir="/workdir", mount_tmp_dir=False, mounts=[ Mount(source=BASE_DIR + "backend/modeling/bin", target="/workdir/bin", type="bind"), Mount(source=BASE_DIR + "backend/modeling/src", target="/workdir/src", type="bind"), Mount(source=BASE_DIR + "shared", target="/workdir/shared", type="bind"), Mount(source=BASE_DIR + "mlflow/db", target="/workdir/data", type="bind"), Mount(source=BASE_DIR + "mlflow/artifacts", target="/workdir/artifacts", type="bind"), ], network_mode="sncf_forecast_default", ) update_autoencoder = DockerOperator( task_id="task_____daily_update_autoencoder", image="sncf_forecast_modeling", environment=dic_env, container_name="task_____daily_update_autoencoder", api_version="auto", auto_remove=True, command="python3 /workdir/bin/train_model.py -m autoencoder", docker_url="unix://var/run/docker.sock", working_dir="/workdir", mount_tmp_dir=False, mounts=[ Mount(source=BASE_DIR + "backend/modeling/bin", target="/workdir/bin", type="bind"), Mount(source=BASE_DIR + "backend/modeling/src", target="/workdir/src", type="bind"), Mount(source=BASE_DIR + "shared", target="/workdir/shared", type="bind"), Mount(source=BASE_DIR + "mlflow/db", target="/workdir/data", type="bind"), Mount(source=BASE_DIR + "mlflow/artifacts", target="/workdir/artifacts", type="bind"), ], network_mode="sncf_forecast_default", ) update_db >> update_lstm update_db >> update_baseline update_db >> update_autoencoder
[ 11748, 28686, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 198, 198, 6738, 45771, 1330, 360, 4760, 198, 6738, 45771, 13, 3575, 2024, 13, 45986, 62, 46616, 1330, 25716, 18843, 1352, 198, 6738, 36253, 13, 19199, 1330, 5628, ...
2.254019
2,177
from django.http import JsonResponse from django.http import HttpResponse from rest_framework.views import APIView from .store_population import StorePopulation import time as processTiming import uuid # API to fetch Ireland population used by frontend. The result consist of population estimate and year. # API to fetch Dublin population used by frontend. The result consist of population estimate and year.
[ 6738, 42625, 14208, 13, 4023, 1330, 449, 1559, 31077, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 198, 6738, 1334, 62, 30604, 13, 33571, 1330, 3486, 3824, 769, 198, 6738, 764, 8095, 62, 39748, 1330, 9363, 45251, 198, 117...
4.361702
94
# -*- coding: utf-8 -*- """ This script shows how to embed the animation into a background image (it's also possible to embed the animation into another animation, but that's too complicated to implement in a simple program ...) """ from colorsys import hls_to_rgb import gifmaze as gm from gifmaze.algorithms import wilson, bfs from gifmaze.utils import generate_text_mask # firstly define the size and color_depth of the image. width, height = 600, 400 color_depth = 8 # define a surface to draw on. surface = gm.GIFSurface.from_image('teacher.png', color_depth) # set the 0-th color to be the same with the blackboard's. palette = [52, 51, 50, 200, 200, 200, 255, 0, 255] for i in range(256): rgb = hls_to_rgb((i / 360.0) % 1, 0.5, 1.0) palette += [int(round(255 * x)) for x in rgb] surface.set_palette(palette) # next define an animation environment to run the algorithm. anim = gm.Animation(surface) # set the speed, delay, and transparent color we want. anim.set_control(speed=50, delay=2, trans_index=3) # add a maze instance. mask = generate_text_mask(surface.size, 'UST', 'ubuntu.ttf', 350) # specify the region that where the animation is embedded. left, top, right, bottom = 66, 47, 540, 343 maze = anim.create_maze_in_region(cell_size=4, region=(left, top, right, bottom), mask=mask) anim.pad_delay_frame(100) # paint the blackboard surface.rectangle(left, top, right - left + 1, bottom - top + 1, 0) # in the first algorithm only 4 colors occur in the image, so we can use # a smaller minimum code length, this can help reduce the file size significantly. surface.set_lzw_compress(2) # pad one second delay, get ready! anim.pad_delay_frame(100) # the animation runs here. wilson(maze, root=(0, 0)) # pad three seconds delay to see the result clearly. anim.pad_delay_frame(300) # now we run the maze solving algorithm. # this time we use full 256 colors, hence the minimum code length is 8. surface.set_lzw_compress(8) # the tree and wall are unchanged throughout the maze solving algorithm hence # it's safe to use 0 as the transparent color and color the wall and tree transparent. anim.set_colormap({0: 0, 1: 0, 2: 2, 3: 3}) anim.set_control(speed=30, delay=5, trans_index=0) # run the maze solving algorithm. bfs(maze, start=(0, 0), end=(maze.size[0] - 1, maze.size[1] - 1)) # pad five seconds delay to see the path clearly. anim.pad_delay_frame(500) # save the result. surface.save('wilson_bfs.gif') surface.close()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 1212, 4226, 2523, 703, 284, 11525, 262, 11034, 656, 257, 198, 25249, 2939, 357, 270, 338, 635, 1744, 284, 11525, 262, 11034, 198, 20424, 1194, 11034, 11, 475...
2.839866
893