content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
# -*- coding: utf-8 -*- ''' author: Soizic Laguitton organization: I2BM, Neurospin, Gif-sur-Yvette, France organization: CATI, France organization: IFR 49 License: `CeCILL version 2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.html>`_ ''' # # Soma-workflow constants # # ''' Job status: ''' NOT_SUBMITTED = "not_submitted" UNDETERMINED = "undetermined" QUEUED_ACTIVE = "queued_active" SYSTEM_ON_HOLD = "system_on_hold" USER_ON_HOLD = "user_on_hold" USER_SYSTEM_ON_HOLD = "user_system_on_hold" RUNNING = "running" SYSTEM_SUSPENDED = "system_suspended" USER_SUSPENDED = "user_suspended" USER_SYSTEM_SUSPENDED = "user_system_suspended" DONE = "done" FAILED = "failed" DELETE_PENDING = "delete_pending" KILL_PENDING = "kill_pending" SUBMISSION_PENDING = "submission_pending" WARNING = "warning" JOB_STATUS = [NOT_SUBMITTED, UNDETERMINED, QUEUED_ACTIVE, SYSTEM_ON_HOLD, USER_ON_HOLD, USER_SYSTEM_ON_HOLD, RUNNING, SYSTEM_SUSPENDED, USER_SUSPENDED, USER_SYSTEM_SUSPENDED, DONE, FAILED, DELETE_PENDING, KILL_PENDING, SUBMISSION_PENDING, WARNING] ''' Exit job status: ''' EXIT_UNDETERMINED = "exit_status_undetermined" EXIT_ABORTED = "aborted" EXIT_NOTRUN = "aborted_before_running" FINISHED_REGULARLY = "finished_regularly" FINISHED_TERM_SIG = "finished_signal" FINISHED_UNCLEAR_CONDITIONS = "finished_unclear_condition" USER_KILLED = "killed_by_user" JOB_EXIT_STATUS = [EXIT_UNDETERMINED, EXIT_ABORTED, FINISHED_REGULARLY, FINISHED_TERM_SIG, FINISHED_UNCLEAR_CONDITIONS, USER_KILLED, EXIT_NOTRUN] ''' File transfer status: ''' FILES_DO_NOT_EXIST = "do not exist" FILES_ON_CLIENT = "on client side" FILES_ON_CR = "on computing resource side" FILES_ON_CLIENT_AND_CR = "on both sides" TRANSFERING_FROM_CLIENT_TO_CR = "transfering client->cr" TRANSFERING_FROM_CR_TO_CLIENT = "transfering cr->client" FILES_UNDER_EDITION = "under edition" FILE_TRANSFER_STATUS = [FILES_DO_NOT_EXIST, FILES_ON_CLIENT, FILES_ON_CR, FILES_ON_CLIENT_AND_CR, TRANSFERING_FROM_CLIENT_TO_CR, TRANSFERING_FROM_CR_TO_CLIENT, FILES_UNDER_EDITION] ''' Transfer type ''' TR_FILE_C_TO_CR = "file transfer form client to cr" TR_DIR_C_TO_CR = "dir transfer from client to cr" TR_MFF_C_TO_CR = "multi file format from client to cr" TR_FILE_CR_TO_C = "file transfer form cr to client" TR_DIR_CR_TO_C = "dir transfer from cr to client" TR_MFF_CR_TO_C = "multi file format from cr to client" TRANSFER_TYPES = [TR_FILE_C_TO_CR, TR_DIR_C_TO_CR, TR_MFF_C_TO_CR, TR_FILE_CR_TO_C, TR_DIR_CR_TO_C, TR_MFF_CR_TO_C] ''' Workflow status: ''' WORKFLOW_NOT_STARTED = "worklflow_not_started" WORKFLOW_IN_PROGRESS = "workflow_in_progress" WORKFLOW_DONE = "workflow_done" WORKFLOW_STATUS = [WORKFLOW_NOT_STARTED, WORKFLOW_IN_PROGRESS, WORKFLOW_DONE, DELETE_PENDING, WARNING]
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 7061, 6, 198, 9800, 25, 1406, 528, 291, 406, 11433, 47304, 198, 198, 9971, 1634, 25, 314, 17, 12261, 11, 13782, 39706, 11, 402, 361, 12, 11793, 12, 56, 33573, 1...
1.84199
1,829
# expected: fail # - this particular check isn't implemented yet # I would have expected this to be valid, but cPython and pypy err out saying "name 'x' is local and global" print "first" x = 1 print "calling" f(2) print x
[ 2, 2938, 25, 2038, 198, 2, 532, 428, 1948, 2198, 2125, 470, 9177, 1865, 198, 198, 2, 314, 561, 423, 2938, 428, 284, 307, 4938, 11, 475, 269, 37906, 290, 279, 4464, 88, 11454, 503, 2282, 366, 3672, 705, 87, 6, 318, 1957, 290, 329...
3.152778
72
res_words = [] seps = [] ops = []
[ 198, 411, 62, 10879, 796, 17635, 198, 325, 862, 796, 17635, 198, 2840, 796, 17635, 628, 198 ]
2.176471
17
# encoding=utf-8 """ Auth: coco369 Email: 779598160@qq.com CreateTime: 2021/07/30 Desc: fastspider, Item """
[ 2, 21004, 28, 40477, 12, 23, 198, 37811, 198, 30515, 25, 8954, 78, 30803, 198, 15333, 25, 767, 3720, 41292, 14198, 31, 38227, 13, 785, 198, 198, 16447, 7575, 25, 33448, 14, 2998, 14, 1270, 198, 198, 24564, 25, 3049, 2777, 1304, 11, ...
2.354167
48
#!/usr/bin/env python # # Public Domain 2014-present MongoDB, Inc. # Public Domain 2008-2014 WiredTiger, Inc. # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as a compiled # binary, for any purpose, commercial or non-commercial, and by any # means. # # In jurisdictions that recognize copyright laws, the author or authors # of this software dedicate any and all copyright interest in the # software to the public domain. We make this dedication for the benefit # of the public at large and to the detriment of our heirs and # successors. We intend this dedication to be an overt act of # relinquishment in perpetuity of all present and future rights to this # software under copyright law. # # 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 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. # # [TEST_TAGS] # ignored_file # [END_TAGS] # # run.py # Command line test runner # from __future__ import print_function import glob, json, os, random, re, sys if sys.version_info[0] <= 2: print('WiredTiger requires Python version 3.0 or above') sys.exit(1) # Set paths suitedir = sys.path[0] wt_disttop = os.path.dirname(os.path.dirname(suitedir)) wt_3rdpartydir = os.path.join(wt_disttop, 'test', '3rdparty') # Check for a local build that contains the wt utility. First check if the # supplied an explicit build directory ('WT_BUILDDIR'), then the current # working directory, and finally in the disttop directory. # This isn't ideal - if a user has multiple builds in a tree we # could pick the wrong one. We also need to account for the fact that there # may be an executable 'wt' file the build directory. env_builddir = os.getenv('WT_BUILDDIR') curdir = os.getcwd() if env_builddir and os.path.isfile(os.path.join(env_builddir, 'wt')): wt_builddir = env_builddir elif os.path.isfile(os.path.join(curdir, 'wt')): wt_builddir = curdir elif os.path.isfile(os.path.join(curdir, 'wt.exe')): wt_builddir = curdir elif os.path.isfile(os.path.join(wt_disttop, 'wt')): wt_builddir = wt_disttop elif os.path.isfile(os.path.join(wt_disttop, 'wt.exe')): wt_builddir = wt_disttop else: print('Unable to find useable WiredTiger build') sys.exit(1) # Cannot import wiredtiger and supporting utils until we set up paths # We want our local tree in front of any installed versions of WiredTiger. # Don't change sys.path[0], it's the dir containing the invoked python script. sys.path.insert(1, os.path.join(wt_builddir, 'lang', 'python')) # Append to a colon separated path in the environment # If we built with libtool, explicitly put its install directory in our library # search path. This only affects library loading for subprocesses, like 'wt'. libsdir = os.path.join(wt_builddir, '.libs') if os.path.isdir(libsdir): append_env_path('LD_LIBRARY_PATH', libsdir) if sys.platform == "darwin": append_env_path('DYLD_LIBRARY_PATH', libsdir) # Add all 3rd party directories: some have code in subdirectories for d in os.listdir(wt_3rdpartydir): for subdir in ('lib', 'python', ''): if os.path.exists(os.path.join(wt_3rdpartydir, d, subdir)): sys.path.insert(1, os.path.join(wt_3rdpartydir, d, subdir)) break # unittest will be imported later, near to when it is needed. unittest = None # Find an executable of the given name in the execution path. # Follow a symbolic link, returning the target # Find all instances of a filename under a directory # Show an environment variable if verbose enough. # capture the category (AKA 'subsuite') part of a test name, # e.g. test_util03 -> util reCatname = re.compile(r"test_([^0-9]+)[0-9]*") # Look for a list of the form 0-9,11,15-17. def configRecord(cmap, tup): """ Records this tuple in the config. It is marked as None (appearing as null in json), so it can be easily adjusted in the output file. """ tuplen = len(tup) pos = 0 for name in tup: last = (pos == tuplen - 1) pos += 1 if not name in cmap: if last: cmap[name] = {"run":None} else: cmap[name] = {"run":None, "sub":{}} if not last: cmap = cmap[name]["sub"] def configGet(cmap, tup): """ Answers the question, should we do this test, given this config file? Following the values of the tuple through the map, returning the first non-null value. If all values are null, return True (handles tests that may have been added after the config was generated). """ for name in tup: if not name in cmap: return True run = cmap[name]["run"] if "run" in cmap[name] else None if run != None: return run cmap = cmap[name]["sub"] if "sub" in cmap[name] else {} return True if __name__ == '__main__': # Turn numbers and ranges into test module names preserve = timestamp = debug = dryRun = gdbSub = lldbSub = longtest = zstdtest = ignoreStdout = False removeAtStart = True asan = False parallel = 0 random_sample = 0 batchtotal = batchnum = 0 seed = seedw = seedz = 0 configfile = None configwrite = False dirarg = None scenario = '' verbose = 1 args = sys.argv[1:] testargs = [] hook_names = [] while len(args) > 0: arg = args.pop(0) from unittest import defaultTestLoader as loader # Command line options if arg[0] == '-': option = arg[1:] if option == '-asan': asan = True continue if option == '-batch' or option == 'b': if batchtotal != 0 or len(args) == 0: usage() sys.exit(2) # Batch expects an argument that has int slash int. # For example "-b 4/12" try: left, right = args.pop(0).split('/') batchnum = int(left) batchtotal = int(right) except: print('batch argument should be nnn/nnn') usage() sys.exit(2) if batchtotal <= 0 or batchnum < 0 or batchnum >= batchtotal: usage() sys.exit(2) continue if option == '-dir' or option == 'D': if dirarg != None or len(args) == 0: usage() sys.exit(2) dirarg = args.pop(0) continue if option == '-debug' or option == 'd': debug = True continue if option == '-dry-run' or option == 'n': dryRun = True continue if option == '-gdb' or option == 'g': gdbSub = True continue if option == '-lldb': lldbSub = True continue if option == '-help' or option == 'h': usage() sys.exit(0) if option == '-hook': if len(args) == 0: usage() sys.exit(2) hook_names.append(args.pop(0)) continue if option == '-long' or option == 'l': longtest = True continue if option == '-zstd' or option == 'z': zstdtest = True continue if option == '-noremove': removeAtStart = False continue if option == '-random-sample' or option == 'r': if len(args) == 0: usage() sys.exit(2) random_sample = int(args.pop(0)) if random_sample < 2 or random_sample > 1000: usage() sys.exit(2) continue if option == '-parallel' or option == 'j': if parallel != 0 or len(args) == 0: usage() sys.exit(2) parallel = int(args.pop(0)) continue if option == '-preserve' or option == 'p': preserve = True continue if option == '-scenario' or option == 's': if scenario != '' or len(args) == 0: usage() sys.exit(2) scenario = args.pop(0) continue if option == '-timestamp' or option == 't': timestamp = True continue if option == '-verbose' or option == 'v': if len(args) == 0: usage() sys.exit(2) verbose = int(args.pop(0)) if verbose > 3: verbose = 3 if verbose < 0: verbose = 0 continue if option == '--ignore-stdout' or option == 'i': ignoreStdout = True continue if option == '-config' or option == 'c': if configfile != None or len(args) == 0: usage() sys.exit(2) configfile = args.pop(0) continue if option == '-configcreate' or option == 'C': if configfile != None or len(args) == 0: usage() sys.exit(2) configfile = args.pop(0) configwrite = True continue if option == '-randomseed' or option == 'R': seedw = random.randint(1, 0xffffffff) seedz = random.randint(1, 0xffffffff) continue if option == '-seed' or option == 'S': if seed != 0 or len(args) == 0: usage() sys.exit(2) seed = args.pop(0) [seedw, seedz] = seed.split('.') if seedw == 0 or seedz == 0: usage() sys.exit(2) continue print('unknown arg: ' + arg) usage() sys.exit(2) testargs.append(arg) if asan: # To run ASAN, we need to ensure these environment variables are set: # ASAN_SYMBOLIZER_PATH full path to the llvm-symbolizer program # LD_LIBRARY_PATH includes path with wiredtiger shared object # LD_PRELOAD includes the ASAN runtime library # # Note that LD_LIBRARY_PATH has already been set above. The trouble with # simply setting these variables in the Python environment is that it's # too late. LD_LIBRARY_PATH is commonly cached by the shared library # loader at program startup, and that's already been done before Python # begins execution. Likewise, any preloading indicated by LD_PRELOAD # has already been done. # # Our solution is to set the variables as appropriate, and then restart # Python with the same argument list. The shared library loader will # have everything it needs on the second go round. # # Note: If the ASAN stops the program with the error: # Shadow memory range interleaves with an existing memory mapping. # ASan cannot proceed correctly. # # try rebuilding with the clang options: # "-mllvm -asan-force-dynamic-shadow=1" # and make sure that clang is used for all compiles. # # We'd like to show this as a message, but there's no good way to # detect this error from here short of capturing/parsing all output # from the test run. ASAN_ENV = "__WT_TEST_SUITE_ASAN" # if set, we've been here before ASAN_SYMBOLIZER_PROG = "llvm-symbolizer" ASAN_SYMBOLIZER_ENV = "ASAN_SYMBOLIZER_PATH" LD_PRELOAD_ENV = "LD_PRELOAD" SO_FILE_NAME = "libclang_rt.asan-x86_64.so" if not os.environ.get(ASAN_ENV): if verbose >= 2: print('Enabling ASAN environment and rerunning python') os.environ[ASAN_ENV] = "1" show_env(verbose, "LD_LIBRARY_PATH") if not os.environ.get(ASAN_SYMBOLIZER_ENV): os.environ[ASAN_SYMBOLIZER_ENV] = which(ASAN_SYMBOLIZER_PROG) if not os.environ.get(ASAN_SYMBOLIZER_ENV): error(ASAN_SYMBOLIZER_ENV, 'symbolizer program not found in PATH') show_env(verbose, ASAN_SYMBOLIZER_ENV) if not os.environ.get(LD_PRELOAD_ENV): symbolizer = follow_symlinks(os.environ[ASAN_SYMBOLIZER_ENV]) bindir = os.path.dirname(symbolizer) sofiles = [] if os.path.basename(bindir) == 'bin': libdir = os.path.join(os.path.dirname(bindir), 'lib') sofiles = find(libdir, SO_FILE_NAME) if len(sofiles) != 1: if len(sofiles) == 0: fmt = 'ASAN shared library file not found.\n' + \ 'Set {} to the file location and rerun.' error(3, SO_FILE_NAME, fmt.format(LD_PRELOAD_ENV)) else: fmt = 'multiple ASAN shared library files found\n' + \ 'under {}, expected just one.\n' + \ 'Set {} to the correct file location and rerun.' error(3, SO_FILE_NAME, fmt.format(libdir, LD_PRELOAD_ENV)) os.environ[LD_PRELOAD_ENV] = sofiles[0] show_env(verbose, LD_PRELOAD_ENV) # Restart python! python = sys.executable os.execl(python, python, *sys.argv) elif verbose >= 2: print('Python restarted for ASAN') # We don't import wttest until after ASAN environment variables are set. import wttest # Use the same version of unittest found by wttest.py unittest = wttest.unittest tests = unittest.TestSuite() from testscenarios.scenarios import generate_scenarios import wthooks hookmgr = wthooks.WiredTigerHookManager(hook_names) # All global variables should be set before any test classes are loaded. # That way, verbose printing can be done at the class definition level. wttest.WiredTigerTestCase.globalSetup(preserve, removeAtStart, timestamp, gdbSub, lldbSub, verbose, wt_builddir, dirarg, longtest, zstdtest, ignoreStdout, seedw, seedz, hookmgr) # Without any tests listed as arguments, do discovery if len(testargs) == 0: if scenario != '': sys.stderr.write( 'run.py: specifying a scenario requires a test name\n') usage() sys.exit(2) from discover import defaultTestLoader as loader suites = loader.discover(suitedir) # If you have an empty Python file, it comes back as an empty entry in suites # and then the sort explodes. Drop empty entries first. Note: this converts # suites to a list, but the sort does that anyway. Also note: there seems to be # no way to count other than iteration; there's a count method but it also # returns zero for test files that contain a test class with no test functions, # and it's not clear that dropping those here is correct. suites = [s for s in suites if not isempty(s)] suites = sorted(suites, key=lambda c: str(list(c)[0])) if configfile != None: suites = configApply(suites, configfile, configwrite) tests.addTests(restrictScenario(generate_scenarios(suites), '')) else: for arg in testargs: testsFromArg(tests, loader, arg, scenario) tests = hookmgr.filter_tests(tests) # Shuffle the tests and create a new suite containing every Nth test from # the original suite if random_sample > 0: random_sample_tests = [] for test in tests: random_sample_tests.append(test) random.shuffle(random_sample_tests) tests = unittest.TestSuite(random_sample_tests[::random_sample]) if debug: import pdb pdb.set_trace() if batchtotal != 0: # For test batching, we want to split up all the tests evenly, and # spread out the tests, so each batch contains tests of all kinds. We'd # like to prioritize the lowest scenario numbers first, so if there's a # failure, we won't have to do all X thousand of some test's scenarios # before we see a failure in the next test. To that end, we define a # sort function that sorts by scenario first, and test name second. hugetests = set() all_tests = sorted(tests, key = get_sort_keys) if not longtest: for name in hugetests: print("WARNING: huge test " + name + " has > 1000 scenarios.\n" + "That is only appropriate when using the --long option.\n" + "The number of scenarios for the test should be pruned") # At this point we have an ordered list of all the tests. # Break it into just our batch. tests = unittest.TestSuite(all_tests[batchnum::batchtotal]) if dryRun: for line in tests: print(line) else: result = wttest.runsuite(tests, parallel) sys.exit(0 if result.wasSuccessful() else 1) sys.exit(0)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 5094, 20021, 1946, 12, 25579, 42591, 11012, 11, 3457, 13, 198, 2, 5094, 20021, 3648, 12, 4967, 39721, 51, 8254, 11, 3457, 13, 198, 2, 198, 2, 770, 318, 1479, 290, 555, ...
2.155972
8,431
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'SumDialog.ui' # # Created by: PyQt5 UI code generator 5.15.0 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets from SumAllTable import DataGridAll
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 5178, 7822, 7560, 422, 3555, 334, 72, 2393, 705, 13065, 44204, 13, 9019, 6, 198, 2, 198, 2, 15622, 416, 25, 9485, 48, 83, 20, 12454, 2438, 17301, 642, 13, ...
3.117647
119
from dataclasses import dataclass, field from typing import Optional from .t_expression import TExpression from .t_gateway import TGateway __NAMESPACE__ = "http://www.omg.org/spec/BPMN/20100524/MODEL"
[ 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 11, 2214, 198, 6738, 19720, 1330, 32233, 198, 6738, 764, 83, 62, 38011, 1330, 309, 16870, 2234, 198, 6738, 764, 83, 62, 10494, 1014, 1330, 309, 22628, 1014, 198, 198, 834, 45, 29559, 47,...
2.942029
69
# -*- coding: utf-8 -*- __author__ = 'M.Novikov' from model.project import Project # Mantis from pony.orm import * # from pymysql.converters import decoders #
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 834, 9800, 834, 796, 705, 44, 13, 20795, 1134, 709, 6, 198, 198, 6738, 2746, 13, 16302, 1330, 4935, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
1.510101
198
# Generated by Django 2.1.7 on 2019-02-23 18:47 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 22, 319, 13130, 12, 2999, 12, 1954, 1248, 25, 2857, 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 bs4 import BeautifulSoup from threading import Thread import requests from urllib.parse import urlparse,urljoin from urllib import parse
[ 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 6738, 4704, 278, 1330, 14122, 198, 11748, 7007, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 19016, 29572, 11, 6371, 22179, 198, 6738, 2956, 297, 571, 1330, 21136, 628 ]
3.763158
38
from factories.celery import create_celery from factories.application import create_application celery = create_celery(create_application())
[ 6738, 17590, 13, 7015, 88, 1330, 2251, 62, 7015, 88, 198, 6738, 17590, 13, 31438, 1330, 2251, 62, 31438, 198, 198, 7015, 88, 796, 2251, 62, 7015, 88, 7, 17953, 62, 31438, 28955 ]
4.272727
33
# MIT License # # Copyright (c) 2020 Anderson Vitor Bento # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import tkinter as tk from tkinter.scrolledtext import ScrolledText from simublocks.dialog.dialogTools import dialogTools
[ 2, 17168, 13789, 198, 2, 198, 2, 15069, 357, 66, 8, 12131, 9918, 569, 2072, 20421, 78, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 2, 286, 428, 3788, 290, 3917, 1...
3.791411
326
import socket import os from _thread import start_new_thread ip = "localhost" port = 1234 global number_of_connections number_of_connections = 0 server = socket.socket() server.bind((ip, port)) server.listen(5) engine()
[ 11748, 17802, 198, 11748, 28686, 198, 6738, 4808, 16663, 1330, 923, 62, 3605, 62, 16663, 198, 220, 220, 220, 220, 220, 198, 541, 796, 366, 36750, 1, 198, 634, 796, 1105, 2682, 198, 198, 20541, 1271, 62, 1659, 62, 8443, 507, 198, 176...
2.817073
82
#coding=utf-8 import os delete_files=["RCCall.mm","RCCXCall.m"] start_key = "RCCallKit_Delete_Start" end_key = "RCCallKit_Delete_end" for root,dirs,files in os.walk("./CallKit"): for file in files: if file in delete_files: print("will delete %s" % file) delete_used(os.path.join(root,file))
[ 2, 66, 7656, 28, 40477, 12, 23, 198, 198, 11748, 28686, 198, 198, 33678, 62, 16624, 28, 14692, 49, 4093, 439, 13, 3020, 2430, 49, 4093, 55, 14134, 13, 76, 8973, 198, 198, 9688, 62, 2539, 796, 366, 49, 4093, 439, 20827, 62, 38727, ...
2.318182
132
#!/usr/bin/python #-*- coding: utf-8 -*- #--------------------------------------- # # Copyright(c) Aixi Wang 2014-2015 #--------------------------------------- # v1 -- initial version #--------------------------------------- #----------------------- # mail #----------------------- global mail_sender,mail_smtpserver,mail_username,mail_password global mail_enable,mail_to mail_to = 'xx@xxx.xxx' mail_username = 'xxx@xxx.xxx' mail_password = 'xxx' mail_smtpserver = 'xxx.xxx.xxx' mail_sender = 'xxx@xxx.xxx' mail_enable = 1
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 12, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 3880, 26866, 198, 2, 198, 2, 15069, 7, 66, 8, 317, 844, 72, 15233, 1946, 12, 4626, 198, 2, 3880, 26866, 198, 2, 410, ...
3.181818
165
#-*- coding:utf-8 _*- """ @author:charlesXu @file: urls.py @desc: url @time: 2019/05/10 """ # =============== # # apis # # =============== from django.urls import path from intent_rest_controller import intent_controller from entity_extraction_controller import entity_ext_controller from bot_controller import get_chat_msg # from time_convert_server import time_convert # urlpatterns = [ path('entity', entity_ext_controller), # path('intent', intent_controller), # path('chat', get_chat_msg), # chatbot path('time_convert', time_convert) # ]
[ 2, 12, 9, 12, 19617, 25, 40477, 12, 23, 4808, 9, 12, 220, 220, 198, 37811, 220, 198, 31, 9800, 25, 10641, 829, 55, 84, 198, 31, 7753, 25, 2956, 7278, 13, 9078, 220, 198, 31, 20147, 25, 19016, 198, 31, 2435, 25, 13130, 14, 2713...
2.57265
234
# (c) Copyright IBM Corp. 2021 # (c) Copyright Instana Inc. 2020 from __future__ import absolute_import import time import urllib3 import unittest import tests.apps.flask_app from ..helpers import testenv from instana.singletons import agent, tracer
[ 2, 357, 66, 8, 15069, 19764, 11421, 13, 33448, 198, 2, 357, 66, 8, 15069, 2262, 2271, 3457, 13, 12131, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 640, 198, 11748, 2956, 297, 571, 18, 198, 11748, 555, ...
3.25641
78
import math import os import random import cv2 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torchvision def box_iou(box1, box2): # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py """ Return intersection-over-union (Jaccard index) of boxes. Both sets of boxes are expected to be in (x1, y1, x2, y2) format. Arguments: box1 (Tensor[N, 4]) box2 (Tensor[M, 4]) Returns: iou (Tensor[N, M]): the NxM matrix containing the pairwise IoU values for every element in boxes1 and boxes2 """ area1 = box_area(box1.t()) area2 = box_area(box2.t()) # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2) inter = ( ( torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2]) ) .clamp(0) .prod(2) ) return inter / ( area1[:, None] + area2 - inter ) # iou = inter / (area1 + area2 - inter) def non_max_suppression( prediction, conf_thres=0.1, iou_thres=0.6, multi_label=True, classes=None, agnostic=False, ): """ Performs Non-Maximum Suppression on inference results Returns detections with shape: nx6 (x1, y1, x2, y2, conf, cls) """ # Box constraints min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height method = "merge" nc = prediction[0].shape[1] - 5 # number of classes multi_label &= nc > 1 # multiple labels per box output = [None] * len(prediction) for xi, x in enumerate(prediction): # image index, image inference # Apply conf constraint x = x[x[:, 4] > conf_thres] # Apply width-height constraint x = x[((x[:, 2:4] > min_wh) & (x[:, 2:4] < max_wh)).all(1)] # If none remain process next image if not x.shape[0]: continue # Compute conf x[..., 5:] *= x[..., 4:5] # conf = obj_conf * cls_conf # Box (center x, center y, width, height) to (x1, y1, x2, y2) box = xywh2xyxy(x[:, :4]) # Detections matrix nx6 (xyxy, conf, cls) if multi_label: i, j = (x[:, 5:] > conf_thres).nonzero().t() x = torch.cat((box[i], x[i, j + 5].unsqueeze(1), j.float().unsqueeze(1)), 1) else: # best class only conf, j = x[:, 5:].max(1) x = torch.cat((box, conf.unsqueeze(1), j.float().unsqueeze(1)), 1) # Filter by class if classes: x = x[(j.view(-1, 1) == torch.tensor(classes, device=j.device)).any(1)] # Apply finite constraint if not torch.isfinite(x).all(): x = x[torch.isfinite(x).all(1)] # If none remain process next image n = x.shape[0] # number of boxes if not n: continue # Sort by confidence # if method == 'fast_batch': # x = x[x[:, 4].argsort(descending=True)] # Batched NMS c = x[:, 5] * 0 if agnostic else x[:, 5] # classes boxes, scores = ( x[:, :4].clone() + c.view(-1, 1) * max_wh, x[:, 4], ) # boxes (offset by class), scores if method == "merge": # Merge NMS (boxes merged using weighted mean) i = torchvision.ops.boxes.nms(boxes, scores, iou_thres) if n < 1e4: # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4) # weights = (box_iou(boxes, boxes).tril_() > iou_thres) * scores.view(-1, 1) # box weights # weights /= weights.sum(0) # normalize # x[:, :4] = torch.mm(weights.T, x[:, :4]) weights = (box_iou(boxes[i], boxes) > iou_thres) * scores[ None ] # box weights x[i, :4] = torch.mm( weights / weights.sum(1, keepdim=True), x[:, :4] ).float() # merged boxes elif method == "vision": i = torchvision.ops.boxes.nms(boxes, scores, iou_thres) elif method == "fast": # FastNMS from https://github.com/dbolya/yolact iou = box_iou(boxes, boxes).triu_(diagonal=1) # upper triangular iou matrix i = iou.max(0)[0] < iou_thres output[xi] = x[i] return output
[ 11748, 10688, 198, 11748, 28686, 198, 11748, 4738, 198, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, ...
2.022844
2,145
#!/usr/bin/env python # encoding: utf-8 # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # """This module creates the flask application. """ import os import sys import argparse from alembic import command from alembic.config import Config as AlembicConfig from flask import Flask from ConfigParser import SafeConfigParser from ec2stack.controllers import * from ec2stack.core import DB from ec2stack.models import User def create_app(settings=None): """ Creates a flask application. @param settings: Settings override object. @return: The flask application. """ app = Flask(__name__) if settings: app.config.from_object(settings) else: args = _generate_args() profile = args.pop('profile') app.config['DEBUG'] = args.pop('debug') config_file = _load_config_file() database_uri = _load_database() _config_from_config_profile(config_file, profile, app) app.config['SQLALCHEMY_DATABASE_URI'] = database_uri DB.init_app(app) default_controller = __import__( 'ec2stack.controllers.' + 'default', None, None, 'DEFAULT' ) default_controller = getattr(default_controller, 'DEFAULT') app.register_blueprint(default_controller) return app def _generate_args(): """ Generate command line arguments for ec2stack-configure. @return: args. """ parser = argparse.ArgumentParser() parser.add_argument( '-p', '--profile', required=False, help='The profile to run ec2stack with, default is initial', default='initial' ) parser.add_argument( '-d', '--debug', required=False, help='Turn debug on for application', default=False ) args = parser.parse_args() return vars(args) def _load_config_file(): """ Checks that the user's configuration file exists and returns its path. @return: The path to the user's configuration file. """ config_file = os.path.join( os.path.expanduser('~'), '.ec2stack/ec2stack.conf' ) if not os.path.exists(config_file): sys.exit('No configuration found, please run ec2stack-configure') return config_file def _config_from_config_profile(config_file, profile, app): """ Configures ec2stack app based on configuration profile. @param config_file: current config file configuration. @param profile: the profile to set the attribute in. """ config = SafeConfigParser() config.read(config_file) if not config.has_section(profile): sys.exit('No profile matching ' + profile + ' found in configuration, please run ec2stack-configure -p ' + profile) for attribute in config.options(profile): app.config[attribute.upper()] = config.get(profile, attribute) instance_type_map = {} instance_section = profile + "instancemap" if config.has_section(instance_section): for attribute in config.options(instance_section): instance_type_map[attribute] = config.get( instance_section, attribute) app.config['INSTANCE_TYPE_MAP'] = instance_type_map resource_type_map = {} resource_section = profile + "resourcemap" if config.has_section(resource_section): for attribute in config.options(resource_section): resource_type_map[attribute] = config.get( resource_section, attribute) app.config['RESOURCE_TYPE_MAP '] = resource_type_map def _load_database(): """ Checks that the user's database exists and returns its uri. @return: The uri to the user's database. """ database_file = os.path.join( os.path.expanduser('~'), '.ec2stack/ec2stack.sqlite' ) if not os.path.exists(database_file): directory = os.path.join(os.path.dirname(__file__), '../migrations') config = AlembicConfig(os.path.join( directory, 'alembic.ini' )) config.set_main_option('script_location', directory) command.upgrade(config, 'head', sql=False, tag=None) return 'sqlite:///' + database_file
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 2, 198, 2, 220, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 220, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 26...
2.741111
1,800
# -*- coding:utf-8 -*- """ Test module docstring. """ import threading from typing import Type Unset = UnsetType() # pylint: disable=invalid-name
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 37811, 198, 14402, 8265, 2205, 8841, 13, 198, 37811, 198, 11748, 4704, 278, 198, 6738, 19720, 1330, 5994, 628, 198, 198, 3118, 2617, 796, 791, 2617, 6030, 3419, 220, 1303, ...
2.777778
54
""" Event handler decorators for common Lambda events """ from .api_gateway import ApiGatewayResolver from .appsync import AppSyncResolver __all__ = ["AppSyncResolver", "ApiGatewayResolver"]
[ 37811, 198, 9237, 21360, 11705, 2024, 329, 2219, 21114, 6814, 2995, 198, 37811, 198, 198, 6738, 764, 15042, 62, 10494, 1014, 1330, 5949, 72, 22628, 1014, 4965, 14375, 198, 6738, 764, 1324, 27261, 1330, 2034, 28985, 4965, 14375, 198, 198, ...
3.271186
59
import itertools as it from torch.optim import Optimizer
[ 11748, 340, 861, 10141, 355, 340, 198, 6738, 28034, 13, 40085, 1330, 30011, 7509, 198 ]
3.8
15
from tkinter import * # import expdate import mysql.connector db_connect=mysql.connector.connect(host="localhost",user="root",password="maan",database="expense") db_cursor=db_connect.cursor()
[ 6738, 256, 74, 3849, 1330, 1635, 198, 2, 1330, 1033, 4475, 198, 11748, 48761, 13, 8443, 273, 198, 9945, 62, 8443, 28, 28744, 13976, 13, 8443, 273, 13, 8443, 7, 4774, 2625, 36750, 1600, 7220, 2625, 15763, 1600, 28712, 2625, 2611, 272, ...
3.112903
62
from __future__ import division from BlackJack.UserInterface import tk from BlackJack.UserInterface import tkFont from BlackJack.UserInterface import BlackJackWindows from BlackJack.UserInterface import SelectGameType from BlackJack.UserInterface import Helpers
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 198, 6738, 2619, 14295, 13, 12982, 39317, 1330, 256, 74, 198, 6738, 2619, 14295, 13, 12982, 39317, 1330, 256, 74, 23252, 198, 6738, 2619, 14295, 13, 12982, 39317, 1330, 2619, 14295, 11209, 198, ...
4.327869
61
from .country import Country from .game import Game from .game import Bid from .user import User from .grape import Grape from .wine import Wine from .base import new_id __all__ = [ "new_id", "Country", "Game", "Grape", "User", "Wine", ]
[ 6738, 764, 19315, 1330, 12946, 198, 6738, 764, 6057, 1330, 3776, 198, 6738, 764, 6057, 1330, 43484, 198, 6738, 764, 7220, 1330, 11787, 198, 6738, 764, 70, 13484, 1330, 48315, 198, 6738, 764, 39002, 1330, 20447, 198, 6738, 764, 8692, 133...
2.63
100
import random p = str(input('digite o nome do primeiro aluno :')) s = str(input('o nome do segundo aluno :')) t = str(input('o nome do terceiro aluno :')) q = str(input('o nome do quato aluno :')) lista = [p, s, t, q] aluno = random.choice(lista) print('o aluno sorteado foi {}'.format(aluno))
[ 11748, 4738, 198, 79, 796, 965, 7, 15414, 10786, 12894, 578, 267, 299, 462, 466, 6994, 7058, 435, 36909, 1058, 6, 4008, 198, 82, 796, 965, 7, 15414, 10786, 78, 299, 462, 466, 384, 70, 41204, 435, 36909, 1058, 6, 4008, 198, 83, 796...
2.418033
122
#!/usr/bin/env python3 import gym import torch import numpy as np import multiprocessing as mp import os import pickle import sys import time import logging import cma import argparse from torchmodel import StandardFCNet def fitness_shift(x): x = np.asarray(x).flatten() ranks = np.empty(len(x)) ranks[x.argsort()] = np.arange(len(x)) ranks /= (len(x) - 1) ranks -= .5 return ranks def train(config, logger): task_queue = mp.SimpleQueue() result_queue = mp.SimpleQueue() stop = mp.Value('i', False) stats = SharedStats(config.state_dim) normalizers = [StaticNormalizer(config.state_dim) for _ in range(config.num_workers)] for normalizer in normalizers: normalizer.offline_stats.load(stats) workers = [CMAWorker(id, normalizers[id], task_queue, result_queue, stop, config) for id in range(config.num_workers)] for w in workers: w.start() opt = cma.CMAOptions() opt['tolfun'] = -config.target opt['popsize'] = config.pop_size opt['verb_disp'] = 0 opt['verb_log'] = 0 opt['maxiter'] = sys.maxsize es = cma.CMAEvolutionStrategy(config.initial_weight, config.sigma, opt) total_steps = 0 initial_time = time.time() training_rewards = [] training_steps = [] training_timestamps = [] test_mean, test_std = test(config, config.initial_weight, stats) logger.info('total steps %8d, %+4.0f(%+4.0f)' % (total_steps, test_mean, test_std)) training_rewards.append(test_mean) training_steps.append(0) training_timestamps.append(0) while True: solutions = es.ask() for id, solution in enumerate(solutions): task_queue.put((id, solution)) while not task_queue.empty(): continue result = [] while len(result) < len(solutions): if result_queue.empty(): continue result.append(result_queue.get()) result = sorted(result, key=lambda x: x[0]) total_steps += np.sum([r[2] for r in result]) cost = [r[1] for r in result] best_solution = solutions[np.argmin(cost)] elapsed_time = time.time() - initial_time test_mean, test_std = test(config, best_solution, stats) best = -np.min(cost) logger.info('total steps = %8d test = %+4.0f (%4.0f) best = %+4.0f (%+4.0f) elapased time = %4.0f sec' % (total_steps, test_mean, test_std, best, config.target, elapsed_time)) training_rewards.append(test_mean) training_steps.append(total_steps) training_timestamps.append(elapsed_time) #with open('data/%s-best_solution_%s.bin' % (TAG, config.task), 'wb') as f: # XXX gets stuck # pickle.dump(solutions[np.argmin(result)], f) if best > config.target: logger.info('Best score of %f exceeds target %f' % (best, config.target)) break if config.max_steps and total_steps > config.max_steps: logger.info('Maximum number of steps exceeded') stop.value = True break cost = fitness_shift(cost) es.tell(solutions, cost) # es.disp() for normalizer in normalizers: stats.merge(normalizer.online_stats) normalizer.online_stats.zero() for normalizer in normalizers: normalizer.offline_stats.load(stats) stop.value = True for w in workers: w.join() return [training_rewards, training_steps, training_timestamps] def test(config, solution, stats): normalizer = StaticNormalizer(config.state_dim) normalizer.offline_stats.load_state_dict(stats.state_dict()) evaluator = Evaluator(config, normalizer) evaluator.model.set_weight(solution) rewards = [] for i in range(config.test_repetitions): reward, _ = evaluator.single_run() rewards.append(reward) return np.mean(rewards), np.std(rewards) / config.repetitions def multi_runs(task, logger, runs=1): if not os.path.exists('log'): os.makedirs('log') fh = logging.FileHandler('log/%s-%s.txt' % (task.tag, task.task)) fh.setLevel(logging.DEBUG) logger.addHandler(fh) stats = [] for run in range(runs): logger.info('Run %3d/%3d' % (run+1, runs)) stats.append(train(task, logger)) with open('data/%s-stats-%s.bin' % (task.tag, task.task), 'wb') as f: pickle.dump(stats, f) if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 11550, 198, 11748, 28034, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 18540, 305, 919, 278, 355, 29034, 198, 11748, 28686, 198, 11748, 2298, 293, 198, 11748, 25064, 198, 1...
2.322564
1,919
""" """ import numpy as np def get_corrected_TMP(TMP: np.ndarray, ele_gap: float) -> np.ndarray: """ Args: TMP (np.ndarray): [] ele_gap (np.ndarray): [m] Returns: np.ndarray: [C] Notes: 0.0065/m """ return TMP + ele_gap * -0.0065
[ 37811, 198, 198, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 628, 198, 4299, 651, 62, 30283, 276, 62, 51, 7378, 7, 51, 7378, 25, 45941, 13, 358, 18747, 11, 9766, 62, 43554, 25, 12178, 8, 4613, 45941, 13, 358, 18747, 25, 198, 2...
1.861635
159
from abc import (ABC, abstractmethod) import os import rastervision as rv
[ 6738, 450, 66, 1330, 357, 24694, 11, 12531, 24396, 8, 198, 11748, 28686, 198, 198, 11748, 374, 1603, 10178, 355, 374, 85, 628, 628, 198 ]
3.16
25
import sys import os from flask import Flask, flash, redirect, render_template, request, url_for, session from flaskext.mysql import MySQL from flask_login import LoginManager from flask_bcrypt import Bcrypt from flask_session import Session from database import Database from makedb import MakeDB from helpers import generate_weekID import pymysql from boto.s3.connection import S3Connection # init flask app app = Flask(__name__) app.config['TESTING'] = False # session secret key app.secret_key = os.environ.get('SECRETKEYFLASK') # Ensure templates are auto-reloaded app.config["TEMPLATES_AUTO_RELOAD"] = True app.config["SESSION_PERMANENT"] = False app.config["SESSION_TYPE"] = "filesystem" Session(app) # Password Hashing bcrypt = Bcrypt(app) # init MySQL database mysql = MySQL() mysql.init_app(app) #Make database if not EXISTS MakeDB() if __name__ == "__main__": app.run()
[ 11748, 25064, 198, 11748, 28686, 198, 6738, 42903, 1330, 46947, 11, 7644, 11, 18941, 11, 8543, 62, 28243, 11, 2581, 11, 19016, 62, 1640, 11, 6246, 198, 6738, 781, 292, 365, 742, 13, 28744, 13976, 1330, 33476, 198, 6738, 42903, 62, 382...
3.108014
287
from django.db import models # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 201, 198, 201, 198, 2, 13610, 534, 4981, 994, 13, 201 ]
3.277778
18
#!/usr/bin/env python # coding: utf-8 # In[2]: import numpy as np import pandas as pd import random import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.keras.layers import Dense,Flatten,GlobalAveragePooling2D,Input,Lambda from tensorflow.keras.models import Model,load_model import tensorflow.keras.backend as K from tensorflow.keras.applications.vgg16 import VGG16 from tensorflow.keras.models import Sequential from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.applications.vgg16 import preprocess_input from sklearn.model_selection import train_test_split from tensorflow.keras.utils import to_categorical from sklearn.metrics import accuracy_score,confusion_matrix from skimage.color import rgb2gray import cv2 from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing import image # In[110]: # In[150]: # In[112]: # In[113]: # In[151]: test_brute_model_on_gray_scale_test_images(brute_model) # In[115]: #brute model print("/nbrute model/n") brute_model = brute_vgg16() test_brute_model_on_gray_scale_test_images(brute_model) class_accuracy_brute_model = class_wise_accuracy(brute_model) bias_metrics(class_accuracy_brute_model,brute_model) # In[40]: # In[68]: layer_names = ["block5_conv3","block4_conv2"] for l in layer_names: print("layer name:",l) make_gradCAM("/home/euclid/Desktop/Chiranjeev/DAI/Assignment_1_Q2/correct_actual7pred7.jpg",brute_model,classified="correct",layer_name=l) make_gradCAM("/home/euclid/Desktop/Chiranjeev/DAI/Assignment_1_Q2/correct_actual8pred8.jpg",brute_model,classified="correct",layer_name=l) make_gradCAM("/home/euclid/Desktop/Chiranjeev/DAI/Assignment_1_Q2/incorrect_actual3pred0.jpg",brute_model,classified="incorrect",layer_name=l) make_gradCAM("/home/euclid/Desktop/Chiranjeev/DAI/Assignment_1_Q2/incorrect_actual5pred4.jpg",brute_model,classified="incorrect",layer_name =l) # In[161]: layer_names = ["block5_conv3","block4_conv2"] for l in layer_names: print("layer name:",l) img_path1 = "/home/euclid/Desktop/Chiranjeev/DAI/Assignment_1_Q2/correct_actual7pred7.jpg" img_path2 = "/home/euclid/Desktop/Chiranjeev/DAI/Assignment_1_Q2/correct_actual8pred8.jpg" img_path3 = "/home/euclid/Desktop/Chiranjeev/DAI/Assignment_1_Q2/incorrect_actual3pred0.jpg" img_path4 = "/home/euclid/Desktop/Chiranjeev/DAI/Assignment_1_Q2/incorrect_actual5pred4.jpg" img1 = cv2.imread(img_path1) cam1 = grad_cam_pp(brute_model, img1,layer_name=l, label_name=labels,category_id=int(img_path1[-5])) plot(img1,cam1) img2 = cv2.imread(img_path2) cam2 = grad_cam_pp(brute_model, img2,layer_name=l, label_name=labels,category_id=int(img_path2[-5])) plot(img2,cam2) img3 = cv2.imread(img_path3) cam3 = grad_cam_pp(brute_model, img3,layer_name=l, label_name=labels,category_id=int(img_path3[-5])) plot(img3,cam3) img4 = cv2.imread(img_path4) cam4 = grad_cam_pp(brute_model, img4,layer_name=l, label_name=labels,category_id=int(img_path4[-5])) plot(img4,cam4) # In[162]: # In[38]: # In[39]: #preporocess model print("\npreporocess model\n") preprocessed_model = preprocessed_data_model() x_test_preprocessed,y_test_preprocessed = preprocess_helper() preprocessed_model1 = tf.keras.models.load_model("/home/euclid/Desktop/Chiranjeev/DAI/vgg16_cifar10_preprocessed_rot_new") class_accuracy_preprocessed_model1 = class_wise_accuracy_preprocess(preprocessed_model1, x_test_preprocessed,y_test_preprocessed) bias_metrics_preprocess(class_accuracy_preprocessed_model1,preprocessed_model1, x_test_preprocessed,y_test_preprocessed) create_results_preprocess(preprocessed_model1, x_test_preprocessed,y_test_preprocessed) # In[118]: # In[119]: #method model print("/nmethod model/n") kl_model = method_model() class_accuracy_kl_model = class_wise_accuracy(kl_model) bias_metrics(class_accuracy_kl_model,kl_model) create_results(kl_model) # In[120]: print("\npreprocessed model\n") class_accuracy_preprocessed = class_wise_accuracy(preprocessed_model) print("each class accuracies preprocessed",class_accuracy_preprocessed) bias_metrics(class_accuracy_preprocessed,preprocessed_model) print("\nmethod model\n") class_accuracy_method = class_wise_accuracy(kl_model) print("each class accuracies mehtod",class_accuracy_method) bias_metrics(class_accuracy_method,kl_model) # In[187]: # In[200]: print("cross entropy loss") filename1 = "/home/euclid/Desktop/Chiranjeev/DAI/Assignment_1_Q1/categorical_cross_entropy/test_gender_across_race_age_y_test_pred2_optimizer2_45.csv" dob_across_race1,dob_across_race2,dob_across_race3,dob_across_race4,dob_across_age_0_28,dob_across_age_29_56,dob_across_age_57_84,dob_across_age_85_116,dob_across_race_overall,dob_across_age_overall = check_bias_by_counting(filename1) print("\nfocal loss") filename2 = "/home/euclid/Desktop/Chiranjeev/DAI/Assignment_1_Q1/focal_loss/test_gender_across_race_age_y_test_pred2_optimizer2_45_focal_loss.csv" dob_across_race1,dob_across_race2,dob_across_race3,dob_across_race4,dob_across_age_0_28,dob_across_age_29_56,dob_across_age_57_84,dob_across_age_85_116,dob_across_race_overall,dob_across_age_overall = check_bias_by_counting(filename2) print("\nLinearsvm") filename3 = "/home/euclid/Desktop/Chiranjeev/DAI/Assignment_1_Q1/svm/test_gender_across_race_age_y_test_pred2_optimizer2_svm.csv" dob_across_race1,dob_across_race2,dob_across_race3,dob_across_race4,dob_across_age_0_28,dob_across_age_29_56,dob_across_age_57_84,dob_across_age_85_116,dob_across_race_overall,dob_across_age_overall = check_bias_by_counting(filename3)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 554, 58, 17, 5974, 628, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 4738, 198, 11748, 11192, ...
2.332382
2,452
import numpy as np import astropy.units as u def snr(signal, detector): """ Calculate the SNR of a signal in a given detector, assuming that it has been detected with an optimal filter. See e.g. arxiv.org/abs/1408.0740 Parameters ---------- signal : Source A Source object which describes the source producing the signal, e.g. a CBC. detector : Detector A Detector object describing the instrument making the observation e.g. aLIGO. Returns ------- SNR : float The signal-to-noise ratio of the signal in the detector. """ if signal.ncycles(): ncycles = np.sqrt(2*signal.ncycles(detector.frequencies)) else: ncycles = 1 noise = detector.psd(detector.frequencies) ampli = signal.raw_strain(detector.frequencies) * ncycles fraction = 4*(np.abs(ampli)**2 / noise) fraction[np.isnan(fraction)]=0 return np.sqrt(np.trapz(fraction, x=detector.frequencies, dx=0.01*u.hertz))
[ 11748, 299, 32152, 355, 45941, 198, 11748, 6468, 28338, 13, 41667, 355, 334, 198, 4299, 3013, 81, 7, 12683, 282, 11, 31029, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 27131, 378, 262, 11346, 49, 286, 257, 6737, 287, 257, 1...
2.399533
428
''' Script to plot the accuracy and the fairness measures for different algorithms from the log files ''' import matplotlib matplotlib.use('agg') from matplotlib import pyplot as plt import os print(os.getcwd()) import numpy as np plt.style.use('ggplot') if __name__ == "__main__": gen_all_plots()
[ 7061, 6, 198, 7391, 284, 7110, 262, 9922, 290, 262, 22692, 5260, 329, 1180, 16113, 198, 6738, 262, 2604, 3696, 198, 7061, 6, 198, 198, 11748, 2603, 29487, 8019, 198, 6759, 29487, 8019, 13, 1904, 10786, 9460, 11537, 198, 6738, 2603, 29...
2.872727
110
import requests from satella.coding.decorators import retry
[ 11748, 7007, 198, 6738, 8983, 64, 13, 66, 7656, 13, 12501, 273, 2024, 1330, 1005, 563, 628 ]
3.588235
17
# Copyright (c) Microsoft Corporation # # All rights reserved. # # MIT License # # 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. # # @author: asedighi import asyncio import sys sys.path.append('.') sys.path.append('..') sys.path.append('/mnt/resource/batch/tasks/shared/') sys.path.append('/mnt/resource/batch/tasks/shared/engine') sys.path.append('/mnt/resource/batch/tasks/shared/batchwrapper') sys.path.append('/mnt/resource/batch/tasks/shared/tasks') from batchwrapper.config import getRandomizer from batchwrapper.config import AzureCredentials from batchwrapper.config import ReadConfig from batchwrapper.config import TaskConfig from batchwrapper.config import find_file_path import argparse import ntpath from engine.taskengine import task_loop from subprocess import * from azure.storage.blob import BlobServiceClient from azure.servicebus import ServiceBusClient import os if __name__ == '__main__': print("Starting engine ...") #all_input = sys.argv[1:]; #data_input = ' '.join(all_input[1:]) #foo = (all_input[0], data_input) #print(foo) #exit(1) engine = AzureBatchEngine() engine.do()
[ 2, 15069, 357, 66, 8, 5413, 10501, 198, 2, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 17168, 13789, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 198, 2, 4866, 286, 428, ...
3.349922
643
import tkinter as tk import sys if __name__ == '__main__': while True: try: print("qiaulfskhdnliukf") root = tk.Tk() t = tk.Text() t.pack() # create instance of file like object pl = PrintLogger(t) # replace sys.stdout with our object sys.stdout = pl # now we can print to stdout or file print('hello world') print('hello world') root.mainloop() except: print("exception")
[ 11748, 256, 74, 3849, 355, 256, 74, 198, 11748, 25064, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 628, 220, 220, 220, 981, 6407, 25, 198, 220, 220, 220, 220, 220, 220, 220, 1949, 25, 628, 220, 220, 220, 22...
1.872483
298
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ============================================================================ # ByteWeiser - Byte comparison and replacement tool # Main script # Copyright (C) 2021 by Ralf Kilian # Distributed under the MIT License (https://opensource.org/licenses/MIT) # # GitHub: https://github.com/urbanware-org/byteweiser # GitLab: https://gitlab.com/urbanware-org/byteweiser # ============================================================================ import os import sys if __name__ == "__main__": main() # EOF
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 38093, 2559, 18604, 198, 2, 30589, 1135, 5847, 532, 30589, 7208, 290, 9014, 2891, 198, 2, 8774, 4226, 198...
3.556962
158
import altair as alt import os import pandas as pd import streamlit as st import sys from datetime import datetime from dateutil.relativedelta import relativedelta from dotenv import load_dotenv from plaid.api_client import ApiClient from plaid.exceptions import ApiException from pathlib import Path from traceback import format_exc from urllib.error import URLError sys.path.append(os.getcwd()) load_dotenv() from src.budget import Budget from src.transactions import get_transactions_df from src.user_modifications import transform_pipeline from src.views import top_vendors EXISTING_TRANSACTIONS_FILE = f"{Path.home()}/.ry-n-shres-budget-app/all_transactions.csv" TRANSACTION_GRACE_BUFFER = relativedelta(days=10) # How far before latest transaction to pull from def write_df(df: pd.DataFrame): """Helper function to st.write a DF with amount stylized to dollars""" st.dataframe( df.style.format({ col_name: "{:,.2f}" for col_name in ["amount", "Total Spent"] }) ) # TODO: Make non-budgeted columns show up on bar chart, just without ticks # TODO: Make all-time a budget period option (figure out what to do about this - maybe it only shows up for one month?) # TODO: Allow you to set custom start date for your budget period (i.e. make your monthly spending start on the 3rd) # TODO: Fix the duplicate charge issue with pending charges def single_inc_spending_summary(df: pd.DataFrame, date_inc_key: str, curr_date: str, is_current: bool = False) -> None: """Creates display for a single date increment Parameters ---------- df Transactions Dataframe date_inc_key The key for date increment (one of week, month, year) curr_date The selected date increment value is_current Whether the date represents the most recent date increment """ budget = Budget(df) curr_df = df[df[date_inc_key] == curr_date] total_spending_str = f"{curr_df['amount'].sum():,.2f}" if budget.budget_plan: show_budget = st.checkbox("Budget View", value=True) total_budget = budget.total_limit(date_inc_key) if budget.budget_plan and show_budget: metric_col1, metric_col2 = st.columns(2) with metric_col1: st.metric(f"Total Spending", total_spending_str) with metric_col2: st.metric(f"Total Budget", f"{total_budget:,.2f}") simple_summary = budget.simple_summary(date_inc_key, curr_date) bar = alt.Chart(simple_summary).mark_bar().encode( y="category", x="spent", tooltip=alt.Tooltip(field="spent", aggregate="sum", type="quantitative"), ).properties( height=alt.Step(60) ) ticks = alt.Chart(simple_summary).mark_tick( color="red", thickness=3, size=60 * 0.9, ).encode( y="category", x="total_budget", tooltip=alt.Tooltip(field="total_budget", aggregate="sum", type="quantitative") ) if is_current: ticks += alt.Chart(simple_summary).mark_tick( color="white", thickness=2, size=60 * 0.9, ).encode( y="category", x="projected_budget", ) st.altair_chart(bar + ticks, use_container_width=True) else: st.metric(f"Total Spending", total_spending_str) chart = alt.Chart(curr_df).mark_bar().encode( x=alt.X("sum(amount)", axis=alt.Axis(title='Spent')), y=alt.Y("category_1", axis=alt.Axis(title="Category")), tooltip=alt.Tooltip(field="amount", aggregate="sum", type="quantitative"), ).properties( height=alt.Step(40), ) st.altair_chart(chart, use_container_width=True) with st.expander("Largest Transactions"): write_df( curr_df[["date", "amount", "name", "category_1", "category_2"]].sort_values( by="amount", ascending=False ) ) def df_for_certain_categories(df: pd.DataFrame) -> pd.DataFrame: """Helper function to get a DF filtered by any user selected categories""" categories = st.multiselect( f"Select any categories to only see spending for", options=sorted(df['category_1'].unique()), default=[], ) if len(categories) > 0: bool_key = df['category_1'] == 'NOT_A CATEGORY' for cat in categories: bool_key = bool_key | (df['category_1'] == cat) df = df[bool_key] return df if __name__ == "__main__": main()
[ 11748, 5988, 958, 355, 5988, 198, 11748, 28686, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 4269, 18250, 355, 336, 198, 11748, 25064, 198, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 3128, 22602, 13, 2411, 265, 1572, 12514...
2.343029
1,994
import yaml import argparse import sys import os import subprocess import time def get_nodes(yml_dict, host_index_map): nodes = [] shard_index = yml_dict['shard_index'] try: host_index_map = yml_dict['host_index_map'] print("Using shard's {} for shard {}".format(host_index_map, shard_index)) except: print("Using devvnet host_index_map ({}) for shard {}".format(host_index_map, shard_index)) for proc in yml_dict['process']: try: print("creating {} {} processes".format(len(host_index_map), proc['name'])) for node_index in host_index_map: node = Node(shard_index, node_index, proc['name'], host_index_map[node_index], proc['bind_port']) try: rawsubs = proc['subscribe'] for sub in proc['subscribe']: try: si = sub['shard_index'] except: si = yml_dict['shard_index'] node.add_raw_sub(sub['name'], si, sub['node_index']) except: pass nodes.append(node) except: nodes.append(Node(shard_index, ind, proc['name'], proc['host'], proc['bind_port'])) print("creating a "+proc['name']+" process") return nodes def run_validator(node): # ./devcash --node-index 0 --config ../opt/basic_shard.conf --config ../opt/default_pass.conf --host-list tcp://localhost:56551 --host-list tcp://localhost:56552 --host-list tcp://localhost:57550 --bind-endpoint tcp://*:56550 cmd = [] cmd.append("./devcash") cmd.extend(["--shard-index", str(node.get_shard_index())]) cmd.extend(["--node-index", str(node.get_index())]) cmd.extend(["--num-consensus-threads", "1"]) cmd.extend(["--num-validator-threads", "1"]) cmd.extend(["--config", node.get_config_file()]) cmd.extend(["--config", node.get_password_file()]) cmd.extend(["--bind-endpoint", "tcp://*:" + str(node.get_port())]) for sub in node.get_subscriber_list(): cmd.extend(["--host-list", "tcp://" + sub.get_host() + ":" + str(sub.get_port())]) return cmd def run_announcer(node): # ./announcer --node-index 0 --shard-index 1 --mode T2 --stop-file /tmp/stop-devcash-announcer.ctl --inn-keys ../opt/inn.key --node-keys ../opt/node.key --bind-endpoint 'tcp://*:50020' --working-dir ../../tmp/working/input/laminar4/ --key-pass password --separate-ops true cmd = [] cmd.append("./pb_announcer") cmd.extend(["--shard-index", str(node.get_shard_index())]) cmd.extend(["--node-index", str(node.get_index())]) cmd.extend(["--config", node.get_config_file()]) cmd.extend(["--config", node.get_password_file()]) cmd.extend(["--mode", node.get_type()]) cmd.extend(["--bind-endpoint", "tcp://*:" + str(node.get_port())]) cmd.extend(["--separate-ops", "true"]) cmd.extend(["--start-delay", str(30)]) cmd.extend(["--protobuf-endpoint", "tcp://*:" + str(node.get_port() + 100)]) return cmd def run_repeater(node): # ./repeater --node-index 0 --shard-index 1 --mode T2 --stop-file /tmp/stop-devcash-repeater.ctl --inn-keys ../opt/inn.key --node-keys ../opt/node.key --working-dir ../../tmp/working/output/repeater --host-list tcp://localhost:56550 --key-pass password cmd = [] cmd.append("./repeater") cmd.extend(["--shard-index", str(node.get_shard_index())]) cmd.extend(["--node-index", str(node.get_index())]) cmd.extend(["--num-consensus-threads", "1"]) cmd.extend(["--num-validator-threads", "1"]) cmd.extend(["--mode", node.get_type()]) cmd.extend(["--working-dir", node.get_working_dir()]) cmd.extend(["--protobuf-endpoint", "tcp://*:" + str(node.get_port() + 200)]) for sub in node.get_subscriber_list(): cmd.extend(["--host-list", "tcp://" + sub.get_host() + ":" + str(sub.get_port())]) return cmd if __name__ == '__main__': parser = argparse.ArgumentParser(description='Launch a devvnet.') parser.add_argument('--logdir', action="store", dest='logdir', help='Directory to log output') parser.add_argument('--start-processes', action="store_true", dest='start', default=True, help='Start the processes') parser.add_argument('--hostname', action="store", dest='hostname', default=None, help='Debugging output') parser.add_argument('--debug', action="store_true", dest='start', default=False, help='Debugging output') parser.add_argument('devvnet', action="store", help='YAML file describing the devvnet') args = parser.parse_args() print(args) print("logdir: " + args.logdir) print("start: " + str(args.start)) print("hostname: " + str(args.hostname)) print("devvnet: " + args.devvnet) devvnet = get_devvnet(args.devvnet) d = Devvnet(devvnet) num_nodes = d.get_num_nodes() logfiles = [] cmds = [] for s in d.get_shards(): for n in s.get_nodes(): if args.hostname and (args.hostname != n.get_host()): continue if n.get_name() == 'validator': cmds.append(run_validator(n)) elif n.get_name() == 'repeater': cmds.append(run_repeater(n)) elif n.get_name() == 'announcer': cmds.append(run_announcer(n)) logfiles.append(os.path.join(args.logdir, n.get_name()+"_s"+ str(n.get_shard_index())+"_n"+ str(n.get_index())+"_output.log")) ps = [] for index,cmd in enumerate(cmds): print("Node " + str(index) + ":") print(" Command: ", *cmd) print(" Logfile: ", logfiles[index]) if args.start: with open(logfiles[index], "w") as outfile: ps.append(subprocess.Popen(cmd, stdout=outfile, stderr=outfile)) time.sleep(1.5) if args.start: for p in ps: print("Waiting for nodes ... ctl-c to exit.") p.wait() print("Goodbye.")
[ 11748, 331, 43695, 198, 11748, 1822, 29572, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 850, 14681, 198, 11748, 640, 628, 628, 628, 198, 198, 4299, 651, 62, 77, 4147, 7, 88, 4029, 62, 11600, 11, 2583, 62, 9630, 62, 8899, 2599, ...
2.163848
2,838
#!/usr/bin/env python # coding: utf-8 # Copyright 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. ''' This tool submits a QASM file to any backend and show the result. It requires 'Qconfig.py' to set a token of IBM Quantum Experience. It supports the following backends: ibmqx2(5 qubits), ibmqx4(5 qubits), ibmqx5(16 qubits), simulator(32 qubits). see https://quantumexperience.ng.bluemix.net/qx/devices for more details of the backends. Examples: $ python run_qasm.py -b # show backend information $ python run_qasm.py -c # show remaining credits $ python run_qasm.py -l 10 # show job list (10 jobs) $ python run_qasm.py -j (job id) # show the result of a job $ python run_qasm.py -q (qasm file) # submit a qasm file $ python run_qasm.py -z -l 10 # show job list (10 jobs) of qconsole $ python run_qasm.py -z -d ibmq_20_tokyo -q (qasm file) # submit a qasm file to ibmq_20_tokyo ''' import json import time from argparse import ArgumentParser from IBMQuantumExperience import IBMQuantumExperience try: import Qconfig except ImportError: raise RuntimeError('You need "Qconfig.py" with a token in the same directory.') if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 15069, 2864, 11, 19764, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 1043, 287, 1...
2.74187
492
"""adding usrname column Revision ID: 175f5441bd46 Revises: 186abcf43cae Create Date: 2021-11-20 22:54:04.157131 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '175f5441bd46' down_revision = '186abcf43cae' branch_labels = None depends_on = None
[ 37811, 26872, 514, 81, 3672, 5721, 198, 198, 18009, 1166, 4522, 25, 19038, 69, 20, 39710, 17457, 3510, 198, 18009, 2696, 25, 28481, 397, 12993, 3559, 66, 3609, 198, 16447, 7536, 25, 33448, 12, 1157, 12, 1238, 2534, 25, 4051, 25, 3023,...
2.623932
117
from django.conf import settings from django.contrib.auth import get_user_model from django.db import models from nucleus.models import ( AbstractBaseModel, EmailRecord, TeamMember, ) User = get_user_model() INVITE_TEMPLATE = """Hello, You've been invited to join a team on push.gg. Click the link below to sign up: {signup_link} - Push League """
[ 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, 19849, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 198, 6738, 29984, 13, 27530, 1330, 357, 198, 220, 220, 2...
2.928571
126
""" Lazy loading modules """ import sys import importlib.util def lazyImport(modulename): """ This will allow us to lazy import various modules Parameters ---------- modulename : `str` The name of the module in question Returns ------- module : `importlib.LazyModule` A lazy loader for the module in question """ try: return sys.modules[modulename] except KeyError: spec = importlib.util.find_spec(modulename) if spec is None: print("Can't find module %s" % modulename) return DeferredModuleError(modulename) module = importlib.util.module_from_spec(spec) loader = importlib.util.LazyLoader(spec.loader) # Make module with proper locking and get it inserted into sys.modules. loader.exec_module(module) try: _ = dir(module) except ValueError: pass return module tables = lazyImport('tables') apTable = lazyImport('astropy.table') fits = lazyImport('astropy.io.fits') h5py = lazyImport('h5py') pd = lazyImport('pandas') pq = lazyImport('pyarrow.parquet') HAS_TABLES = tables is not None HAS_PQ = pq is not None HAS_FITS = fits is not None HAS_ASTROPY = apTable is not None HAS_HDF5 = h5py is not None HAS_PANDAS = pd is not None
[ 37811, 406, 12582, 11046, 13103, 37227, 198, 198, 11748, 25064, 198, 11748, 1330, 8019, 13, 22602, 628, 628, 198, 4299, 16931, 20939, 7, 4666, 377, 12453, 2599, 198, 220, 220, 220, 37227, 770, 481, 1249, 514, 284, 16931, 1330, 2972, 131...
2.482109
531
import numpy as np from keras.optimizers import Adam, SGD from tensorflow.keras.metrics import AUC import metrics from networks.unet_nn import unet from networks.unet_res_se_nn import unet_res_se from networks.focus import get_focusnetAlpha from networks.resnet import get_res from data_processing.generate_new_dataset import generate_targets from tensorflow.keras.applications.resnet50 import preprocess_input ########### SEGMENTATION ########### # U-Net model = unet(batch_norm=False) model.load_weights("/var/tmp/mi714/NEW/models/UNET/unet10/unet10_weights.h5") # U-Net BatchNorm # model = unet(batch_norm=True) # model.load_weights("/var/tmp/mi714/NEW/models/UNET_BN/unet_bn10/unet_bn10_weights.h5") # U-Net Res SE # model = unet_res_se() # model.load_weights("/var/tmp/mi714/NEW/models/UNET_RES_SE/unet_res_se10/unet_res_se10_weights.h5") #Focusnet # model = get_focusnetAlpha() # model.load_weights("/var/tmp/mi714/NEW/models/FOCUS/focusnet10/focusnet10_weights.h5") ########### CLASSIFICATION ########### # model = get_res() # Original # model.load_weights("/var/tmp/mi714/NEW/models/RESNETS/RESNET_OG/resnet_og10/resnet_og10_weights.h5") # U-Net # model.load_weights("/var/tmp/mi714/NEW/models/RESNETS/RESNET_UNET_BN/resnet_unet10/resnet_unet10_weights.h5") # U-Net BatchNorm # model.load_weights("/var/tmp/mi714/NEW/models/RESNETS/RESNET_UNET_BN/resnet_unet_bn10/resnet_unet_bn10_weights.h5") # Res SE U-Net # model.load_weights("/var/tmp/mi714/NEW/models/RESNETS/RESNET_UNET_RES_SE/resnet_unet_res_se10/resnet_unet_res_se10_weights.h5") # FocusNet # model.load_weights("/var/tmp/mi714/NEW/models/RESNETS/RESNET_FOCUSNET/resnet_focusnet7/resnet_focusnet7_weights.h5") # Data, Masks & Classification target labels # trainData = np.load('/var/tmp/mi714/test_new_npy2/data.npy') # valData = np.load('/var/tmp/mi714/test_new_npy2/dataval.npy') testData = np.load('/var/tmp/mi714/NEW/npy_dataset/datatest.npy') # Segmentation masks # trainMask = np.load('/var/tmp/mi714/test_new_npy2/dataMask.npy') # valMask = np.load('/var/tmp/mi714/test_new_npy2/dataMaskval.npy') testMask = np.load('/var/tmp/mi714/NEW/npy_dataset/dataMasktest.npy') ########### SEGMENTATION ########### X = testData y = testMask X = X.astype('float32') y /= 255. # scale masks to [0, 1] my_adam = Adam(lr=0.00001, beta_1=0.9, beta_2=0.999, epsilon=1e-07) model.compile(optimizer=my_adam, loss=metrics.focal_loss, metrics=[metrics.dice_coef_loss, metrics.jaccard_coef_loss, metrics.true_positive, metrics.true_negative, ]) score = model.evaluate(X, y, verbose=1) dice_coef_loss = score[1] jac_indx_loss = score[2] true_positive = score[3] true_negative = score[4] print(f""" RESULTS: Dice Coefficient Loss: {dice_coef_loss} Jaccard Index Loss: {jac_indx_loss} True Positive: {true_positive} True Negative: {true_negative} """) ########### CLASSIFICATION ########### # # Classification data # # x_train = np.concatenate((trainData,)*3, axis=-1) # # x_train = preprocess_input(x_train) # # x_val = np.concatenate((valData,)*3, axis=-1) # # x_val = preprocess_input(x_val) # x_test = np.concatenate((testData,)*3, axis=-1) # x_test = preprocess_input(x_test) # # Classification target labels # path = "/var/tmp/mi714/NEW/aug_dataset/" # # y_train = generate_targets(path + "ISIC-2017_Training_Data", # # path + "ISIC-2017_Training_Part3_GroundTruth.csv") # # y_val = generate_targets(path + "ISIC-2017_Validation_Data", # # path + "ISIC-2017_Validation_Part3_GroundTruth.csv") # y_test = generate_targets(path + "ISIC-2017_Test_v2_Data", # path + "ISIC-2017_Test_v2_Part3_GroundTruth.csv") # X = x_test # y = y_test # my_adam = Adam(lr=0.00001, beta_1=0.9, beta_2=0.999, epsilon=1e-07) # # Compile model and print summary # rocauc = AUC(num_thresholds=200, # curve="ROC", # summation_method="interpolation", # name=None, # dtype=None, # thresholds=None, # multi_label=False, # label_weights=None, # ) # model.compile(loss='categorical_crossentropy', # optimizer=my_adam, # metrics=[metrics.sensitivity, # metrics.specificity, # rocauc, # 'acc' # ]) # score = model.evaluate(X, y, verbose=1) # binary_ce = score[0] # sensitivity = score[1] # specificity = score[2] # rocauc = score[3] # acc = score[4] # print(f""" # RESULTS: # Binary Cross-Entropy Loss: {binary_ce} # Sensitivity: {sensitivity} # Specificity: {specificity} # AUC ROC: {rocauc} # Accuracy: {acc} # """)
[ 11748, 299, 32152, 355, 45941, 198, 198, 6738, 41927, 292, 13, 40085, 11341, 1330, 7244, 11, 26147, 35, 198, 6738, 11192, 273, 11125, 13, 6122, 292, 13, 4164, 10466, 1330, 317, 9598, 198, 198, 11748, 20731, 198, 6738, 7686, 13, 403, 3...
2.158367
2,229
""" An implementation of Bohnanza @author: David Kelley, 2018 """ import random from collections import defaultdict
[ 37811, 198, 2025, 7822, 286, 347, 1562, 35819, 198, 198, 31, 9800, 25, 3271, 34560, 11, 2864, 198, 37811, 198, 198, 11748, 4738, 220, 198, 6738, 17268, 1330, 4277, 11600, 198, 220, 220, 220, 220, 220, 220, 220, 220, 198, 220, 220, 2...
2.795918
49
"""Tests for calling other functions, and the corresponding checks.""" from pytype import utils from pytype.tests import test_inference if __name__ == "__main__": test_inference.main()
[ 37811, 51, 3558, 329, 4585, 584, 5499, 11, 290, 262, 11188, 8794, 526, 15931, 628, 198, 6738, 12972, 4906, 1330, 3384, 4487, 198, 6738, 12972, 4906, 13, 41989, 1330, 1332, 62, 259, 4288, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366...
3.428571
56
import unittest import lecture1_code00 as dl from sklearn.datasets.samples_generator import make_blobs
[ 11748, 555, 715, 395, 198, 11748, 19143, 16, 62, 8189, 405, 355, 288, 75, 198, 6738, 1341, 35720, 13, 19608, 292, 1039, 13, 82, 12629, 62, 8612, 1352, 1330, 787, 62, 2436, 8158, 628 ]
3.058824
34
#-*-coding: utf-8 -*- """ /dms/edumediaitem/views_manage.py .. enthaelt den View fuer die Management-Ansicht des Medienpaketes Django content Management System Hans Rauch hans.rauch@gmx.net Die Programme des dms-Systems koennen frei genutzt und den spezifischen Beduerfnissen entsprechend angepasst werden. 0.01 11.09.2007 Beginn der Arbeit """ from django.utils.translation import ugettext as _ from dms.queries import get_site_url from dms.roles import require_permission from dms.roles import UserEditPerms from dms.folder.views_manage import do_manage from dms_ext.extension import * # dms-Funktionen ueberschreiben # -----------------------------------------------------
[ 2, 12, 9, 12, 66, 7656, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 14, 67, 907, 14, 276, 388, 5507, 9186, 14, 33571, 62, 805, 496, 13, 9078, 198, 198, 492, 920, 3099, 2120, 2853, 3582, 14035, 263, 4656, 8549, 12, 2025,...
2.506803
294
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from .feature_engineering import get_features_for_deep_gaussian from .convnet import ConvModel from .rnn import RNNModel __all__ = ['get_features_for_deep_gaussian', 'ConvModel', 'RNNModel']
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 17168, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287,...
3
138
from django.http import HttpResponse, JsonResponse, Http404 from django.core.exceptions import PermissionDenied from rest_framework.parsers import JSONParser, FormParser, MultiPartParser from rest_framework.permissions import IsAuthenticatedOrReadOnly from rest_framework import generics from rest_framework.response import Response from projects.models import Project from projects.serializers import ProjectSerializer from projects.permissions import IsOwnerOrReadOnly from django.contrib.auth.models import User
[ 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 11, 449, 1559, 31077, 11, 367, 29281, 26429, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 2448, 3411, 21306, 798, 198, 198, 6738, 1334, 62, 30604, 13, 79, 945, 364, 1...
4.054688
128
import ddt import mock from unittest import TestCase from muduapiclient.client import MuduApiClient, gen_signed_params import time
[ 11748, 288, 28664, 198, 11748, 15290, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 6738, 17492, 84, 499, 291, 75, 1153, 13, 16366, 1330, 32878, 84, 32, 14415, 11792, 11, 2429, 62, 32696, 62, 37266, 198, 11748, 640, 198 ]
3.275
40
from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from productapp.views import product_list from reviewapp.views import index urlpatterns = [ url(r'^$', index, name='index'), url(r'^admin/', admin.site.urls), url(r'^review/', include('reviewapp.urls')), url(r'^product/', include('productapp.urls')), url(r'^account/', include('accountapp.urls')), ] if settings.DEBUG: urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT )
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 11, 2291, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 13, 12708, 1330, ...
2.712963
216
__doc__ = ''' ''' from threading import Thread from time import process_time if 'enums': OK = 0 # ENDGAME = 1 # DRAW = 2 # INVALID = -1 # / CONFILCT = -2 # ERROR = -3 # TIMEOUT = -4 # def match(self): """ : """ self.board = Board() timeouts = [self.timeout] * 2 self.timeout_history = [] for nround in range(9): # plr_idx = nround % 2 thread_output = {} frame = self.board.get_board(plr_idx + 1) thr = Thread(target=self._thread_wrap, args=(self.codes[plr_idx], frame, thread_output)) # thr.start() thr.join(timeouts[plr_idx]) # if thr.is_alive(): return self._get_result(1 - plr_idx, TIMEOUT, '') # timeouts[plr_idx] -= thread_output['dt'] if timeouts[plr_idx] < 0: return self._get_result(1 - plr_idx, TIMEOUT) self.timeout_history.append(timeouts.copy()) # if thread_output['error']: return self._get_result( 1 - plr_idx, ERROR, thread_output['error'], ) # res = self.board.drop(plr_idx + 1, thread_output['result']) if res == OK: # continue return self._get_result( plr_idx if res == ENDGAME else 1 - plr_idx, res, ) return self._get_result(None, DRAW) # if __name__ == '__main__': import codes.dumb_ordered as plr1, codes.dumb_random as plr2 game = Game([plr1, plr2]) print(game.match())
[ 834, 15390, 834, 796, 705, 7061, 628, 198, 7061, 6, 198, 198, 6738, 4704, 278, 1330, 14122, 198, 6738, 640, 1330, 1429, 62, 2435, 198, 198, 361, 705, 268, 5700, 10354, 198, 220, 220, 220, 7477, 796, 657, 220, 1303, 220, 198, 220, ...
1.742498
1,033
"""Escreva um programa que leia o valor em metros e o exiba convertido em centmetros e milmetros""" from utilidadescev.dado import leia_real n = leia_real('Digite a metragem: ') km = n / 1000 hec = n / 100 dam = n / 10 dec = n * 10 cent = n * 100 mil = n * 1000 print(f'{km:.3f}km') print(f'{hec:.2f}hm') print(f'{dam:.1f}dam') print(f'{dec:.0f}dm') print(f'{cent:.0f}cm ') print(f'{mil:.0f}mm')
[ 37811, 47051, 260, 6862, 23781, 1430, 64, 8358, 443, 544, 267, 1188, 273, 795, 1138, 4951, 304, 267, 409, 23718, 10385, 17305, 795, 1247, 4164, 4951, 304, 1465, 4164, 4951, 37811, 198, 198, 6738, 7736, 312, 2367, 344, 85, 13, 67, 4533...
2.10582
189
import os import pyowm from datetime import datetime from timezone_conversion import gmt_to_eastern #API_KEY = os.environ['API_KEY'] owm=pyowm.OWM('0833f103dc7c2924da06db624f74565c') mgr=owm.weather_manager() if __name__ == '__main__': get_temperature()
[ 11748, 28686, 198, 11748, 12972, 322, 76, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 640, 11340, 62, 1102, 9641, 1330, 308, 16762, 62, 1462, 62, 68, 6470, 198, 198, 2, 17614, 62, 20373, 796, 28686, 13, 268, 2268, 17816, 17614...
2.333333
114
import copy import datetime import json import math import multiprocessing import numpy as np import os import pandas as pd import pydotplus import random import re import time from math import * from sklearn import metrics _CLUSTER_DATA = './bike_sharing_data/mydata' RATEDATA = './bike_sharing_data/mydata/' rateName = 'rental_return_rate_cluster_6_month_678_timedelta_5.json' # STATION_STATUS = './station_status_by_id' ########################### # MCTS algorithm def start(availStations, neighbor, lostNums, visitedPath, cumulativeDis, startStation, balanceNum, mutex, realtimeBikes, day, olderNeighbor): print("start running, the process number is %d" % (os.getpid())) mcts = MCTS(availStations) selectedSta = startStation starttime = 0 rateData = getRateData() station_status, totalDocksDict = getStation_status() # visitedPath = [] # cumulativeDis = [] info = {} visitedPath.append(selectedSta) totalLost = 0 print('start station:' + str(selectedSta)) # lostNums = {} isRequest, starttime, dropNum, pickNum, rentalLost, returnLost, realbikes = getRequest(selectedSta, selectedSta, starttime, cumulativeDis, rateData, station_status, totalDocksDict, day) lostNums[str(selectedSta)] = float(rentalLost) + float(returnLost) totalLost += lostNums[str(selectedSta)] info['time'] = starttime info['realbikes'] = realbikes realtimeBikes[str(selectedSta)] = info if int(dropNum) > 0: balanceNum[str(selectedSta)] = -int(dropNum) elif int(pickNum) > 0: balanceNum[str(selectedSta)] = int(pickNum) else: balanceNum[str(selectedSta)] = 0 if isRequest: print('sub-process:pid=%d' % os.getpid()) print('balance station:' + str(selectedSta) + ' dropNum:' + str(dropNum) + ' pickNum:' + str(pickNum)) print('customer loss:' + str(lostNums[str(selectedSta)])) print('current time:' + str(starttime) + ' min') print('travel distance:') print(cumulativeDis) # bikeSystem.update(selectedSta) availStations.remove(str(selectedSta)) mcts.fileCount = 0 while 1: lastSta = selectedSta info = {} mutex.acquire() if not len(availStations): print('There are no stations need to be balanced') lostNums['totalLost'] = totalLost mutex.release() break selectedSta = mcts.get_action(lastSta, starttime, neighbor, rateData, station_status, totalDocksDict, day, olderNeighbor) mcts.fileCount += 1 print('through station:' + str(selectedSta)) # bikeSystem.update(selectedSta) availStations.remove(str(selectedSta)) mutex.release() visitedPath.append(selectedSta) isRequest, starttime, dropNum, pickNum, rentalLost, returnLost, realbikes = getRequest(lastSta, selectedSta, starttime, cumulativeDis, rateData, station_status, totalDocksDict, day) lostNums[str(selectedSta)] = float(rentalLost) + float(returnLost) totalLost += lostNums[str(selectedSta)] info['time'] = starttime info['realbikes'] = realbikes realtimeBikes[str(selectedSta)] = info if int(dropNum) > 0: balanceNum[str(selectedSta)] = -int(dropNum) elif int(pickNum) > 0: balanceNum[str(selectedSta)] = int(pickNum) else: balanceNum[str(selectedSta)] = 0 if isRequest: print('sub-process:pid=%d' % os.getpid()) print('balance station:' + str(selectedSta) + ' dropNum:' + str(dropNum) + ' pickNum:' + str(pickNum)) print('customer loss:' + str(lostNums[str(selectedSta)])) print('current time:' + str(starttime) + ' min') print('travel distance:') print(cumulativeDis) if not len(availStations): print('There are no stations need to be balanced') lostNums['totalLost'] = totalLost break print('****************************************************') if __name__ == '__main__': mctsAlgorithm() # noReposition() # staticReposition() # nearestNeihborReposition() # nearestNeihborBaseServiceLevelReposition()
[ 11748, 4866, 201, 198, 11748, 4818, 8079, 201, 198, 11748, 33918, 201, 198, 11748, 10688, 201, 198, 11748, 18540, 305, 919, 278, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 28686, 201, 198, 11748, 19798, 292, 355, 279, 67,...
1.926667
2,700
## @ingroup Components-Energy-Storages-Batteries-Constant_Mass # Lithium_Ion_LiFePO4_18650.py # # Created: Feb 2020, M. Clarke # Modified: Sep 2021, R. Erhard # ---------------------------------------------------------------------- # Imports # ---------------------------------------------------------------------- # suave imports from SUAVE.Core import Units from .Lithium_Ion import Lithium_Ion # package imports import numpy as np ## @ingroup Components-Energy-Storages-Batteries-Constant_Mass
[ 2235, 2488, 278, 3233, 36109, 12, 28925, 12, 1273, 273, 1095, 12, 33, 1436, 444, 12, 3103, 18797, 62, 20273, 198, 2, 19730, 1505, 62, 40, 261, 62, 32304, 14304, 16402, 19, 62, 1507, 17544, 13, 9078, 198, 2, 220, 198, 2, 15622, 25,...
3.510345
145
# Copyright 2011-2012 10gen, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Motor, an asynchronous driver for MongoDB and Tornado.""" import collections import functools import inspect import socket import time import warnings import weakref from tornado import ioloop, iostream, gen, stack_context from tornado.concurrent import Future import greenlet import bson import pymongo import pymongo.auth import pymongo.common import pymongo.database import pymongo.errors import pymongo.mongo_client import pymongo.mongo_replica_set_client import pymongo.son_manipulator from pymongo.pool import _closed, SocketInfo import gridfs from pymongo.database import Database from pymongo.collection import Collection from pymongo.cursor import Cursor, _QUERY_OPTIONS from gridfs import grid_file import util __all__ = ['MotorClient', 'MotorReplicaSetClient', 'Op'] version_tuple = (0, 1, '+') version = get_version_string() """Current version of Motor.""" # TODO: ensure we're doing # timeouts as efficiently as possible, test performance hit with timeouts # from registering and cancelling timeouts HAS_SSL = True try: import ssl except ImportError: ssl = None HAS_SSL = False callback_type_error = TypeError("callback must be a callable") def motor_sock_method(method): """Wrap a MotorSocket method to pause the current greenlet and arrange for the greenlet to be resumed when non-blocking I/O has completed. """ return _motor_sock_method def callback_from_future(future): """Return a callback that sets a Future's result or exception""" return callback def asynchronize(motor_class, sync_method, has_write_concern, doc=None): """Decorate `sync_method` so it accepts a callback or returns a Future. The method runs on a child greenlet and calls the callback or resolves the Future when the greenlet completes. :Parameters: - `motor_class`: Motor class being created, e.g. MotorClient. - `sync_method`: Bound method of pymongo Collection, Database, MongoClient, or Cursor - `has_write_concern`: Whether the method accepts getLastError options - `doc`: Optionally override sync_method's docstring """ # This is for the benefit of motor_extensions.py, which needs this info to # generate documentation with Sphinx. method.is_async_method = True method.has_write_concern = has_write_concern name = sync_method.__name__ if name.startswith('__') and not name.endswith("__"): # Mangle, e.g. Cursor.__die -> Cursor._Cursor__die classname = motor_class.__delegate_class__.__name__ name = '_%s%s' % (classname, name) method.pymongo_method_name = name if doc is not None: method.__doc__ = doc return method def check_delegate(obj, attr_name): if not obj.delegate: raise pymongo.errors.InvalidOperation( "Call open() on %s before accessing attribute '%s'" % ( obj.__class__.__name__, attr_name)) DelegateMethod = ReadOnlyProperty """A method on the wrapped PyMongo object that does no I/O and can be called synchronously""" def _delegate_init_args(self): """Override MotorOpenable._delegate_init_args to ensure auto_start_request is False and _pool_class is MotorPool. """ kwargs = self._init_kwargs.copy() kwargs['auto_start_request'] = False kwargs['_pool_class'] = functools.partial(MotorPool, self.io_loop) return self._init_args, kwargs class MotorClient(MotorClientBase): __delegate_class__ = pymongo.mongo_client.MongoClient kill_cursors = AsyncCommand() fsync = AsyncCommand() unlock = AsyncCommand() nodes = ReadOnlyProperty() host = ReadOnlyProperty() port = ReadOnlyProperty() _simple_command = AsyncCommand(attr_name='__simple_command') def __init__(self, *args, **kwargs): """Create a new connection to a single MongoDB instance at *host:port*. :meth:`open` or :meth:`open_sync` must be called before using a new MotorClient. No property access is allowed before the connection is opened. MotorClient takes the same constructor arguments as `MongoClient`_, as well as: :Parameters: - `io_loop` (optional): Special :class:`tornado.ioloop.IOLoop` instance to use instead of default .. _MongoClient: http://api.mongodb.org/python/current/api/pymongo/mongo_client.html """ super(MotorClient, self).__init__( None, kwargs.pop('io_loop', None), *args, **kwargs) def _async_get_socket(self, pool): """Return a ``Future`` that will resolve to a socket.""" # MongoClient passes host and port into the pool for each call to # get_socket. return pool.async_get_socket((self.host, self.port)) class MotorReplicaSetClient(MotorClientBase): __delegate_class__ = pymongo.mongo_replica_set_client.MongoReplicaSetClient primary = ReadOnlyProperty() secondaries = ReadOnlyProperty() arbiters = ReadOnlyProperty() hosts = ReadOnlyProperty() seeds = ReadOnlyProperty() close = DelegateMethod() _simple_command = AsyncCommand(attr_name='__simple_command') def __init__(self, *args, **kwargs): """Create a new connection to a MongoDB replica set. :meth:`open` or :meth:`open_sync` must be called before using a new MotorReplicaSetClient. No property access is allowed before the connection is opened. MotorReplicaSetClient takes the same constructor arguments as `MongoReplicaSetClient`_, as well as: :Parameters: - `io_loop` (optional): Special :class:`tornado.ioloop.IOLoop` instance to use instead of default .. _MongoReplicaSetClient: http://api.mongodb.org/python/current/api/pymongo/mongo_replica_set_client.html """ super(MotorReplicaSetClient, self).__init__( None, kwargs.pop('io_loop', None), *args, **kwargs) def open_sync(self): """Synchronous open(), returning self. Under the hood, this method creates a new Tornado IOLoop, runs :meth:`open` on the loop, and deletes the loop when :meth:`open` completes. """ super(MotorReplicaSetClient, self).open_sync() # We need to wait for open_sync() to complete and restore the # original IOLoop before starting the monitor. self.delegate._MongoReplicaSetClient__monitor.start_motor(self.io_loop) return self def open(self, callback=None): """Actually initialize. Takes an optional callback, or returns a Future that resolves to self when opened. :Parameters: - `callback`: Optional function taking parameters (self, error) """ if callback and not callable(callback): raise callback_type_error if callback: super(MotorReplicaSetClient, self)._open(callback=opened) else: future = Future() # The final callback run from inside opened callback = callback_from_future(future) super(MotorReplicaSetClient, self)._open(callback=opened) return future def _async_get_socket(self, pool): """Return a ``Future`` that will resolve to a socket.""" # MongoReplicaSetClient sets pools' host and port when it creates them. return pool.async_get_socket() # PyMongo uses a background thread to regularly inspect the replica set and # monitor it for changes. In Motor, use a periodic callback on the IOLoop to # monitor the set. MotorGridIn.set = asynchronize( MotorGridIn, gridfs.GridIn.__setattr__, False, doc=""" Set an arbitrary metadata attribute on the file. Stores value on the server as a key-value pair within the file document once the file is closed. If the file is already closed, calling `set` will immediately update the file document on the server. Metadata set on the file appears as attributes on a :class:`~MotorGridOut` object created from the file. :Parameters: - `name`: Name of the attribute, will be stored as a key in the file document on the server - `value`: Value of the attribute - `callback`: Optional callback to execute once attribute is set. """) def Op(fn, *args, **kwargs): """Obsolete; here for backwards compatibility with Motor 0.1. Op had been necessary for ease-of-use with Tornado 2 and @gen.engine. But Motor 0.2 is built for Tornado 3, @gen.coroutine, and Futures, so motor.Op is deprecated. """ msg = "motor.Op is deprecated, simply call %s and yield its Future." % ( fn.__name__) warnings.warn(msg, DeprecationWarning, stacklevel=2) result = fn(*args, **kwargs) assert isinstance(result, Future) return result
[ 2, 15069, 2813, 12, 6999, 838, 5235, 11, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, ...
2.779145
3,414
''' Created on Oct 20, 2015 @author: bardya ''' import os import argparse from Bio import SeqIO if __name__ == '__main__': args = parse_args() try: inputfile = open(args.infilepath.name, 'r') outputfile = open(args.outfilepath.name, 'w') # if not os.path.basename(args.outfilepath.name) == "basename": # outputfile = open(args.outfilepath.name, 'w') # else: # outputfile = open(os.path.join(os.path.dirname(args.outfilepath.name),os.path.basename(args.infilepath.name) + '_consensus.faa'), 'w') except: print('IOError occured') seqlst, stats_dict = readfasta(args.infilepath.name, keep_flag=args.keep_flag, rename_flag=args.rename_flag) printStats(stats_dict) writefasta(outputfile, seqlst)
[ 7061, 6, 198, 41972, 319, 2556, 1160, 11, 1853, 198, 198, 31, 9800, 25, 275, 446, 3972, 198, 7061, 6, 198, 11748, 28686, 198, 11748, 1822, 29572, 198, 6738, 16024, 1330, 1001, 80, 9399, 628, 198, 198, 361, 11593, 3672, 834, 6624, 70...
2.240113
354
def log_improvement(value): """function to log improvements to the command line. Parameters ---------- value : int or float The value for the improvement """ print("Improvement : " + str(value)) def log_passed_worse(value): """function to log the passing of worse solutions to the command line. Parameters ---------- value : int or float The value for the improvement """ print("Passed worse: " + str(value))
[ 198, 198, 4299, 2604, 62, 49453, 434, 7, 8367, 2599, 198, 220, 220, 220, 37227, 8818, 284, 2604, 8561, 284, 262, 3141, 1627, 13, 628, 220, 220, 220, 40117, 198, 220, 220, 220, 24200, 438, 198, 220, 220, 220, 1988, 1058, 493, 393, ...
2.871345
171
# https://github.com/pokidovea/immobilus/issues/30 from immobilus import immobilus # noqa from immobilus.logic import fake_time, fake_localtime, fake_gmtime, fake_strftime, fake_mktime from datetime import datetime
[ 2, 3740, 1378, 12567, 13, 785, 14, 79, 482, 312, 659, 64, 14, 8608, 25898, 385, 14, 37165, 14, 1270, 198, 198, 6738, 47800, 385, 1330, 47800, 385, 220, 1303, 645, 20402, 198, 6738, 47800, 385, 13, 6404, 291, 1330, 8390, 62, 2435, ...
2.986667
75
import abc
[ 11748, 450, 66, 628 ]
3
4
#!/usr/bin/env python import re from param import * from emit import Emit # Emit docs in a form acceptable to the APM wiki site
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 302, 198, 6738, 5772, 1330, 1635, 198, 6738, 27588, 1330, 2295, 270, 198, 198, 2, 2295, 270, 34165, 287, 257, 1296, 10909, 284, 262, 3486, 44, 22719, 2524, 198, 220, 220, ...
2.978261
46
#!/usr/bin/env python from PIL import Image import os, os.path import cv2 import sys # Detect faces, then returns number of faces. # Moves pictures based on detection of faces. if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 28686, 11, 28686, 13, 6978, 198, 11748, 269, 85, 17, 198, 11748, 25064, 198, 198, 2, 35874, 6698, 11, 788, 5860, 1271, 286, 6698, 13, 19...
3.070423
71
from.Model import Model import numpy as np
[ 6738, 13, 17633, 1330, 9104, 198, 11748, 299, 32152, 355, 45941, 628, 198 ]
3.461538
13
#!/usr/bin/env python """pygto900 contains commands to interface with a astro-physics gto900 mount """ import serial import io import sys import string import math import time from binutils import * from datetime import datetime from astropy.coordinates import Angle def status(g): """Chck the values for the telescope""" ra = g.ra() dec = g.dec() lst = g.lst() ha = Angle('%s hour' % lst) - Angle('%s hour' % ra) alt = g.alt() az = g.az() a = Angle(alt, unit='degree') z = airmass(a) p = g.pier() return ra,dec,ha,lst,alt,az,z,p def slew(g, ra, dec, niter=100): """Slew to a location Paramters --------- ra: astropy.coordinates.Angle Right Ascension of source dec: astropy.coordinates.Angle Declination of source niter: int Number of loops to attempt if monitoring progress """ g.command_ra(ra.hms[0], ra.hms[1], ra.hms[2]) g.command_dec(dec.dms[0], dec.dms[1], dec.dms[2]) g.slew() for i in range(niter): try: r = Angle(g.ra(), unit='hour') d = Angle(g.dec(), unit='degree') except Exception,e: print e continue dist = ((r.degree - ra.degree)**2 + (d.degree-dec.degree)**2)**0.5 if dist < 1.0/60.0: print 'Done Slewing' return else: print '%5.2f degrees to go until target' % dist return def init(g): """Initialize the telescope""" print "Initializing mount...." g.startup() return def nudge(g, mdir): """Nudge the telescope in one direction""" g.set_center_rate(10) g.move(mdir) time.sleep(1) g.halt(mdir) time.sleep(1) def usage(): """Print the usage string""" usage_str = """ Usage for pygto900: python pygto900 [init/status/log/move/nudge/slew/sync/park/help] [optional] """ print usage_str if __name__=='__main__': task = sys.argv[1].lower() if len(sys.argv) < 2: usage() exit() if task in ['help']: usage() exit() with GTO900() as g: if task == 'status': results = status(g) output ="At RA = %s, Dec = %s, HA = %s, LST = %s, Alt = %s, Az = %s, secz = %.2f, on the %s side of the pier" % results print output elif task == 'log': results = status(g) print '%s %s %s %s %s %s %.2f %s' % results elif task == 'init': init(g) elif task == 'park': g.park_mode() elif task == 'park_off': g.park_off() elif task == 'sync': g.sync() elif task == 'move': g.move(sys.argv[2]) elif task == 'nudge': nudge(g, sys.argv[2]) elif task == 'slew': ra = Angle(sys.argv[2], unit='hour') dec = Angle(sys.argv[3], unit='degree') slew(g, ra, dec) elif task == 'help': usage() else: usage() #y=GTO900() #print y.ra(), y.dec() #y.lst(), y.get_local_time(), y.get_local_date() #print y.get_UTC_offset(), y.get_longitude(), y.get_latitude() #print y.command_ra(12,01,34) #print y.command_dec(-37,01,34) #print y.slew() #print y.ra(), y.dec() #print y.alt(), y.az() #print y.move('e') #print y.alt(), y.az()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 9078, 70, 1462, 12865, 4909, 9729, 284, 7071, 351, 257, 6468, 305, 12, 746, 23154, 308, 1462, 12865, 3817, 198, 37811, 198, 198, 11748, 11389, 198, 11748, 33245, 198, 11748, 25064...
2.057536
1,599
# -*- coding: utf-8 -*- """ Created on Wed Jun 23 15:56:55 2021 @author: Kathryn Haske Create plotly graphs for webpage """ import pandas as pd import plotly.graph_objs as go def line_graph(x_list, df, name_col, y_cols, chart_title, x_label, y_label): """ Function to create plotly line graph Args: x_list (list): graph x values df (Pandas DataFrame): dataframe to use for series and y-values name_col (string): df column to use for series names y_cols (int or slice object): df column numbers to use for y-values chart_title (string): title for chart x_label (string): label for x-axis y_label (string): label for y-axis Returns: dictionary for plotly line graph """ graph = [] for index, row in df.iterrows(): graph.append(go.Scatter( x = x_list, y = row.tolist()[y_cols], mode = 'lines', name = row[name_col] )) graph_layout = dict(title = chart_title, xaxis = dict(title = x_label), yaxis = dict(title = y_label), ) return dict(data=graph, layout=graph_layout) def scatter_plot(x_vals, y_vals, names, chart_title, x_label, y_label): """ Function to create plotly scatter plot Args: x_vals (list): graph x values y_vals (list): graph y values names (list of strings): title for each marker chart_title (string): title for chart x_label (string): label for x-axis y_label (string): label for y-axis Returns: dictionary for plotly scatter plot """ graph= [go.Scatter( x = x_vals, y = y_vals, mode = 'markers', text=names, marker=dict( color=y_vals, #set color equal to a variable colorscale='Viridis' # plotly colorscale ) )] graph_layout = dict(title = chart_title, xaxis = dict(title = x_label), yaxis = dict(title = y_label), ) return dict(data=graph, layout=graph_layout) def bar_chart(x_vals, y_vals, chart_title, x_label, y_label): """ Function to create plotly bar graph Args: x_vals (list): graph x values y_vals (list): graph y values chart_title (string): title for chart x_label (string): label for x-axis y_label (string): label for y-axis Returns: dictionary for plotly bar graph """ graph = [go.Bar( x = x_vals, y = y_vals )] graph_layout = dict(title = chart_title, xaxis = dict(title = x_label), yaxis = dict(title = y_label), ) return dict(data=graph, layout=graph_layout)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 3300, 7653, 2242, 1315, 25, 3980, 25, 2816, 33448, 198, 198, 31, 9800, 25, 48674, 7875, 365, 198, 198, 16447, 7110, 306, 28770, 329, 35699, 198, ...
2.133234
1,336
import jax.numpy as jnp from jax import vmap from jax.scipy.optimize import minimize import chex import typing_extensions from typing import Any, NamedTuple import warnings from jsl.experimental.seql.agents.agent_utils import Memory from jsl.experimental.seql.agents.base import Agent from jsl.experimental.seql.utils import posterior_noise, mse Params = Any def bfgs_agent(objective_fn: ObjectiveFn = mse, model_fn: ModelFn = lambda mu, x: x @ mu, obs_noise: float = 0.01, buffer_size: int = jnp.inf, threshold: int = 1): assert threshold <= buffer_size memory = Memory(buffer_size) return Agent(init_state, update, predict)
[ 11748, 474, 897, 13, 77, 32152, 355, 474, 37659, 198, 6738, 474, 897, 1330, 410, 8899, 198, 6738, 474, 897, 13, 1416, 541, 88, 13, 40085, 1096, 1330, 17775, 198, 198, 11748, 1125, 87, 198, 11748, 19720, 62, 2302, 5736, 198, 6738, 19...
2.465753
292
from .abusech import AbuseCh from collections import namedtuple from datetime import datetime
[ 6738, 764, 47158, 354, 1330, 24221, 1925, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, 6738, 4818, 8079, 1330, 4818, 8079, 628 ]
4.318182
22
# Copyright 2021 John Reese # Licensed under the MIT license from .cli import CliTest from .core import CoreTest
[ 2, 15069, 33448, 1757, 39929, 198, 2, 49962, 739, 262, 17168, 5964, 198, 198, 6738, 764, 44506, 1330, 1012, 72, 14402, 198, 6738, 764, 7295, 1330, 7231, 14402, 198 ]
3.931034
29
"""eafm fixtures.""" import pytest from tests.async_mock import patch
[ 37811, 68, 1878, 76, 34609, 526, 15931, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 5254, 13, 292, 13361, 62, 76, 735, 1330, 8529, 628, 198 ]
2.846154
26
import os from django.conf import settings from django.core.checks import Error, register from thorbanks.settings import configure, parse_banklinks
[ 11748, 28686, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 7295, 13, 42116, 1330, 13047, 11, 7881, 198, 198, 6738, 294, 27688, 2283, 13, 33692, 1330, 17425, 11, 21136, 62, 17796, 28751, 628, 198 ]
3.8
40
"""Defining and analysing axisymmetric optical systems.""" import itertools from functools import singledispatch from dataclasses import dataclass from abc import ABC, abstractmethod from typing import Sequence, Tuple, Mapping import numpy as np import scipy.optimize from . import abcd, paraxial, functions, ri from .functions import calc_sphere_sag # TODO Make Interface composition of Surface and refractive indeices. class Surface(ABC): """An axisymmetric surface between two media. TODO define radius. Is sag constant outside this i.e. is sag(rho) = sag(radius) for rho > radius?""" roc: float radius: float class ConicSurface(Surface): # TODO move to rt1 # def make_profile(self): # return rt1.ConicProfile(self.roc, self.kappa, self.alphas) def calc_sag(self, rho, derivative: bool = False): """Calculate sag of surface. Positive ROC means positive sag. Args: rho: Distance from center. derivative: If True, tuple of sag and its derivative is returned. """ sag = functions.calc_conic_sag(self.roc, self.kappa, self.alphas, rho, False) if derivative: grad_sag = functions.calc_conic_sag(self.roc, self.kappa, self.alphas, rho, True) return sag, grad_sag else: return sag # TODO make radius of each segment the outer radius rather than the incremental radius. class SingletSequence: def __init__(self, singlets: Sequence[Singlet], spaces: Sequence[float], n_external: ri.Index = ri.vacuum): """A sequence of singlets in a homogeneous medium with external and internal spaces. The first and last spaces must be included i.e. len(spaces) = len(singlets) + 1. """ assert len(spaces) == len(singlets) + 1 self.singlets = tuple(singlets) self.spaces = tuple(spaces) self.n_external = n_external self.center_length = sum(self.spaces) + sum(s.thickness for s in self.singlets)
[ 37811, 7469, 3191, 290, 11090, 278, 7877, 13560, 3020, 19482, 18480, 3341, 526, 15931, 198, 11748, 340, 861, 10141, 198, 6738, 1257, 310, 10141, 1330, 31958, 8802, 963, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 6738, 450, ...
2.63089
764
from sys import argv, exit from os.path import expanduser as expu, expandvars as expv from os.path import basename, dirname, abspath, isdir, exists from subprocess import Popen, PIPE from builtins import input from rm_protection.config import Config c = Config() evaledpaths = [] if __name__ == "__main__": rm()
[ 6738, 25064, 1330, 1822, 85, 11, 8420, 198, 6738, 28686, 13, 6978, 1330, 4292, 7220, 355, 1033, 84, 11, 4292, 85, 945, 355, 1033, 85, 198, 6738, 28686, 13, 6978, 1330, 1615, 12453, 11, 26672, 3672, 11, 2352, 6978, 11, 318, 15908, 11...
3.074766
107
""" """ import logging import re import string from enum import IntEnum from functools import lru_cache from typing import Tuple, Iterator from nltk.corpus import stopwords from nltk.tokenize import ToktokTokenizer from nltk.tokenize.api import TokenizerI from ..config import RegexConfigType, PipelineConfigType, load_regex_conf, load_conf __all__ = [ 'sent_tokenize', 'TokTok', 'token_type', 'to_token', 'TokenType', 'iTokenTuple', 'russian_stopwords', 'replace_bigrams', 'KILO_POSTFIX', 'init_cache', 'cache_clear', 'get_tokenizer' ] logger = logging.getLogger('rtn') # , "" (e.g. 5, 5 ) KILO_POSTFIX = '%' russian_stopwords = stopwords.words("russian") _spaces = string.whitespace _punct = set(f'{string.punctuation}{"=#-``"}{string.whitespace}') _isolating_punct = {'"', "'", '{', '}', '[', ']', '(', ')', '', ''} _synonyms = load_conf(PipelineConfigType.SYNONIMS) _regex_time = load_regex_conf(RegexConfigType.TIME) def sent_tokenize(sentence: str, tokenizer: TokenizerI) -> Iterator[iTokenTuple]: """ :param sentence: :param tokenizer: NLTK-TokenizerI """ return map(to_token, tokenizer.tokenize(sentence)) def token_type(token_string: str) -> TokenType: """ """ if not token_string: return TokenType.NONE if token_string in _spaces: # "in" works faster then calling a method ' '.isspace() return TokenType.SPACE elif token_string in _isolating_punct: return TokenType.PUNKT_ISO elif token_string in _punct: return TokenType.PUNKT elif token_string.isnumeric(): return TokenType.NUM rextype = get_regex_type() type_ = rextype(token_string) if type_ is not TokenType.NONE: return type_ return TokenType.TXT def to_token(token_string: str) -> iTokenTuple: """ >>> to_token('.') ('.', TokenType.PUNKT) >>> to_token('1') ('1', TokenType.NUM) >>> to_token('hello@gmail.com') ('hello@gmail.com', TokenType.EMAIL) :param token_string: """ return token_string, token_type(token_string) def replace_bigrams(tokens: Iterator[iTokenTuple]) -> Iterator[iTokenTuple]: """ . " " "-", . >>> from text_normalizer.tokenization import replace_bigrams >>> replace_bigrams(iter(['', TokenType.TXT), ('', TokenType.TXT)])) ('-', TokenType.TXT) """ crnt = None buffer = [] for token, _type in tokens: crnt, prev = token, crnt synonym = _synonyms.get(f'{crnt}', crnt) if prev: bigram = _synonyms.get(f'{prev} {crnt}') if bigram: buffer[-1] = (bigram, _type) continue buffer.append((synonym, _type)) yield from buffer def init_cache(): get_regex_type() get_tokenizer() logger.debug('Cache initiated') def cache_clear(): get_regex_type.cache_clear() get_tokenizer.cache_clear() logger.debug('Cache cleared')
[ 37811, 220, 220, 220, 220, 220, 37227, 198, 11748, 18931, 198, 11748, 302, 198, 11748, 4731, 198, 6738, 33829, 1330, 2558, 4834, 388, 198, 6738, 1257, 310, 10141, 1330, 300, 622, 62, 23870, 198, 6738, 19720, 1330, 309, 29291, 11, 40806,...
2.303328
1,322
from array import array import rx import rxsci as rs
[ 6738, 7177, 1330, 7177, 198, 11748, 374, 87, 198, 11748, 374, 34223, 979, 355, 44608, 628 ]
3.375
16
#!/usr/bin/env python3 """============================================================================= los for Little-Oven. los (Little Oven Setup) prepares a Raspberry Pi for Little-Oven development. This module does the actual work. los (no extension) is a bash script that creates a service that runs this code. Running the following puts the whole mess in motion... curl -s "https://raw.githubusercontent.com/Coding-Badly/Little-Oven/master/pi/los" | bash journalctl -u los.service ---------------------------------------------------------------------------- Copyright 2019 Brian Cook (aka Coding-Badly) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================""" import grp import json import os import pathlib import pwd import requests import stat import subprocess import time import uuid def wall(text): subprocess.run(['wall',text], check=True) def wall_and_print(text, step=None): if step is not None: text = 'Step #{}: {}'.format(int(step), text) wall(text) print(text) def update_then_upgrade(): time.sleep(5.0) wall('Update the APT package list.') subprocess.run(['apt-get','-y','update'], check=True) wall('Upgrade APT packages.') subprocess.run(['apt-get','-y','upgrade'], check=True) def simple_get(source_url, destination_path): r = requests.get(source_url, stream=True) r.raise_for_status() with destination_path.open('wb') as f: for chunk in r.iter_content(64*1024): f.write(chunk) def check_global_config(): global global_config if path_los_json.exists(): with path_los_json.open() as f: global_config = json.load(f) else: global_config = dict() csm = CurrentStepManager() path_los_json = pathlib.Path('los.json') check_global_config() MODE_EXECUTABLE = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH need_reboot = False go_again = True while go_again: go_again = False if csm.get_current_step() == 1: wall_and_print('Ensure the operating system is up-to-date.', csm.get_current_step()) update_then_upgrade() need_reboot = True csm.increment_current_step() elif csm.get_current_step() == 2: wall_and_print('Install Git.', csm.get_current_step()) subprocess.run(['apt-get','-y','install','git'], check=True) go_again = True csm.increment_current_step() elif csm.get_current_step() == 3: wall_and_print('Install Python development.', csm.get_current_step()) subprocess.run(['apt-get','-y','install','python3-dev'], check=True) go_again = True csm.increment_current_step() elif csm.get_current_step() == 4: wall_and_print('Ensure the operating system is up-to-date again.', csm.get_current_step()) update_then_upgrade() need_reboot = True csm.increment_current_step() elif csm.get_current_step() == 5: wall_and_print('Install pip.', csm.get_current_step()) path_get_pip = pathlib.Path('get-pip.py') simple_get('https://bootstrap.pypa.io/get-pip.py', path_get_pip) subprocess.run(['python3',str(path_get_pip)], check=True) path_get_pip.unlink() go_again = True csm.increment_current_step() elif csm.get_current_step() == 6: wall_and_print('Install Python modules required by this module.', csm.get_current_step()) subprocess.run(['pip','install', 'xkcdpass'], check=True) go_again = True csm.increment_current_step() elif csm.get_current_step() == 7: wall_and_print('Get the global configuration file.', csm.get_current_step()) base_url = os.environ.get('LOS_BASE_URL', 'https://raw.githubusercontent.com/Coding-Badly/Little-Oven/master/pi') get_this = base_url + '/' + 'los.json' try: simple_get(get_this, path_los_json) except requests.exceptions.HTTPError: pass check_global_config() go_again = True csm.increment_current_step() elif csm.get_current_step() == 8: wall_and_print('Set the password using the https://xkcd.com/936/ technique.', csm.get_current_step()) from xkcdpass import xkcd_password as xp wordfile = xp.locate_wordfile() mywords = xp.generate_wordlist(wordfile=wordfile, min_length=5, max_length=8) new_password = xp.generate_xkcdpassword(mywords, delimiter=',', numwords=3) wall_and_print(' The new password is...') wall_and_print(' {}'.format(new_password)) # fix: Send the new password to a repository. new_password = 'whatever' # rmv pi_new_password = ('pi:' + new_password).encode('ascii') subprocess.run("chpasswd", input=pi_new_password, check=True) go_again = True csm.increment_current_step() elif csm.get_current_step() == 9: wall_and_print('Change the hostname.', csm.get_current_step()) path_hostname = pathlib.Path('/etc/hostname') path_hostname.write_text('Little-Oven\n') subprocess.run(['sed','-i',"s/raspberrypi/Little-Oven/",'/etc/hosts'], check=True) need_reboot = True csm.increment_current_step() elif csm.get_current_step() == 10: wall_and_print('Change the timezone.', csm.get_current_step()) # Why localtime has to be removed... # https://bugs.launchpad.net/ubuntu/+source/tzdata/+bug/1554806 # date "+%Z %z" pathlib.Path('/etc/timezone').write_text('America/Chicago\n') pathlib.Path('/etc/localtime').unlink() subprocess.run(['dpkg-reconfigure','-f','noninteractive','tzdata'], check=True) go_again = True csm.increment_current_step() elif csm.get_current_step() == 11: wall_and_print('Change the keyboard layout.', csm.get_current_step()) # debconf-get-selections | grep keyboard-configuration # The top entry is suspect. "gb" was the value after changing # keyboards using dpkg-reconfigure. keyboard_conf = """ keyboard-configuration\tkeyboard-configuration/xkb-keymap\tselect\tus keyboard-configuration\tkeyboard-configuration/layoutcode\tstring\tus keyboard-configuration\tkeyboard-configuration/layout\tselect\tEnglish (US) keyboard-configuration\tkeyboard-configuration/variant\tselect\tEnglish (US) """.encode("ascii") subprocess.run("debconf-set-selections", input=keyboard_conf, check=True) subprocess.run(['dpkg-reconfigure','-f','noninteractive','keyboard-configuration'], check=True) go_again = True csm.increment_current_step() elif csm.get_current_step() == 12: wall_and_print('Change the locale.', csm.get_current_step()) # locale locale_conf = """ locales\tlocales/locales_to_be_generated\tmultiselect\ten_US.UTF-8 UTF-8 locales\tlocales/default_environment_locale\tselect\ten_US.UTF-8 """.encode("ascii") subprocess.run("debconf-set-selections", input=locale_conf, check=True) subprocess.run(['sed','-i',"s/^# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/",'/etc/locale.gen'], check=True) subprocess.run(['dpkg-reconfigure','-f','noninteractive','locales'], check=True) subprocess.run(['update-locale','LANG=en_US.UTF-8'], check=True) go_again = True csm.increment_current_step() elif csm.get_current_step() == 13: wall_and_print('Configure Git.', csm.get_current_step()) this_mac = format(uuid.getnode(), 'X') config_by_this_mac = global_config.get(this_mac, None) config_github = config_by_this_mac.get('github', None) if config_by_this_mac else None if config_github: # Set basic Git configuration. git_user_name = config_github.get('user.name', 'Git User Name Goes Here') git_user_email = config_github.get('user.email', 'whomever@dallasmakerspace.org') git_core_editor = config_github.get('core.editor', 'nano') subprocess.run(['git','config','--system','user.name',git_user_name], check=True) subprocess.run(['git','config','--system','user.email',git_user_email], check=True) subprocess.run(['git','config','--system','core.editor',git_core_editor], check=True) # Ensure the .ssh directory exists. path_dot_ssh = pathlib.Path('/home/pi/.ssh') # https://superuser.com/questions/215504/permissions-on-private-key-in-ssh-folder dm = DirectoryMaker() dm.mkdir(path_dot_ssh) # Add a Github section to the .ssh/config file. path_ssh_config = path_dot_ssh / 'config' with path_ssh_config.open('at') as f: f.write('Host github.com\n') f.write(' User git\n') f.write(' Hostname github.com\n') f.write(' PreferredAuthentications publickey\n') f.write(' IdentityFile ~/.ssh/github/id_rsa\n') dm.chown(path_ssh_config) # Create a github subdirectory for the Github key pair. path_github = path_dot_ssh / 'github' dm.mkdir(path_github) # Generate the Github key pair. path_id_rsa = path_github / 'id_rsa' # ssh-keygen -t rsa -C "arduino.tiny@gmail.com" -b 1024 -N '' -f ~/.ssh/github/id_rsa subprocess.run(['ssh-keygen','-t','rsa','-C',git_user_email,'-b','4096','-N','','-f',str(path_id_rsa)], check=True) dm.chown(path_id_rsa) dm.chown(path_id_rsa.with_suffix('.pub')) go_again = True csm.increment_current_step() elif csm.get_current_step() == 14: # wall_and_print('Install PiFace Digital 2 packages from GitHub.', csm.get_current_step()) # # Common # subprocess.run(['git','clone','git://github.com/piface/pifacecommon.git','/home/pi/python-things/pifacecommon'], check=True) # subprocess.run(['python3','/home/pi/python-things/pifacecommon/setup.py','install'], cwd='/home/pi/python-things/pifacecommon/', check=True) # #subprocess.run(['rm','-rf','/home/pi/python-things/pifacecommon'], check=True) # # Digital I/O # subprocess.run(['git','clone','git://github.com/piface/pifacedigitalio.git','/home/pi/python-things/pifacedigitalio'], check=True) # subprocess.run(['python3','/home/pi/python-things/pifacedigitalio/setup.py','install'], cwd='/home/pi/python-things/pifacedigitalio/', check=True) # #subprocess.run(['rm','-rf','/home/pi/python-things/pifacedigitalio'], check=True) go_again = True csm.increment_current_step() elif csm.get_current_step() == 15: # wall_and_print('Install python-dispatch package from GitHub.', csm.get_current_step()) # subprocess.run(['git','clone','https://github.com/Coding-Badly/python-dispatch.git','/home/pi/python-things/python-dispatch'], check=True) # subprocess.run(['python3','/home/pi/python-things/python-dispatch/setup.py','install'], cwd='/home/pi/python-things/python-dispatch/', check=True) # #subprocess.run(['rm','-rf','/home/pi/python-dispatch'], check=True) go_again = True csm.increment_current_step() elif csm.get_current_step() == 16: wall_and_print('Clone the Little Oven.', csm.get_current_step()) # git clone git@github.com:Coding-Badly/Little-Oven.git /home/pi/Little-Oven # git clone https://github.com/Coding-Badly/Little-Oven.git /home/pi/Little-Oven subprocess.run(['git','clone','https://github.com/Coding-Badly/Little-Oven.git','/home/pi/Little-Oven'], check=True) try: subprocess.run(['git','checkout','-t','remotes/origin/master'], cwd='/home/pi/Little-Oven', stderr=subprocess.PIPE, check=True) except subprocess.CalledProcessError as exc: if not "already exists" in exc.stderr.decode("utf-8"): raise # Change the remote url to use ssh. # git remote set-url origin git@github.com:Coding-Badly/Little-Oven.git subprocess.run(['git','remote','set-url','origin','git@github.com:Coding-Badly/Little-Oven.git'], cwd='/home/pi/Little-Oven', check=True) # Use pip to install dependencies. path_requirements = pathlib.Path('/home/pi/Little-Oven/requirements.txt') if path_requirements.exists(): subprocess.run(['pip','install','-U','-r',str(path_requirements)], check=True) # Fix ownership of the Little-Oven repository. subprocess.run(['chown','-R','pi:pi','/home/pi/Little-Oven'], check=True) # Prepare the cache directory. dm = DirectoryMaker(default_final_mode=0o755) path_cache = pathlib.Path('/var/cache/Rowdy Dog Software/Little-Oven/pans') dm.mkdir(path_cache, parents=True) go_again = True csm.increment_current_step() elif csm.get_current_step() == 17: # wall_and_print('Install PiFace Digital 2 initialization service.', csm.get_current_step()) # subprocess.run(['cp','/home/pi/Little-Oven/pi/init_PiFace_Digital_2.service','/etc/systemd/system/init_PiFace_Digital_2.service'], check=True) # subprocess.run(['systemctl','enable','init_PiFace_Digital_2.service'], check=True) # need_reboot = True go_again = True csm.increment_current_step() elif csm.get_current_step() == 18: wall_and_print('Configure Rust to be easily installed.', csm.get_current_step()) # Download rustup.sh to a common location and make it Read + Execute # for everyone. Writable for the owner (root). path_rustup_sh = pathlib.Path('/usr/local/bin/rustup.sh') simple_get('https://sh.rustup.rs', path_rustup_sh) path_rustup_sh.chmod(MODE_EXECUTABLE) go_again = True csm.increment_current_step() elif csm.get_current_step() == 19: wall_and_print('Install FUSE (support for VeraCrypt).', csm.get_current_step()) subprocess.run(['apt-get','-y','install','fuse'], check=True) go_again = True csm.increment_current_step() elif csm.get_current_step() == 20: wall_and_print('Configure VeraCrypt to be easily installed.', csm.get_current_step()) # Prepare a directory for the VeraCrypt files. dm = DirectoryMaker(default_final_mode=0o755) path_temp = pathlib.Path('./veracrypt_CErQ2nnwvZCVeKQHhLV24TWW') dm.mkdir(path_temp, parents=True) # Download the install script path_tar_bz2 = path_temp / 'veracrypt-setup.tar.bz2' simple_get('https://launchpad.net/veracrypt/trunk/1.21/+download/veracrypt-1.21-raspbian-setup.tar.bz2', path_tar_bz2) # Extract the contents subprocess.run(['tar','xvfj',str(path_tar_bz2),'-C',str(path_temp)], check=True) path_src = path_temp / 'veracrypt-1.21-setup-console-armv7' path_dst = pathlib.Path('/usr/local/bin/veracrypt-setup') # Copy the console setup to a location on the PATH subprocess.run(['cp',str(path_src),str(path_dst)], check=True) # Remove the temporary directory subprocess.run(['rm','-rf',str(path_temp)], check=True) # Run the install script #subprocess.run(['bash',str(path_setup),'--quiet'], check=True) # mkdir veracrypt_CErQ2nnwvZCVeKQHhLV24TWW # wget --output-document=./veracrypt_CErQ2nnwvZCVeKQHhLV24TWW/veracrypt-setup.tar.bz2 https://launchpad.net/veracrypt/trunk/1.21/+download/veracrypt-1.21-raspbian-setup.tar.bz2 # tar xvfj ./veracrypt_CErQ2nnwvZCVeKQHhLV24TWW/veracrypt-setup.tar.bz2 -C ./veracrypt_CErQ2nnwvZCVeKQHhLV24TWW # ./veracrypt_CErQ2nnwvZCVeKQHhLV24TWW/veracrypt-1.21-setup-console-armv7 --check # ./veracrypt_CErQ2nnwvZCVeKQHhLV24TWW/veracrypt-1.21-setup-console-armv7 --quiet # rm -rf veracrypt_CErQ2nnwvZCVeKQHhLV24TWW go_again = True csm.increment_current_step() elif csm.get_current_step() == 21: wall_and_print('Check for Rust and VeraCrypt after login.', csm.get_current_step()) # Write the following to /etc/profile.d/check_for_rust_and_veracrypt.sh and make it # executable. check_for_rust_and_veracrypt = """#!/bin/bash if [ ! -e $HOME/.cargo ]; then rustup.sh -y fi if ! command -v veracrypt; then veracrypt-setup fi """ path_check_for = pathlib.Path('/etc/profile.d/check_for_rust_and_veracrypt.sh') path_check_for.write_text(check_for_rust_and_veracrypt) path_check_for.chmod(MODE_EXECUTABLE) go_again = True csm.increment_current_step() #elif csm.get_current_step() == 20: # wall_and_print('One last reboot for good measure.', csm.get_current_step()) # need_reboot = True # csm.increment_current_step() # fix: Configure Little-Oven to automatically run on boot. else: wall_and_print('Little-Oven installed. Disabling the los service.') subprocess.run(['systemctl','disable','los.service'], check=True) if need_reboot: wall_and_print('REBOOT!') time.sleep(5.0) subprocess.run(['reboot'], check=True)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 23926, 25609, 28, 628, 220, 22346, 329, 7703, 12, 46, 574, 13, 220, 22346, 357, 22253, 440, 574, 31122, 8, 25978, 257, 24244, 13993, 329, 198, 220, 7703, 12, 46, 574, 2478...
2.328605
7,614
from django.contrib.auth.models import User from django.db.models import Model, CharField, TextField, ForeignKey, CASCADE
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 1330, 9104, 11, 3178, 15878, 11, 8255, 15878, 11, 8708, 9218, 11, 35106, 34, 19266, 628 ]
3.416667
36
import streamlit as st import yaml from load_css import local_css import tensorflow as tf import tensorflow_hub as hub import tensorflow_text as text import numpy as np from random import sample import os local_css("style.css") prediction_key = { 0:'Gastroenterology', 1:'Neurology', 2:'Orthopedic', 3:'Radiology', 4:'Urology' } # Load model from file model = tf.keras.models.load_model('/home/muody/saved_model/my_model', compile=False) # load data if st.button("New Text Sample"): main()
[ 11748, 4269, 18250, 355, 336, 198, 11748, 331, 43695, 198, 6738, 3440, 62, 25471, 1330, 1957, 62, 25471, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 11192, 273, 11125, 62, 40140, 355, 12575, 198, 11748, 11192, 273, 11125, 62, ...
2.475336
223
#!/usr/bin/env python # -*- coding: utf-8 -*- """Python Team Awareness Kit (PyTAK) Module Tests.""" import asyncio import urllib import pytest import pytak __author__ = 'Greg Albrecht W2GMD <oss@undef.net>' __copyright__ = 'Copyright 2022 Greg Albrecht' __license__ = 'Apache License, Version 2.0'
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 37906, 4816, 36735, 10897, 357, 20519, 5603, 42, 8, 19937, 30307, 526, 15931, 198, 198, 11748, 30351, 952, ...
2.686957
115
# test_aoc_day_02.py import pytest import solution.aoc_day_02 as aoc def test_parse_test_solution(test_solution): """Test that input is parsed properly""" assert test_solution.data == [ ("forward", 5), ("down", 5), ("forward", 8), ("up", 3), ("down", 8), ("forward", 2), ] def test_part1_test_solution(test_solution): """Test part 1 on example input""" assert test_solution.part1() == 150 def test_part2_test_solution(test_solution): """Test part 2 on example input""" assert test_solution.part2() == 900 def test_part1_exercise_solution(exercise_solution): """Test part 1 on exercise_solution input""" assert exercise_solution.part1() == 1383564 def test_part2_exercise_solution(exercise_solution): """Test part 2 on exercise_solution input""" assert exercise_solution.part2() == 1488311643
[ 2, 1332, 62, 64, 420, 62, 820, 62, 2999, 13, 9078, 198, 198, 11748, 12972, 9288, 198, 11748, 4610, 13, 64, 420, 62, 820, 62, 2999, 355, 257, 420, 628, 628, 198, 4299, 1332, 62, 29572, 62, 9288, 62, 82, 2122, 7, 9288, 62, 82, 2...
2.555556
351
from operator import add, sub import numpy as np from scipy.stats import norm
[ 6738, 10088, 1330, 751, 11, 850, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 34242, 1330, 2593, 628 ]
3.478261
23
s=input() print(s+'s' if s[-1]!='s' else s+'es')
[ 82, 28, 15414, 3419, 198, 4798, 7, 82, 10, 6, 82, 6, 611, 264, 58, 12, 16, 60, 0, 11639, 82, 6, 2073, 264, 10, 6, 274, 11537 ]
1.714286
28
from __future__ import annotations import operator from enum import Enum from itertools import product from typing import Dict, Union import numpy as np #################################################################################################### def h(x, fx): """helper function as in the PLoS article, doi:10.1371/journal.pcbi.1005352.t003 pg 16/24""" fx = fx % 3 x = x % 3 if fx > x: return x + 1 elif fx < x: return x - 1 else: return x #################################################################################################### # monomial and sparse polynomial classes. These should be faster than the sympy versions due to # their reduced scope. #################################################################################################### #################################################################################################### def rename_helper(expression: Union[Expression, int], name_dict: Dict[str, str]): if is_integer(expression): return expression else: return expression.rename_variables(name_dict=name_dict) #################################################################################################### # actions on expressions, suitable for conversion to polynomial form. Not best for simulator. #################################################################################################### #################################################################################################### __rmul__ = __mul__ def as_poly(self): """converts this monomial to a polynomial with only one term""" return Mod3Poly({self: 1}) __repr__ = __str__ # def as_sympy(self): # # sympy empty product is 1, consistent with power_dict # return sympy.prod([sympy.Symbol(var, integer=True) ** pow # for var, pow in self._power_dict.items()]) # # Fun fact: sympy doesn't recognize Symbol(var) and Symbol(var, integer=True) to be the same #################################################################################################### def eval(self, variable_dict): """evaluates the polynomial. variable_dict is expected to be a dict containing str:Expression or Monomial:Expression pairs. The latter are constrained to be of single-variable type. """ if type(variable_dict) != dict: raise Exception("Mod3Poly.eval is not defined on this input") accumulator = Mod3Poly.zero() for monomial, coeff in self.coeff_dict.items(): accumulator += coeff * monomial.eval(variable_dict) return accumulator def get_variable_set(self): """return a set containing all variables which occur in this polynomial""" var_set = set() for monomial in self.coeff_dict: var_set = var_set.union(monomial.get_variable_set()) return var_set def __clear_zero_monomials(self): """purge unneeded data""" self.coeff_dict = {monomial: self.coeff_dict[monomial] for monomial in self.coeff_dict if self.coeff_dict[monomial] != 0} # assure at least one entry if len(self.coeff_dict) == 0: self.coeff_dict = {Monomial.unit(): 0} __radd__ = __add__ __rmul__ = __mul__ __repr__ = __str__ # def as_sympy(self): # return sum([coeff * expr.as_sympy() for expr, coeff in self.coeff_dict.items()])
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 11748, 10088, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 340, 861, 10141, 1330, 1720, 198, 6738, 19720, 1330, 360, 713, 11, 4479, 198, 198, 11748, 299, 32152, 355, 45941, 628, 198, 198,...
3.034188
1,170
# Copyright 2021 PingCAP, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # See the License for the specific language governing permissions and # limitations under the License. import operator from django.db.backends.mysql.features import ( DatabaseFeatures as MysqlDatabaseFeatures, ) from django.utils.functional import cached_property
[ 2, 15069, 33448, 34263, 33177, 11, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2...
3.707182
181
import numpy as np import sys import glob rbp=sys.argv[1] kmer=sys.argv[2] pfile_list=glob.glob("result_VDM3_"+rbp+"_positive_"+kmer+"_*.npy") pfile1=np.load(pfile_list[0]) psha=np.shape(pfile1) pmatrix=np.zeros(psha) for pfile in pfile_list: file=np.load(pfile) # file=np.fromfile(pfile,dtype=np.float32) pmatrix+=file np.save("positive_"+rbp+"_vdm3_nopaircontrol_distance_matrix_"+kmer+"mer.npy",pmatrix)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 25064, 198, 11748, 15095, 198, 26145, 79, 28, 17597, 13, 853, 85, 58, 16, 60, 198, 74, 647, 28, 17597, 13, 853, 85, 58, 17, 60, 198, 198, 79, 7753, 62, 4868, 28, 4743, 672, 13, 4743, 67...
1.985849
212
'''A common interface to FGVC datasets. Currently supported datasets are - CUB Birds - CUB Birds with expert labels - NA Birds - Stanford Cars - Stanford Dogs - Oxford Flowers - Oxford FGVC Aircraft - Tsinghua Dogs Datasets are constructed and used following the pytorch data.utils.data.Dataset paradigm, and have the signature fgvcdata.Dataset(root='path/to/data/'[,transform[,target_transform[,train]]]) `root` is the path to the base folder for the dataset. Additionally, `root` can end in `/train` or `/test`, to indicate whether to use train or test data -- even if the root folder does not contain `train` or `test` subfolders. The use of training or test data can also be specified through the use of the `train` flag (the path extension on `root` takes precedence). `transform` and `target_transform` are optional callables that preprocess data and targets respectively. It is common to use the torchvision.transforms module for this. ''' from .birds import * from .cars import * from .dogs import * from .aircraft import * from .flowers import * from .icub import * IMAGENET_STATS = ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)) datasets = [] for f in [birds,icub,cars,dogs,aircraft,flowers]: datasets += f.__all__
[ 7061, 6, 32, 2219, 7071, 284, 25503, 15922, 40522, 13, 198, 198, 21327, 4855, 40522, 389, 198, 12, 327, 10526, 27124, 198, 12, 327, 10526, 27124, 351, 5887, 14722, 198, 12, 11746, 27124, 198, 12, 13863, 25277, 198, 12, 13863, 21367, 1...
3.31016
374
from typing import List from celery.result import AsyncResult from fastapi import APIRouter, status, Depends, Form, UploadFile, File, Request, WebSocket from fastapi.responses import RedirectResponse from app.auth import service from app.auth.models import User from app.auth.permission import is_active from app.auth.schemas import ( RegisterUser, VerificationUUID, Tokens, RefreshToken, AccessToken, Password, ChangeUserDataResponse, ChangeUserData, Channel, ChangePassword, Tasks, ) from app.config import oauth from app.db import async_session from app.schemas import Message from app.videos.schemas import GetVideo, SubscriptionsVideos auth_router = APIRouter()
[ 6738, 19720, 1330, 7343, 198, 198, 6738, 18725, 1924, 13, 20274, 1330, 1081, 13361, 23004, 198, 6738, 3049, 15042, 1330, 3486, 4663, 39605, 11, 3722, 11, 2129, 2412, 11, 5178, 11, 36803, 8979, 11, 9220, 11, 19390, 11, 5313, 39105, 198, ...
3.083682
239
# Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed # under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import functools import textwrap import typing import tabulate import clamav.util import mailutil from concourse.model.traits.image_scan import Notify from product.model import ComponentName, UploadResult def protecode_results_table(protecode_cfg, upload_results: typing.Iterable[UploadResult]): table = tabulate.tabulate( map(result_to_tuple, upload_results), headers=('Component Name', 'Greatest CVE', 'Container Image Reference'), tablefmt='html', ) return table
[ 2, 15069, 357, 66, 8, 13130, 48323, 7946, 393, 281, 48323, 17375, 1664, 13, 1439, 2489, 10395, 13, 770, 2393, 318, 11971, 198, 2, 739, 262, 24843, 10442, 13789, 11, 410, 13, 362, 2845, 355, 4367, 4306, 287, 262, 38559, 24290, 2393, ...
3.545714
350
import cv2 import numpy as np height = 500 width = 700 gray = np.zeros((height, width), dtype=np.uint8) # fourcc = cv2.VideoWriter_fourcc(*"MJPG") # filename = "output.avi" fourcc = cv2.VideoWriter_fourcc(*"MP4V") filename = "output.mp4" writer = cv2.VideoWriter( filename, fourcc, fps=30, frameSize=(width, height), isColor=False ) # NOTE isColor doesn't seem to influence resulting file size xs = np.arange(width // 10) ys = np.arange(height // 10) locations = np.dstack(np.meshgrid(ys, xs)).reshape(-1, 2) for y, x in locations: gray[y, x] = 255 # gray_3c = cv2.merge([gray, gray, gray]) writer.write(gray) writer.release()
[ 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 198, 17015, 796, 5323, 198, 10394, 796, 13037, 198, 44605, 796, 45941, 13, 9107, 418, 19510, 17015, 11, 9647, 828, 288, 4906, 28, 37659, 13, 28611, 23, 8, 198, 198, 2, 144...
2.51751
257
from po.base import BasePage from po.base import InvalidPageException
[ 198, 6738, 745, 13, 8692, 1330, 7308, 9876, 198, 6738, 745, 13, 8692, 1330, 17665, 9876, 16922 ]
4.117647
17
from lib import Scrape from typing import List from os import environ main()
[ 6738, 9195, 1330, 1446, 13484, 198, 6738, 19720, 1330, 7343, 198, 6738, 28686, 1330, 551, 2268, 198, 198, 12417, 3419, 198 ]
3.714286
21
var1 = "hello world" # left what you get from the right for character in var1: print(character)
[ 7785, 16, 796, 366, 31373, 995, 1, 198, 198, 2, 1364, 644, 345, 651, 422, 262, 826, 198, 1640, 2095, 287, 1401, 16, 25, 198, 220, 220, 220, 3601, 7, 22769, 8 ]
3.125
32
# -*- coding: utf-8 -*- # Generated by Django 1.11.8 on 2019-03-07 12:55 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 23, 319, 13130, 12, 3070, 12, 2998, 1105, 25, 2816, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.73913
69
# Generated by Django 3.1.7 on 2021-04-08 11:12 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 22, 319, 33448, 12, 3023, 12, 2919, 1367, 25, 1065, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
''' ---------------------------------------------------------------------------------------- This script will update the Prescribed Burn System's ePFP data according to txt input files found in the relevant scripts folder. It requires user input of the Corporate Executive Approval date, which it will then use to set PREVIOUS_YEAR, TARGET_YEAR, DATE_APPROVED and DATE_APPROVED_TO variables used by relevant functions in the script. Sample output below: Please enter the date that the Burn Program was approved by Corporate Executive (dd/mm/yyyy): 03/07/2019 Script will run with the following details: - Previous Year: 2018/2019 - Target Year: 2019/2020 - Script Data Folder: pbs/scripts/eofy_data/2019 Do you wish to continue [y/n]? y Updating financial year and setting planning status modified date for carry over currently approved ePFPs from 2018/2019. Total prescriptions in query: 331 Financial year for ABC_123(2013/2014) is not 2018/2019 or already in 2019/2020. Updated financial year and set planning status modified date for 330 carry over currently approved ePFPs Applying corporate approval and setting planning status modified date for ePFPs currently seeking approval in 2019/2020. Total prescriptions in query: 51 Applied corporate approval and set planning status modified date for 51 ePFPs that were seeking approval Updating financial year only selected ePFPs from 2018/2019 Total prescriptions in query: 330 Financial year for ABC_123(2013/2014) is not 2018/2019. Updated financial year only for 0 ePFPs 329 records already in 2019/2020 Updating priority for selected ePFPs in 2019/2020 Financial year for ABC_123(2013/2014) is not 2019/2020. Updated priority for 412 ePFPs (expected 412) Updating area for selected ePFPs in 2019/2020 Financial year for ABC_123(2013/2014) is not 2019/2020. Updated area for 412 ePFPs (expected 412) Updating perimeters for selected ePFPs in 2019/2020 Financial year for ABC_123(2013/2014) is not 2019/2020. Updated perimeter for 412 ePFPs (expected 412) Updating overall rationale for selected ePFPs in 2019/2020 Financial year for ABC_123(2013/2014) is not 2019/2020. Updated rationale for 168 ePFPs (expected 168) ---------------------------------------------------------------------------------------- ''' import os import sys import confy from django.db import transaction from django.core.wsgi import get_wsgi_application from decimal import Decimal import csv from datetime import datetime, date import pytz application = get_wsgi_application() # This is so models get loaded. try: confy.read_environment_file('.env') except: print('ERROR: Script must be runs from PROJECT BASE_DIR') exit() proj_path = os.getcwd() sys.path.append(proj_path) os.chdir(proj_path) # ---------------------------------------------------------------------------------------- # Script starts here # ---------------------------------------------------------------------------------------- from pbs.prescription.models import Prescription if __name__ == "__main__": try: SCRIPT_FOLDER = 'pbs/scripts' DATE_APPROVED_INPUT = raw_input("Please enter the date that the Burn Program was approved " "by Corporate Executive (dd/mm/yyyy): ") DATE_APPROVED = datetime.strptime(DATE_APPROVED_INPUT, '%d/%m/%Y').replace(tzinfo=pytz.UTC) if DATE_APPROVED.month != 7 or DATE_APPROVED.year != date.today().year: print('Can only run this script in July of the current year') sys.exit() DATE_APPROVED_TO = date(DATE_APPROVED.year, 9, 30) PREVIOUS_YEAR = '{}/{}'.format(DATE_APPROVED.year-1, DATE_APPROVED.year) TARGET_YEAR = '{}/{}'.format(DATE_APPROVED.year, DATE_APPROVED.year+1) SCRIPT_DATA_FOLDER = '{}/eofy_data/{}'.format(SCRIPT_FOLDER, TARGET_YEAR.split('/')[0]) except BaseException: print('Error') sys.exit() print('\nScript will run with the following details:') print(' - Previous Year: {}'.format(PREVIOUS_YEAR)) print(' - Target Year: {}'.format(TARGET_YEAR)) print(' - Script Data Folder: {}/'.format(SCRIPT_DATA_FOLDER)) CONTINUE_INPUT = raw_input("Do you wish to continue [y/n]? ") if CONTINUE_INPUT == 'y': try: with transaction.atomic(): corp_approved_carryover_ids = read_ids('{}/corp_approved_carryover.txt'.format(SCRIPT_DATA_FOLDER)) carryover_currently_approved(corp_approved_carryover_ids) seeking_approval_ids = read_ids('{}/approve_seeking_approval.txt'.format(SCRIPT_DATA_FOLDER)) update_seeking_approval(seeking_approval_ids) update_financial_year_ids = read_ids('{}/financial_year_only.txt'.format(SCRIPT_DATA_FOLDER)) update_financial_year(update_financial_year_ids) burn_priority_tuples = read_id_tuples('{}/burn_priority.txt'.format(SCRIPT_DATA_FOLDER)) update_burn_priority(burn_priority_tuples) burn_area_tuples = read_id_tuples('{}/burn_areas.txt'.format(SCRIPT_DATA_FOLDER)) update_burn_areas(burn_area_tuples) burn_perimeter_tuples = read_id_tuples('{}/burn_perimeters.txt'.format(SCRIPT_DATA_FOLDER)) update_burn_perimeters(burn_perimeter_tuples) overall_rationale_tuples = read_id_tuples_pipe_separated('{}/overall_rationales.txt' .format(SCRIPT_DATA_FOLDER)) update_overall_rationales(overall_rationale_tuples) except BaseException: print('Error') else: sys.exit()
[ 7061, 6, 16529, 22369, 198, 1212, 4226, 481, 4296, 262, 1763, 32968, 8942, 4482, 338, 304, 47, 5837, 1366, 1864, 284, 256, 742, 5128, 198, 16624, 1043, 287, 262, 5981, 14750, 9483, 13, 198, 1026, 4433, 2836, 5128, 286, 262, 26040, 103...
2.705009
2,156
import numpy as np from scipy.stats import binom from sklearn.ensemble import IsolationForest from sklearn.preprocessing import MinMaxScaler from scipy.special import erf from learnware.algorithm.anomaly_detect.base import BaseAnomalyDetect
[ 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 34242, 1330, 9874, 296, 198, 6738, 1341, 35720, 13, 1072, 11306, 1330, 1148, 21417, 34605, 198, 6738, 1341, 35720, 13, 3866, 36948, 1330, 1855, 11518, 3351, 36213, 198, 6738, 6...
3.471429
70
from nox import session
[ 6738, 645, 87, 1330, 6246, 628 ]
4.166667
6
""" Data manipulations """
[ 37811, 198, 6601, 7704, 5768, 198, 37811, 198 ]
3.375
8