content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
# Generated by Django 3.0.2 on 2020-02-09 18:12 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 513, 13, 15, 13, 17, 319, 12131, 12, 2999, 12, 2931, 1248, 25, 1065, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.766667
30
# # mostly copied from # http://bioportal.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/socket/multicast.html # import socket import struct import sys import time message = 'data worth repeating' multicast_group = ('226.1.1.1', 4321) # Create the datagram socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Set a timeout so the socket does not block indefinitely when trying # to receive data. sock.settimeout(0.2) counter = 0 try: while True: counter +=1 # Send data to the multicast group print >>sys.stderr, '%d: sending "%s"' % (counter, message ) sent = sock.sendto(message, multicast_group) time.sleep( 5 ) finally: print >>sys.stderr, 'closing socket' sock.close()
[ 2, 198, 2, 4632, 18984, 422, 198, 2, 220, 220, 2638, 1378, 8482, 404, 16906, 13, 732, 528, 9038, 13, 330, 13, 346, 14, 17319, 14, 29412, 14, 20519, 44, 2394, 54, 14, 20519, 44, 2394, 54, 14, 31628, 14, 44971, 14, 16680, 291, 459...
2.461538
312
import numpy as np from chol_factor import chol_factor from triangular import triangular # TEST: Cholesky factorization (LL') # Symmetric positive definite matrix A = np.matrix('5 1.2 0.3 -0.6;' '1.2 6 -0.4 0.9;' '0.3 -0.4 8 1.7;' '-0.6 0.9 1.7 10'); print('A = \n', A) # Computation of the L factor L = chol_factor(A) print('L = \n', L) # Check if np.allclose(A, np.dot(L, L.transpose())) == False: raise Exception('QR factorizzation test failure') # TEST: System Resolution # Ax = LL'x = b b = np.matrix("68; 9; 45; 35") print('b = \n', b) # Lk = b k = triangular(L, b, 1) print('k = \n', k) # L'x = k x = triangular(L.transpose(), k, 0) print('x = \n', x) # Check b1 = np.dot(A, x) print('b1 = \n', b1) if np.allclose(b, b1) == False: raise Exception('System resolution failure')
[ 11748, 299, 32152, 355, 45941, 198, 6738, 442, 349, 62, 31412, 1330, 442, 349, 62, 31412, 198, 6738, 46963, 1330, 46963, 198, 198, 2, 43001, 25, 609, 4316, 2584, 5766, 1634, 357, 3069, 11537, 198, 198, 2, 1632, 3020, 19482, 3967, 2189...
2.151515
396
"""Build the tkinter gui root""" import math from PyQt5.QtWidgets import *#(QWidget, QToolTip, QDesktopWidget, QPushButton, QApplication) from PyQt5.QtGui import QFont from PyQt5.QtCore import QCoreApplication, QObject, QRunnable, QThread, QThreadPool, pyqtSignal, pyqtSlot from PyQt5.QtGui import QIntValidator, QDoubleValidator import sys from PSO_system.Counting.plot import PlotCanvas from PSO_system.Counting.run import CarRunning from PSO_system.Counting.test_result import TestRunning THREADS = [] if __name__ == '__main__': print("Error: This file can only be imported. Execute 'main.py'")
[ 37811, 15580, 262, 256, 74, 3849, 11774, 6808, 37811, 198, 11748, 10688, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 54, 312, 11407, 1330, 1635, 2, 7, 48, 38300, 11, 1195, 25391, 28434, 11, 1195, 36881, 38300, 11, 1195, 49222, 21864, 1...
2.87619
210
# -*- coding: utf-8 -*- from __future__ import print_function, division from qsrlib_qsrs.qsr_dyadic_abstractclass import QSR_Dyadic_1t_Abstractclass import math
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 11, 7297, 198, 6738, 10662, 27891, 8019, 62, 48382, 3808, 13, 80, 27891, 62, 9892, 23876, 62, 397, 8709, 4871, 1330, 1195,...
2.728814
59
# NBA Stats Clustering # Copyright Matthew Strong, 2019 # gaussian mixture models with em algorithm import numpy as np from scipy import stats from clustering.Cluster import NBACluster # nba gmm class # gmm from scratch as well, more explained below
[ 2, 7403, 20595, 1012, 436, 1586, 198, 2, 15069, 9308, 13535, 11, 13130, 198, 198, 2, 31986, 31562, 11710, 4981, 351, 795, 11862, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 1330, 9756, 198, 6738, 32966, 1586, 13, 2601...
3.705882
68
import torch from torch.utils.data import DataLoader import matplotlib.pyplot as plt import sys sys.path.append("./ML") import Definitions.models as models from Definitions.dataset import Data if __name__ == "__main__": main()
[ 11748, 28034, 201, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 6060, 17401, 201, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 201, 198, 201, 198, 11748, 25064, 201, 198, 201, 198, 17597, 13, 6978, 13, 33295, 7, 1911,...
2.702128
94
from datetime import datetime, timedelta import pygame from pygame.mixer import Sound from screens.base_screen import BaseScreen from ui import colours from ui.widgets.background import LcarsBackgroundImage from ui.widgets.gifimage import LcarsGifImage from ui.widgets.lcars_widgets import LcarsButton from ui.widgets.lcars_widgets import LcarsText
[ 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 198, 198, 11748, 12972, 6057, 198, 6738, 12972, 6057, 13, 19816, 263, 1330, 9506, 198, 198, 6738, 8947, 13, 8692, 62, 9612, 1330, 7308, 23901, 198, 6738, 334, 72, 1330, 18915, 198, ...
3.330189
106
import swarm_tasks.utils.robot
[ 11748, 30077, 62, 83, 6791, 13, 26791, 13, 305, 13645, 198 ]
2.818182
11
# -*- coding: utf-8 -*- """ Created on Sun Mar 7 17:11:12 2021 @author: User SUMMATION OF PRIMES The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. 21min19s to find. """ from datetime import datetime as date # INPUTS target = 2000000 primes = [2, 3, 5, 7, 11, 13, 17, 19] control = target / 10 path = "C:/Users/User/Documents/AA - Pessoal/DataScience/Project Euler/" file = "primos_ate_" + str(target) + ".csv" print("INICIANDO BUSCA DOS NMEROS PRIMOS MENORES QUE", target) start = date.now() # PROCESSING while primes[-1] < target : candidate = nextPrime(primes[-1], primes) if candidate > target : break primes.append(candidate) # CONTROLLING if candidate >= control: print("O", len(primes), " primo ", candidate, "em", date.now() - start) control += target / 10 # OUTPUT print("\n") print("RESULTADOS:") print("ENCONTRAR OS NMEROS PRIMOS MENORES QUE", target) print("FORAM ENCONTRADOS", len(primes), "NMEROS PRIMOS") print("LTIMO PRIMO DA LISTA:", primes[-1]) print("SOMA DOS PRIMOS ENCONTRADOS:", sum(primes)) print("TEMPO TOTAL DA BUSCA:", date.now() - start) # TO FILE f = open(path + file, "w+") for i in range(len(primes)): f.write(str(i+1)) f.write("\t") # tab f.write(str(primes[i])) f.write("\r") # carriage return f.close()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 41972, 319, 3825, 1526, 220, 767, 1596, 25, 1157, 25, 1065, 33448, 201, 198, 201, 198, 31, 9800, 25, 11787, 201, 198, 201, 198, 50, 5883, 44, 6...
2.222222
648
import numpy as np import pytest from l5kit.geometry import transform_points from l5kit.rasterization.render_context import RenderContext
[ 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 9288, 198, 198, 6738, 300, 20, 15813, 13, 469, 15748, 1330, 6121, 62, 13033, 198, 6738, 300, 20, 15813, 13, 81, 1603, 1634, 13, 13287, 62, 22866, 1330, 46722, 21947, 628 ]
3.589744
39
import vim import functools import dbus try: Fcitx = FcitxComm() fcitx_loaded = True except dbus.exceptions.DBusException as e: if not vim.vars.get('silent_unsupported'): vim.command('echohl WarningMsg | echom "fcitx.vim not loaded: %s" | echohl NONE' % e) fcitx_loaded = False
[ 11748, 43907, 198, 11748, 1257, 310, 10141, 198, 198, 11748, 288, 10885, 198, 198, 28311, 25, 198, 220, 376, 47992, 87, 796, 376, 47992, 87, 6935, 3419, 198, 220, 277, 47992, 87, 62, 14578, 796, 6407, 198, 16341, 288, 10885, 13, 1069,...
2.517241
116
import requests post()
[ 11748, 7007, 628, 198, 198, 7353, 3419, 198 ]
3.25
8
# -*- coding: utf-8 -*- from avioclient.send_data import SendControls from avioclient import config if __name__ == "__main__": send_data()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 1196, 72, 38679, 1153, 13, 21280, 62, 7890, 1330, 16290, 15988, 82, 198, 6738, 1196, 72, 38679, 1153, 1330, 4566, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, ...
2.561404
57
c = float(input('Digite a temperatura em Ceusius: ')) f = (9*c + 160)/5 print(f'A temperatura de {c:.1f}C corresponde a {f:.1f}F')
[ 66, 796, 12178, 7, 15414, 10786, 19511, 578, 257, 4124, 2541, 64, 795, 20101, 385, 3754, 25, 705, 4008, 198, 69, 796, 357, 24, 9, 66, 1343, 13454, 20679, 20, 198, 4798, 7, 69, 6, 32, 4124, 2541, 64, 390, 1391, 66, 25, 13, 16, ...
2.166667
60
# not yet finished for _ in range(int(input())):print(len(list(set(input().replace("-", "")))))
[ 2, 407, 1865, 5201, 198, 1640, 4808, 287, 2837, 7, 600, 7, 15414, 28955, 2599, 4798, 7, 11925, 7, 4868, 7, 2617, 7, 15414, 22446, 33491, 7203, 12, 1600, 13538, 4008, 22305 ]
2.96875
32
import os import unittest import despyfitsutils.fitsutils as utils TESTDIR = os.path.dirname(__file__)
[ 11748, 28686, 198, 11748, 555, 715, 395, 198, 11748, 748, 9078, 21013, 26791, 13, 21013, 26791, 355, 3384, 4487, 628, 198, 51, 6465, 34720, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 8, 628 ]
2.864865
37
#!/usr/bin/env python # -*- coding: utf-8 -*- from time import gmtime, strftime from gluon.custom_import import track_changes track_changes(True) from gluon import current from pydal import * import sys reload(sys) sys.setdefaultencoding('utf-8') if request.global_settings.web2py_version < "2.14.1": raise HTTP(500, "Requires web2py 2.13.3 or newer") from gluon.contrib.appconfig import AppConfig myconf = AppConfig(reload=True) uri = "postgres://chito:yndrid@localhost/massivesms" current.db = DAL(uri,pool_size=1, check_reserved=['all'], lazy_tables=False, migrate=False) current.db.define_table('municipio', Field('descripcion', type='string', length=20, required=True, notnull=True, requires=[IS_NOT_EMPTY(error_message=('Este campo no puede ser vacio'))]), ) current.db.define_table('cargo', Field('descripcion', type='string', length=20, required=True, notnull=True, requires=[IS_NOT_EMPTY(error_message=('Este campo no puede ser vacio'))]), ) current.db.define_table('mun_cargo', Field('fk_municipio', 'reference municipio'), Field('fk_cargo', 'reference cargo'), primarykey=['fk_municipio','fk_cargo'], ) current.db.define_table('contacto', Field('numero', type='string', length=11, required=True, notnull=True,unique=True, requires=[IS_NOT_EMPTY(error_message=('Este campo no puede ser vacio'))]), Field('fk_municipio_id', 'reference municipio',required=True), Field('fk_cargo_id', 'reference cargo',required=True), ) current.db.define_table('estado_mensaje', Field('estado', length=1, required=True, notnull=True,default=1), Field('estado_envio',length=1,required=True, notnull=True,default=1), Field('fk_municipio_id', 'reference municipio',required=True), Field('fk_cargo_id', 'reference cargo',required=True), Field('destino',length=11,required=True, notnull=True), Field('mensaje',length=160,required=True, notnull=True), ) # ------------------------------------------------------------------------- response.generic_patterns = ['*'] if request.is_local else [] response.formstyle = myconf.get('forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other response.form_label_separator = myconf.get('forms.separator') or '' from gluon.tools import Auth, Service, PluginManager # host names must be a list of allowed host names (glob syntax allowed) auth = Auth(current.db, host_names=myconf.get('host.names')) service = Service() plugins = PluginManager() # ------------------------------------------------------------------------- # create all tables needed by auth if not custom tables # ------------------------------------------------------------------------- auth.define_tables(username=True, signature=False) # ------------------------------------------------------------------------- # configure email # ------------------------------------------------------------------------- mail = auth.settings.mailer mail.settings.server = 'logging' if request.is_local else myconf.get('smtp.server') mail.settings.sender = myconf.get('smtp.sender') mail.settings.login = myconf.get('smtp.login') mail.settings.tls = myconf.get('smtp.tls') or False mail.settings.ssl = myconf.get('smtp.ssl') or False # ------------------------------------------------------------------------- # configure auth policy # ------------------------------------------------------------------------- auth.settings.registration_requires_verification = False auth.settings.registration_requires_approval = False auth.settings.reset_password_requires_verification = True
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 640, 1330, 308, 76, 2435, 11, 965, 31387, 198, 6738, 1278, 84, 261, 13, 23144, 62, 11748, 1330, 2610, 62, 36653...
2.554924
1,584
import os if (os.name == 'nt' or os.name == 'dos'): try: from win32com.shell import shell import pythoncom except Exception, e: print 'WARNING: Received exception ' + `e` + ' in doing import.' print 'WARNING: Unable to import win32com.shell.shell, pythoncom.' print 'WARNING: Symbolic links and Shortcuts will not work.' from win32com.shell import shell import pythoncom, os else:
[ 201, 198, 201, 198, 11748, 28686, 201, 198, 201, 198, 361, 357, 418, 13, 3672, 6624, 705, 429, 6, 393, 28686, 13, 3672, 6624, 705, 37427, 6, 2599, 201, 198, 220, 220, 220, 1949, 25, 201, 198, 220, 220, 220, 220, 220, 220, 220, 4...
2.508197
183
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-03-28 08:09 from __future__ import unicode_literals from django.db import migrations, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 24, 13, 17, 319, 1584, 12, 3070, 12, 2078, 8487, 25, 2931, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 1...
2.719298
57
""" Group - SwimTime - Swim your way to success """ import ads1x15 import network import time import math import machine from umqtt.simple import MQTTClient import micropython from micropython import const from machine import Pin """ Define constant values """ run = False lapnr = 3 #default lap number temp = 0.0 wifi_ssid = "Alfabeta" wifi_pswd = "12345678" server = "io.adafruit.com" user = "kk2314" passwd = "674d8794c84d49008c5e0092dc6be24b" mqtt_temp = "kk2314/feeds/temp" mqtt_time = "kk2314/feeds/time" mqtt_rawdata = "kk2314/feeds/rawdata" mqtt_control = "kk2314/feeds/control" mqtt_stat = "kk2314/feeds/stat" mqtt_debug = "kk2314/feeds/debug" mqtt_tempalert = "kk2314/feeds/tempalert" """ Define pins for LED and buzzer """ red = Pin(0, Pin.OUT) blue = Pin(2, Pin.OUT) p12 = machine.Pin(12) buzz = machine.PWM(p12) #function to blink LED #setting up I2C for range finder/ set up ADC i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4), freq=100000) adc = ads1x15.ADS1115(i2c) adc.gain = 1 #ADS1015_REG_CONFIG_PGA_4_096V #setting up I2C for temp sens i2c_temp = machine.I2C(scl=machine.Pin(14), sda=machine.Pin(13), freq=100000) #Received messages from subscriptions will be delivered to this callback """ Connect to the wifi """ sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.scan() sta_if.connect(wifi_ssid, wifi_pswd) print('Connecting to Wi-Fi') #while connecting blink LED and wait while not sta_if.isconnected(): blink_LED(red) pass print('Wifi connected') #Turn red LED on (active-low) red.off() # Turn off ESP8266's AP ap_if = network.WLAN(network.AP_IF) ap_if.active(False) #Converts the data received from ultrasonic sensor into meters #Send a read request and read information of temp sensor as well as convert temp into degree celcius #sets up the buzzer to run a countdown composed of 3 short beeps and a long one #converts secs into min and seconds #main() function which executes sensing and mqtt push if __name__ == "__main__": main(server)
[ 37811, 628, 198, 13247, 532, 198, 198, 10462, 320, 7575, 532, 35953, 534, 835, 284, 1943, 198, 198, 37811, 198, 198, 11748, 9011, 16, 87, 1314, 198, 11748, 3127, 198, 11748, 640, 198, 11748, 10688, 198, 11748, 4572, 198, 6738, 23781, ...
2.52451
816
''' The MIT License (MIT) Copyright (c) 2016 WavyCloud 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. ''' def abort_document_version_upload(DocumentId=None, VersionId=None): """ Aborts the upload of the specified document version that was previously initiated by InitiateDocumentVersionUpload . The client should make this call only when it no longer intends or fails to upload the document version. See also: AWS API Documentation :example: response = client.abort_document_version_upload( DocumentId='string', VersionId='string' ) :type DocumentId: string :param DocumentId: [REQUIRED] The ID of the document. :type VersionId: string :param VersionId: [REQUIRED] The ID of the version. """ pass def activate_user(UserId=None): """ Activates the specified user. Only active users can access Amazon WorkDocs. See also: AWS API Documentation :example: response = client.activate_user( UserId='string' ) :type UserId: string :param UserId: [REQUIRED] The ID of the user. :rtype: dict :return: { 'User': { 'Id': 'string', 'Username': 'string', 'EmailAddress': 'string', 'GivenName': 'string', 'Surname': 'string', 'OrganizationId': 'string', 'RootFolderId': 'string', 'RecycleBinFolderId': 'string', 'Status': 'ACTIVE'|'INACTIVE'|'PENDING', 'Type': 'USER'|'ADMIN', 'CreatedTimestamp': datetime(2015, 1, 1), 'ModifiedTimestamp': datetime(2015, 1, 1), 'TimeZoneId': 'string', 'Locale': 'en'|'fr'|'ko'|'de'|'es'|'ja'|'ru'|'zh_CN'|'zh_TW'|'pt_BR'|'default', 'Storage': { 'StorageUtilizedInBytes': 123, 'StorageRule': { 'StorageAllocatedInBytes': 123, 'StorageType': 'UNLIMITED'|'QUOTA' } } } } """ pass def add_resource_permissions(ResourceId=None, Principals=None): """ Creates a set of permissions for the specified folder or document. The resource permissions are overwritten if the principals already have different permissions. See also: AWS API Documentation :example: response = client.add_resource_permissions( ResourceId='string', Principals=[ { 'Id': 'string', 'Type': 'USER'|'GROUP'|'INVITE'|'ANONYMOUS'|'ORGANIZATION', 'Role': 'VIEWER'|'CONTRIBUTOR'|'OWNER'|'COOWNER' }, ] ) :type ResourceId: string :param ResourceId: [REQUIRED] The ID of the resource. :type Principals: list :param Principals: [REQUIRED] The users, groups, or organization being granted permission. (dict) --Describes the recipient type and ID, if available. Id (string) -- [REQUIRED]The ID of the recipient. Type (string) -- [REQUIRED]The type of the recipient. Role (string) -- [REQUIRED]The role of the recipient. :rtype: dict :return: { 'ShareResults': [ { 'PrincipalId': 'string', 'Role': 'VIEWER'|'CONTRIBUTOR'|'OWNER'|'COOWNER', 'Status': 'SUCCESS'|'FAILURE', 'ShareId': 'string', 'StatusMessage': 'string' }, ] } """ pass def can_paginate(operation_name=None): """ Check if an operation can be paginated. :type operation_name: string :param operation_name: The operation name. This is the same name as the method name on the client. For example, if the method name is create_foo, and you'd normally invoke the operation as client.create_foo(**kwargs), if the create_foo operation can be paginated, you can use the call client.get_paginator('create_foo'). """ pass def create_folder(Name=None, ParentFolderId=None): """ Creates a folder with the specified name and parent folder. See also: AWS API Documentation :example: response = client.create_folder( Name='string', ParentFolderId='string' ) :type Name: string :param Name: The name of the new folder. :type ParentFolderId: string :param ParentFolderId: [REQUIRED] The ID of the parent folder. :rtype: dict :return: { 'Metadata': { 'Id': 'string', 'Name': 'string', 'CreatorId': 'string', 'ParentFolderId': 'string', 'CreatedTimestamp': datetime(2015, 1, 1), 'ModifiedTimestamp': datetime(2015, 1, 1), 'ResourceState': 'ACTIVE'|'RESTORING'|'RECYCLING'|'RECYCLED', 'Signature': 'string' } } """ pass def create_notification_subscription(OrganizationId=None, Endpoint=None, Protocol=None, SubscriptionType=None): """ Configure WorkDocs to use Amazon SNS notifications. The endpoint receives a confirmation message, and must confirm the subscription. For more information, see Confirm the Subscription in the Amazon Simple Notification Service Developer Guide . See also: AWS API Documentation :example: response = client.create_notification_subscription( OrganizationId='string', Endpoint='string', Protocol='HTTPS', SubscriptionType='ALL' ) :type OrganizationId: string :param OrganizationId: [REQUIRED] The ID of the organization. :type Endpoint: string :param Endpoint: [REQUIRED] The endpoint to receive the notifications. If the protocol is HTTPS, the endpoint is a URL that begins with 'https://'. :type Protocol: string :param Protocol: [REQUIRED] The protocol to use. The supported value is https, which delivers JSON-encoded messasges using HTTPS POST. :type SubscriptionType: string :param SubscriptionType: [REQUIRED] The notification type. :rtype: dict :return: { 'Subscription': { 'SubscriptionId': 'string', 'EndPoint': 'string', 'Protocol': 'HTTPS' } } """ pass def create_user(OrganizationId=None, Username=None, GivenName=None, Surname=None, Password=None, TimeZoneId=None, StorageRule=None): """ Creates a user in a Simple AD or Microsoft AD directory. The status of a newly created user is "ACTIVE". New users can access Amazon WorkDocs. See also: AWS API Documentation :example: response = client.create_user( OrganizationId='string', Username='string', GivenName='string', Surname='string', Password='string', TimeZoneId='string', StorageRule={ 'StorageAllocatedInBytes': 123, 'StorageType': 'UNLIMITED'|'QUOTA' } ) :type OrganizationId: string :param OrganizationId: The ID of the organization. :type Username: string :param Username: [REQUIRED] The login name of the user. :type GivenName: string :param GivenName: [REQUIRED] The given name of the user. :type Surname: string :param Surname: [REQUIRED] The surname of the user. :type Password: string :param Password: [REQUIRED] The password of the user. :type TimeZoneId: string :param TimeZoneId: The time zone ID of the user. :type StorageRule: dict :param StorageRule: The amount of storage for the user. StorageAllocatedInBytes (integer) --The amount of storage allocated, in bytes. StorageType (string) --The type of storage. :rtype: dict :return: { 'User': { 'Id': 'string', 'Username': 'string', 'EmailAddress': 'string', 'GivenName': 'string', 'Surname': 'string', 'OrganizationId': 'string', 'RootFolderId': 'string', 'RecycleBinFolderId': 'string', 'Status': 'ACTIVE'|'INACTIVE'|'PENDING', 'Type': 'USER'|'ADMIN', 'CreatedTimestamp': datetime(2015, 1, 1), 'ModifiedTimestamp': datetime(2015, 1, 1), 'TimeZoneId': 'string', 'Locale': 'en'|'fr'|'ko'|'de'|'es'|'ja'|'ru'|'zh_CN'|'zh_TW'|'pt_BR'|'default', 'Storage': { 'StorageUtilizedInBytes': 123, 'StorageRule': { 'StorageAllocatedInBytes': 123, 'StorageType': 'UNLIMITED'|'QUOTA' } } } } """ pass def deactivate_user(UserId=None): """ Deactivates the specified user, which revokes the user's access to Amazon WorkDocs. See also: AWS API Documentation :example: response = client.deactivate_user( UserId='string' ) :type UserId: string :param UserId: [REQUIRED] The ID of the user. """ pass def delete_document(DocumentId=None): """ Permanently deletes the specified document and its associated metadata. See also: AWS API Documentation :example: response = client.delete_document( DocumentId='string' ) :type DocumentId: string :param DocumentId: [REQUIRED] The ID of the document. """ pass def delete_folder(FolderId=None): """ Permanently deletes the specified folder and its contents. See also: AWS API Documentation :example: response = client.delete_folder( FolderId='string' ) :type FolderId: string :param FolderId: [REQUIRED] The ID of the folder. """ pass def delete_folder_contents(FolderId=None): """ Deletes the contents of the specified folder. See also: AWS API Documentation :example: response = client.delete_folder_contents( FolderId='string' ) :type FolderId: string :param FolderId: [REQUIRED] The ID of the folder. """ pass def delete_notification_subscription(SubscriptionId=None, OrganizationId=None): """ Deletes the specified subscription from the specified organization. See also: AWS API Documentation :example: response = client.delete_notification_subscription( SubscriptionId='string', OrganizationId='string' ) :type SubscriptionId: string :param SubscriptionId: [REQUIRED] The ID of the subscription. :type OrganizationId: string :param OrganizationId: [REQUIRED] The ID of the organization. """ pass def delete_user(UserId=None): """ Deletes the specified user from a Simple AD or Microsoft AD directory. See also: AWS API Documentation :example: response = client.delete_user( UserId='string' ) :type UserId: string :param UserId: [REQUIRED] The ID of the user. """ pass def describe_document_versions(DocumentId=None, Marker=None, Limit=None, Include=None, Fields=None): """ Retrieves the document versions for the specified document. By default, only active versions are returned. See also: AWS API Documentation :example: response = client.describe_document_versions( DocumentId='string', Marker='string', Limit=123, Include='string', Fields='string' ) :type DocumentId: string :param DocumentId: [REQUIRED] The ID of the document. :type Marker: string :param Marker: The marker for the next set of results. (You received this marker from a previous call.) :type Limit: integer :param Limit: The maximum number of versions to return with this call. :type Include: string :param Include: A comma-separated list of values. Specify 'INITIALIZED' to include incomplete versions. :type Fields: string :param Fields: Specify 'SOURCE' to include initialized versions and a URL for the source document. :rtype: dict :return: { 'DocumentVersions': [ { 'Id': 'string', 'Name': 'string', 'ContentType': 'string', 'Size': 123, 'Signature': 'string', 'Status': 'INITIALIZED'|'ACTIVE', 'CreatedTimestamp': datetime(2015, 1, 1), 'ModifiedTimestamp': datetime(2015, 1, 1), 'ContentCreatedTimestamp': datetime(2015, 1, 1), 'ContentModifiedTimestamp': datetime(2015, 1, 1), 'CreatorId': 'string', 'Thumbnail': { 'string': 'string' }, 'Source': { 'string': 'string' } }, ], 'Marker': 'string' } :returns: (string) -- (string) -- """ pass def describe_folder_contents(FolderId=None, Sort=None, Order=None, Limit=None, Marker=None, Type=None, Include=None): """ Describes the contents of the specified folder, including its documents and sub-folders. By default, Amazon WorkDocs returns the first 100 active document and folder metadata items. If there are more results, the response includes a marker that you can use to request the next set of results. You can also request initialized documents. See also: AWS API Documentation :example: response = client.describe_folder_contents( FolderId='string', Sort='DATE'|'NAME', Order='ASCENDING'|'DESCENDING', Limit=123, Marker='string', Type='ALL'|'DOCUMENT'|'FOLDER', Include='string' ) :type FolderId: string :param FolderId: [REQUIRED] The ID of the folder. :type Sort: string :param Sort: The sorting criteria. :type Order: string :param Order: The order for the contents of the folder. :type Limit: integer :param Limit: The maximum number of items to return with this call. :type Marker: string :param Marker: The marker for the next set of results. (You received this marker from a previous call.) :type Type: string :param Type: The type of items. :type Include: string :param Include: The contents to include. Specify 'INITIALIZED' to include initialized documents. :rtype: dict :return: { 'Folders': [ { 'Id': 'string', 'Name': 'string', 'CreatorId': 'string', 'ParentFolderId': 'string', 'CreatedTimestamp': datetime(2015, 1, 1), 'ModifiedTimestamp': datetime(2015, 1, 1), 'ResourceState': 'ACTIVE'|'RESTORING'|'RECYCLING'|'RECYCLED', 'Signature': 'string' }, ], 'Documents': [ { 'Id': 'string', 'CreatorId': 'string', 'ParentFolderId': 'string', 'CreatedTimestamp': datetime(2015, 1, 1), 'ModifiedTimestamp': datetime(2015, 1, 1), 'LatestVersionMetadata': { 'Id': 'string', 'Name': 'string', 'ContentType': 'string', 'Size': 123, 'Signature': 'string', 'Status': 'INITIALIZED'|'ACTIVE', 'CreatedTimestamp': datetime(2015, 1, 1), 'ModifiedTimestamp': datetime(2015, 1, 1), 'ContentCreatedTimestamp': datetime(2015, 1, 1), 'ContentModifiedTimestamp': datetime(2015, 1, 1), 'CreatorId': 'string', 'Thumbnail': { 'string': 'string' }, 'Source': { 'string': 'string' } }, 'ResourceState': 'ACTIVE'|'RESTORING'|'RECYCLING'|'RECYCLED' }, ], 'Marker': 'string' } :returns: (string) -- (string) -- """ pass def describe_notification_subscriptions(OrganizationId=None, Marker=None, Limit=None): """ Lists the specified notification subscriptions. See also: AWS API Documentation :example: response = client.describe_notification_subscriptions( OrganizationId='string', Marker='string', Limit=123 ) :type OrganizationId: string :param OrganizationId: [REQUIRED] The ID of the organization. :type Marker: string :param Marker: The marker for the next set of results. (You received this marker from a previous call.) :type Limit: integer :param Limit: The maximum number of items to return with this call. :rtype: dict :return: { 'Subscriptions': [ { 'SubscriptionId': 'string', 'EndPoint': 'string', 'Protocol': 'HTTPS' }, ], 'Marker': 'string' } """ pass def describe_resource_permissions(ResourceId=None, Limit=None, Marker=None): """ Describes the permissions of a specified resource. See also: AWS API Documentation :example: response = client.describe_resource_permissions( ResourceId='string', Limit=123, Marker='string' ) :type ResourceId: string :param ResourceId: [REQUIRED] The ID of the resource. :type Limit: integer :param Limit: The maximum number of items to return with this call. :type Marker: string :param Marker: The marker for the next set of results. (You received this marker from a previous call) :rtype: dict :return: { 'Principals': [ { 'Id': 'string', 'Type': 'USER'|'GROUP'|'INVITE'|'ANONYMOUS'|'ORGANIZATION', 'Roles': [ { 'Role': 'VIEWER'|'CONTRIBUTOR'|'OWNER'|'COOWNER', 'Type': 'DIRECT'|'INHERITED' }, ] }, ], 'Marker': 'string' } """ pass def describe_users(OrganizationId=None, UserIds=None, Query=None, Include=None, Order=None, Sort=None, Marker=None, Limit=None, Fields=None): """ Describes the specified users. You can describe all users or filter the results (for example, by status or organization). By default, Amazon WorkDocs returns the first 24 active or pending users. If there are more results, the response includes a marker that you can use to request the next set of results. See also: AWS API Documentation :example: response = client.describe_users( OrganizationId='string', UserIds='string', Query='string', Include='ALL'|'ACTIVE_PENDING', Order='ASCENDING'|'DESCENDING', Sort='USER_NAME'|'FULL_NAME'|'STORAGE_LIMIT'|'USER_STATUS'|'STORAGE_USED', Marker='string', Limit=123, Fields='string' ) :type OrganizationId: string :param OrganizationId: The ID of the organization. :type UserIds: string :param UserIds: The IDs of the users. :type Query: string :param Query: A query to filter users by user name. :type Include: string :param Include: The state of the users. Specify 'ALL' to include inactive users. :type Order: string :param Order: The order for the results. :type Sort: string :param Sort: The sorting criteria. :type Marker: string :param Marker: The marker for the next set of results. (You received this marker from a previous call.) :type Limit: integer :param Limit: The maximum number of items to return. :type Fields: string :param Fields: A comma-separated list of values. Specify 'STORAGE_METADATA' to include the user storage quota and utilization information. :rtype: dict :return: { 'Users': [ { 'Id': 'string', 'Username': 'string', 'EmailAddress': 'string', 'GivenName': 'string', 'Surname': 'string', 'OrganizationId': 'string', 'RootFolderId': 'string', 'RecycleBinFolderId': 'string', 'Status': 'ACTIVE'|'INACTIVE'|'PENDING', 'Type': 'USER'|'ADMIN', 'CreatedTimestamp': datetime(2015, 1, 1), 'ModifiedTimestamp': datetime(2015, 1, 1), 'TimeZoneId': 'string', 'Locale': 'en'|'fr'|'ko'|'de'|'es'|'ja'|'ru'|'zh_CN'|'zh_TW'|'pt_BR'|'default', 'Storage': { 'StorageUtilizedInBytes': 123, 'StorageRule': { 'StorageAllocatedInBytes': 123, 'StorageType': 'UNLIMITED'|'QUOTA' } } }, ], 'TotalNumberOfUsers': 123, 'Marker': 'string' } """ pass def generate_presigned_url(ClientMethod=None, Params=None, ExpiresIn=None, HttpMethod=None): """ Generate a presigned url given a client, its method, and arguments :type ClientMethod: string :param ClientMethod: The client method to presign for :type Params: dict :param Params: The parameters normally passed to ClientMethod. :type ExpiresIn: int :param ExpiresIn: The number of seconds the presigned url is valid for. By default it expires in an hour (3600 seconds) :type HttpMethod: string :param HttpMethod: The http method to use on the generated url. By default, the http method is whatever is used in the method's model. """ pass def get_document(DocumentId=None): """ Retrieves the specified document object. See also: AWS API Documentation :example: response = client.get_document( DocumentId='string' ) :type DocumentId: string :param DocumentId: [REQUIRED] The ID of the document object. :rtype: dict :return: { 'Metadata': { 'Id': 'string', 'CreatorId': 'string', 'ParentFolderId': 'string', 'CreatedTimestamp': datetime(2015, 1, 1), 'ModifiedTimestamp': datetime(2015, 1, 1), 'LatestVersionMetadata': { 'Id': 'string', 'Name': 'string', 'ContentType': 'string', 'Size': 123, 'Signature': 'string', 'Status': 'INITIALIZED'|'ACTIVE', 'CreatedTimestamp': datetime(2015, 1, 1), 'ModifiedTimestamp': datetime(2015, 1, 1), 'ContentCreatedTimestamp': datetime(2015, 1, 1), 'ContentModifiedTimestamp': datetime(2015, 1, 1), 'CreatorId': 'string', 'Thumbnail': { 'string': 'string' }, 'Source': { 'string': 'string' } }, 'ResourceState': 'ACTIVE'|'RESTORING'|'RECYCLING'|'RECYCLED' } } :returns: (string) -- (string) -- """ pass def get_document_path(DocumentId=None, Limit=None, Fields=None, Marker=None): """ Retrieves the path information (the hierarchy from the root folder) for the requested document. By default, Amazon WorkDocs returns a maximum of 100 levels upwards from the requested document and only includes the IDs of the parent folders in the path. You can limit the maximum number of levels. You can also request the names of the parent folders. See also: AWS API Documentation :example: response = client.get_document_path( DocumentId='string', Limit=123, Fields='string', Marker='string' ) :type DocumentId: string :param DocumentId: [REQUIRED] The ID of the document. :type Limit: integer :param Limit: The maximum number of levels in the hierarchy to return. :type Fields: string :param Fields: A comma-separated list of values. Specify 'NAME' to include the names of the parent folders. :type Marker: string :param Marker: This value is not supported. :rtype: dict :return: { 'Path': { 'Components': [ { 'Id': 'string', 'Name': 'string' }, ] } } """ pass def get_document_version(DocumentId=None, VersionId=None, Fields=None): """ Retrieves version metadata for the specified document. See also: AWS API Documentation :example: response = client.get_document_version( DocumentId='string', VersionId='string', Fields='string' ) :type DocumentId: string :param DocumentId: [REQUIRED] The ID of the document. :type VersionId: string :param VersionId: [REQUIRED] The version ID of the document. :type Fields: string :param Fields: A comma-separated list of values. Specify 'SOURCE' to include a URL for the source document. :rtype: dict :return: { 'Metadata': { 'Id': 'string', 'Name': 'string', 'ContentType': 'string', 'Size': 123, 'Signature': 'string', 'Status': 'INITIALIZED'|'ACTIVE', 'CreatedTimestamp': datetime(2015, 1, 1), 'ModifiedTimestamp': datetime(2015, 1, 1), 'ContentCreatedTimestamp': datetime(2015, 1, 1), 'ContentModifiedTimestamp': datetime(2015, 1, 1), 'CreatorId': 'string', 'Thumbnail': { 'string': 'string' }, 'Source': { 'string': 'string' } } } :returns: (string) -- (string) -- """ pass def get_folder(FolderId=None): """ Retrieves the metadata of the specified folder. See also: AWS API Documentation :example: response = client.get_folder( FolderId='string' ) :type FolderId: string :param FolderId: [REQUIRED] The ID of the folder. :rtype: dict :return: { 'Metadata': { 'Id': 'string', 'Name': 'string', 'CreatorId': 'string', 'ParentFolderId': 'string', 'CreatedTimestamp': datetime(2015, 1, 1), 'ModifiedTimestamp': datetime(2015, 1, 1), 'ResourceState': 'ACTIVE'|'RESTORING'|'RECYCLING'|'RECYCLED', 'Signature': 'string' } } """ pass def get_folder_path(FolderId=None, Limit=None, Fields=None, Marker=None): """ Retrieves the path information (the hierarchy from the root folder) for the specified folder. By default, Amazon WorkDocs returns a maximum of 100 levels upwards from the requested folder and only includes the IDs of the parent folders in the path. You can limit the maximum number of levels. You can also request the parent folder names. See also: AWS API Documentation :example: response = client.get_folder_path( FolderId='string', Limit=123, Fields='string', Marker='string' ) :type FolderId: string :param FolderId: [REQUIRED] The ID of the folder. :type Limit: integer :param Limit: The maximum number of levels in the hierarchy to return. :type Fields: string :param Fields: A comma-separated list of values. Specify 'NAME' to include the names of the parent folders. :type Marker: string :param Marker: This value is not supported. :rtype: dict :return: { 'Path': { 'Components': [ { 'Id': 'string', 'Name': 'string' }, ] } } """ pass def get_paginator(operation_name=None): """ Create a paginator for an operation. :type operation_name: string :param operation_name: The operation name. This is the same name as the method name on the client. For example, if the method name is create_foo, and you'd normally invoke the operation as client.create_foo(**kwargs), if the create_foo operation can be paginated, you can use the call client.get_paginator('create_foo'). :rtype: L{botocore.paginate.Paginator} """ pass def get_waiter(): """ """ pass def initiate_document_version_upload(Id=None, Name=None, ContentCreatedTimestamp=None, ContentModifiedTimestamp=None, ContentType=None, DocumentSizeInBytes=None, ParentFolderId=None): """ Creates a new document object and version object. The client specifies the parent folder ID and name of the document to upload. The ID is optionally specified when creating a new version of an existing document. This is the first step to upload a document. Next, upload the document to the URL returned from the call, and then call UpdateDocumentVersion . To cancel the document upload, call AbortDocumentVersionUpload . See also: AWS API Documentation :example: response = client.initiate_document_version_upload( Id='string', Name='string', ContentCreatedTimestamp=datetime(2015, 1, 1), ContentModifiedTimestamp=datetime(2015, 1, 1), ContentType='string', DocumentSizeInBytes=123, ParentFolderId='string' ) :type Id: string :param Id: The ID of the document. :type Name: string :param Name: The name of the document. :type ContentCreatedTimestamp: datetime :param ContentCreatedTimestamp: The time stamp when the content of the document was originally created. :type ContentModifiedTimestamp: datetime :param ContentModifiedTimestamp: The time stamp when the content of the document was modified. :type ContentType: string :param ContentType: The content type of the document. :type DocumentSizeInBytes: integer :param DocumentSizeInBytes: The size of the document, in bytes. :type ParentFolderId: string :param ParentFolderId: [REQUIRED] The ID of the parent folder. :rtype: dict :return: { 'Metadata': { 'Id': 'string', 'CreatorId': 'string', 'ParentFolderId': 'string', 'CreatedTimestamp': datetime(2015, 1, 1), 'ModifiedTimestamp': datetime(2015, 1, 1), 'LatestVersionMetadata': { 'Id': 'string', 'Name': 'string', 'ContentType': 'string', 'Size': 123, 'Signature': 'string', 'Status': 'INITIALIZED'|'ACTIVE', 'CreatedTimestamp': datetime(2015, 1, 1), 'ModifiedTimestamp': datetime(2015, 1, 1), 'ContentCreatedTimestamp': datetime(2015, 1, 1), 'ContentModifiedTimestamp': datetime(2015, 1, 1), 'CreatorId': 'string', 'Thumbnail': { 'string': 'string' }, 'Source': { 'string': 'string' } }, 'ResourceState': 'ACTIVE'|'RESTORING'|'RECYCLING'|'RECYCLED' }, 'UploadMetadata': { 'UploadUrl': 'string', 'SignedHeaders': { 'string': 'string' } } } :returns: (string) -- (string) -- """ pass def remove_all_resource_permissions(ResourceId=None): """ Removes all the permissions from the specified resource. See also: AWS API Documentation :example: response = client.remove_all_resource_permissions( ResourceId='string' ) :type ResourceId: string :param ResourceId: [REQUIRED] The ID of the resource. """ pass def remove_resource_permission(ResourceId=None, PrincipalId=None, PrincipalType=None): """ Removes the permission for the specified principal from the specified resource. See also: AWS API Documentation :example: response = client.remove_resource_permission( ResourceId='string', PrincipalId='string', PrincipalType='USER'|'GROUP'|'INVITE'|'ANONYMOUS'|'ORGANIZATION' ) :type ResourceId: string :param ResourceId: [REQUIRED] The ID of the resource. :type PrincipalId: string :param PrincipalId: [REQUIRED] The principal ID of the resource. :type PrincipalType: string :param PrincipalType: The principal type of the resource. """ pass def update_document(DocumentId=None, Name=None, ParentFolderId=None, ResourceState=None): """ Updates the specified attributes of the specified document. The user must have access to both the document and its parent folder, if applicable. See also: AWS API Documentation :example: response = client.update_document( DocumentId='string', Name='string', ParentFolderId='string', ResourceState='ACTIVE'|'RESTORING'|'RECYCLING'|'RECYCLED' ) :type DocumentId: string :param DocumentId: [REQUIRED] The ID of the document. :type Name: string :param Name: The name of the document. :type ParentFolderId: string :param ParentFolderId: The ID of the parent folder. :type ResourceState: string :param ResourceState: The resource state of the document. Note that only ACTIVE and RECYCLED are supported. """ pass def update_document_version(DocumentId=None, VersionId=None, VersionStatus=None): """ Changes the status of the document version to ACTIVE. Amazon WorkDocs also sets its document container to ACTIVE. This is the last step in a document upload, after the client uploads the document to an S3-presigned URL returned by InitiateDocumentVersionUpload . See also: AWS API Documentation :example: response = client.update_document_version( DocumentId='string', VersionId='string', VersionStatus='ACTIVE' ) :type DocumentId: string :param DocumentId: [REQUIRED] The ID of the document. :type VersionId: string :param VersionId: [REQUIRED] The version ID of the document. :type VersionStatus: string :param VersionStatus: The status of the version. """ pass def update_folder(FolderId=None, Name=None, ParentFolderId=None, ResourceState=None): """ Updates the specified attributes of the specified folder. The user must have access to both the folder and its parent folder, if applicable. See also: AWS API Documentation :example: response = client.update_folder( FolderId='string', Name='string', ParentFolderId='string', ResourceState='ACTIVE'|'RESTORING'|'RECYCLING'|'RECYCLED' ) :type FolderId: string :param FolderId: [REQUIRED] The ID of the folder. :type Name: string :param Name: The name of the folder. :type ParentFolderId: string :param ParentFolderId: The ID of the parent folder. :type ResourceState: string :param ResourceState: The resource state of the folder. Note that only ACTIVE and RECYCLED are accepted values from the API. """ pass def update_user(UserId=None, GivenName=None, Surname=None, Type=None, StorageRule=None, TimeZoneId=None, Locale=None): """ Updates the specified attributes of the specified user, and grants or revokes administrative privileges to the Amazon WorkDocs site. See also: AWS API Documentation :example: response = client.update_user( UserId='string', GivenName='string', Surname='string', Type='USER'|'ADMIN', StorageRule={ 'StorageAllocatedInBytes': 123, 'StorageType': 'UNLIMITED'|'QUOTA' }, TimeZoneId='string', Locale='en'|'fr'|'ko'|'de'|'es'|'ja'|'ru'|'zh_CN'|'zh_TW'|'pt_BR'|'default' ) :type UserId: string :param UserId: [REQUIRED] The ID of the user. :type GivenName: string :param GivenName: The given name of the user. :type Surname: string :param Surname: The surname of the user. :type Type: string :param Type: The type of the user. :type StorageRule: dict :param StorageRule: The amount of storage for the user. StorageAllocatedInBytes (integer) --The amount of storage allocated, in bytes. StorageType (string) --The type of storage. :type TimeZoneId: string :param TimeZoneId: The time zone ID of the user. :type Locale: string :param Locale: The locale of the user. :rtype: dict :return: { 'User': { 'Id': 'string', 'Username': 'string', 'EmailAddress': 'string', 'GivenName': 'string', 'Surname': 'string', 'OrganizationId': 'string', 'RootFolderId': 'string', 'RecycleBinFolderId': 'string', 'Status': 'ACTIVE'|'INACTIVE'|'PENDING', 'Type': 'USER'|'ADMIN', 'CreatedTimestamp': datetime(2015, 1, 1), 'ModifiedTimestamp': datetime(2015, 1, 1), 'TimeZoneId': 'string', 'Locale': 'en'|'fr'|'ko'|'de'|'es'|'ja'|'ru'|'zh_CN'|'zh_TW'|'pt_BR'|'default', 'Storage': { 'StorageUtilizedInBytes': 123, 'StorageRule': { 'StorageAllocatedInBytes': 123, 'StorageType': 'UNLIMITED'|'QUOTA' } } } } """ pass
[ 7061, 6, 198, 198, 464, 17168, 13789, 357, 36393, 8, 198, 198, 15269, 357, 66, 8, 1584, 370, 2830, 18839, 198, 198, 5990, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 1659, 428, 3788, 290, ...
2.221717
18,050
""" Feeder for batch production""" from __future__ import absolute_import import ctypes from ddls.base import check_call, LIB, c_str, c_array from ddls.feeder.batch_iterator import BatchIterator
[ 37811, 18272, 263, 329, 15458, 3227, 37811, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 269, 19199, 198, 6738, 49427, 7278, 13, 8692, 1330, 2198, 62, 13345, 11, 45651, 11, 269, 62, 2536, 11, 269, 62, 18747, 1...
3.45614
57
import pytest from mvlearn.example.example import example_function def test_example_function(): """ Test that example function returns correct value. """ assert example_function() == "param" assert example_function("hello") == "hello"
[ 11748, 12972, 9288, 198, 198, 6738, 285, 85, 35720, 13, 20688, 13, 20688, 1330, 1672, 62, 8818, 628, 198, 4299, 1332, 62, 20688, 62, 8818, 33529, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 6208, 326, 1672, 2163, 5860, 3376, 1988, ...
3.350649
77
from flask_restful import Resource import requests from api.common.utils import file_response ENCODING = 'utf-8' SCHEMA_URL = 'http://127.0.0.1:8422' STORE_URL = 'http://127.0.0.1:8423'
[ 6738, 42903, 62, 2118, 913, 1330, 20857, 198, 11748, 7007, 198, 198, 6738, 40391, 13, 11321, 13, 26791, 1330, 2393, 62, 26209, 628, 198, 24181, 3727, 2751, 796, 705, 40477, 12, 23, 6, 198, 50, 3398, 27630, 62, 21886, 796, 705, 4023, ...
2.5
78
#!/bin/env python #coding: utf-8 import pymongo print [x for x in range(2)] con = pymongo.MongoClient("localhost", 27017) db = con.mars collection = db.users data = collection.find_one({"username":"hyr"}) print data data['age'] = 225 print collection.update({"_idd":data['_id']}, data) print collection.find_one({"username":"hyr"}) # for i in collection.find().sort('_id', pymongo.DESCENDING).limit(1): # print i
[ 2, 48443, 8800, 14, 24330, 21015, 198, 2, 66, 7656, 25, 3384, 69, 12, 23, 628, 198, 198, 11748, 279, 4948, 25162, 198, 4798, 685, 87, 329, 2124, 287, 2837, 7, 17, 15437, 198, 198, 1102, 796, 279, 4948, 25162, 13, 44, 25162, 11792,...
2.635802
162
import numpy as np
[ 11748, 299, 32152, 355, 45941 ]
3.6
5
""" Greedy Module Solution for Utils control """ # Libraries from typing import List from functools import reduce # Modules from src.utils.math import ( list_negative, invert_positions, evaluate_fo ) # Constants COMPARE_VALUE = 99999999 def worst_solution(distance_matrix: List[List[float]]) -> List[int]: """This generate the worst solution""" negative_matrix = list(map( list_negative, distance_matrix )) return neghbord_most_near(negative_matrix) def neghbord_most_near( distance_matrix: List[List[float]], start_city: int = 0 ) -> List[int]: """ get the city most near in distance """ neghbord_used = [start_city] def city_most_near(line: int) -> int: """ Get City most near """ compare_value = COMPARE_VALUE most_near = -1 for key, value in enumerate(distance_matrix[line]): if ( line != key and value < compare_value and key not in neghbord_used ): compare_value = value most_near = key neghbord_used.append(most_near) return most_near return list(map( lambda x: city_most_near(x) if x != start_city else start_city, range(len(distance_matrix)) )) def best_change_not_tabu( matrix_distance: List[List[float]], solution: List[int] ) -> (float, tuple): """ change the data for best change based into function objective matrix_distance: List[List[float]] -> Matrix of distances solution: List[int] -> all solutions return (float, (posx, posy)) -> the best solution into position """ # fun_before = evaluate_fo(matrix_distance, solution) best_fo = 1E+100 position = (-1, -1) tam = len(solution) for posx in range(tam-1): for posy in range(posx+1 if posx+1 != tam else tam, tam): funobj = evaluate_fo( matrix_distance, invert_positions(solution, posx, posy) ) if funobj < best_fo: best_fo = funobj position = (posx, posy) return (best_fo, position) def generate_local_search( matrix_distance: List[List[float]], solution: List[int] ) -> (int, List[int]): """ This generate a local search for the minize way based in fo matrix_distance: List[List[float]] """ counter = 0 manage = True best_change = best_change_not_tabu(matrix_distance, solution) prev_change = (1E+100,) while manage: if prev_change[0] < best_change[0]: manage = False else: prev_change = best_change best_change = best_change_not_tabu(matrix_distance, solution) solution = invert_positions( solution, origin=best_change[1][0], destiny=best_change[1][1] ) counter += 1 return ( counter, ( prev_change[0] if prev_change[0] < best_change[0] and prev_change[0] != 0 else best_change[0] ), solution )
[ 37811, 198, 43887, 4716, 19937, 28186, 329, 7273, 4487, 1630, 198, 37811, 198, 198, 2, 46267, 198, 6738, 19720, 1330, 7343, 198, 6738, 1257, 310, 10141, 1330, 4646, 198, 198, 2, 3401, 5028, 198, 6738, 12351, 13, 26791, 13, 11018, 1330, ...
2.131561
1,505
import math import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from models.modules.model.vgg16 import Vgg16 import os vgg = Vgg16() vgg.load_state_dict(torch.load(os.path.join(os.path.abspath('.'), 'models/modules/model/', 'vgg16.weight'))) params = list(vgg.named_parameters()) encoding1 = params[0][1].data encoding2 = params[2][1].data # class encoder(nn.Module): # def __init__(self, in_channels, out_channels, num_features): # super(encoder, self).__init__() # stride = 1 # padding = 1 # kernel_size = 3 # self.conv1 = nn.Conv2d(in_channels, 2*num_features, kernel_size, stride=stride, padding=padding) # self.conv2 = nn.Conv2d(2*num_features, num_features, kernel_size, stride=stride, padding=padding) # self.conv3 = nn.Conv2d(num_features, out_channels, kernel_size=1, stride=1) # self.prelu = nn.PReLU(num_parameters=1, init=0.2) # # def forward(self, x, rev=False): # x1 = self.prelu(self.conv1(x)) # x2 = self.prelu(self.conv2(x1)) # x3 = self.prelu(self.conv3(x2)) # return x3
[ 11748, 10688, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 4981, 13, 18170, 13, 19849, 13, 85, 1130, 1433, 1330, 569, ...
2.177264
519
import time import random import json import requests
[ 11748, 640, 198, 11748, 4738, 198, 11748, 33918, 198, 11748, 7007, 628, 198 ]
4.307692
13
""" Codemonk link: https://www.hackerearth.com/practice/algorithms/dynamic-programming/introduction-to-dynamic-programming-1/practice-problems/algorithm/equal-array-84cf6c5f/ You are given an array A of size N. Find the minimum non negative number X such that there exists an index j that when you can replace Aj by Aj+X, the sum of elements of the array from index 1 to j and j+1 to N become equal where 1 <= j <= N-1. Assume array to be 1-indexed. If there is no possible X print -1 in a separate line. Input - Output: The first line contains the number of test cases. The first line of each test case contains an integer N,which denotes the size of the array. The second line contains N space-separated integers where the ith integer denotes Ai. Sample input: 1 5 1 2 3 2 1 Sample Output: 3 """ """ We can simply find the partial sums array, iterate throught the array end at each step check for the minimum X number that is required. Final complexity: O(N) """ t = int(input()) for _ in range(t): n = int(input()) array = list(map(int, input().split())) partial_sums = [array[0]] for i in range(1, n): partial_sums.append(array[i]+partial_sums[i-1]) ans = float("inf") stop = False for i in range(n): if partial_sums[i] < partial_sums[-1] - partial_sums[i]: val = partial_sums[-1] - 2*partial_sums[i] ans = min(ans, val) if partial_sums[i] == partial_sums[-1] - partial_sums[i]: print(0) stop = True break if not stop: if ans != float("inf"): print(ans) else: print(-1)
[ 37811, 198, 43806, 7966, 74, 2792, 25, 3740, 1378, 2503, 13, 71, 330, 365, 260, 11999, 13, 785, 14, 39541, 14, 282, 7727, 907, 14, 67, 28995, 12, 23065, 2229, 14, 27427, 596, 12, 1462, 12, 67, 28995, 12, 23065, 2229, 12, 16, 14, ...
2.573668
638
from itertools import chain phi = 1.61803398875
[ 6738, 340, 861, 10141, 1330, 6333, 198, 198, 34846, 796, 352, 13, 21, 15259, 29626, 3459, 2425, 198 ]
2.722222
18
import unittest from unittest.mock import call, patch, Mock, MagicMock from qilib.configuration_helper import InstrumentAdapterFactory
[ 11748, 555, 715, 395, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 869, 11, 8529, 11, 44123, 11, 6139, 44, 735, 198, 198, 6738, 10662, 22282, 13, 11250, 3924, 62, 2978, 525, 1330, 42410, 47307, 22810, 628, 198 ]
3.538462
39
import json import pprint import random from terra_sdk.core import AccAddress, Coins from terra_sdk.core.auth import StdFee from terra_sdk.core.broadcast import BlockTxBroadcastResult from scripts.deploy import owner, lt from terra_sdk.core.wasm import MsgExecuteContract if __name__ == '__main__': main()
[ 11748, 33918, 198, 11748, 279, 4798, 198, 11748, 4738, 198, 198, 6738, 1059, 430, 62, 21282, 74, 13, 7295, 1330, 6366, 20231, 11, 30108, 198, 6738, 1059, 430, 62, 21282, 74, 13, 7295, 13, 18439, 1330, 520, 67, 37, 1453, 198, 6738, 1...
2.908257
109
from core.exceptions import BaseProjectException
[ 6738, 4755, 13, 1069, 11755, 1330, 7308, 16775, 16922, 628, 198 ]
4.636364
11
import math from nexinfosys.model_services import State materials = { "Aluminium", "Antimony", "Arsenic", "Baryte", "Beryllium", "Borates", "Cadmium", "Cerium", "Chromium", "Cobalt", "Copper", "Diatomite", "Dysprosium", "Europium", "Fluorspar", "Gadolinium", "Gallium", "Gold", "Gypsum", "IronOre", "KaolinClay", "Lanthanum", "Lead", "Lithium", "Magnesite", "Magnesium", "Manganese", "Molybdenum", "NaturalGraphite", "Neodymium", "Nickel", "Palladium", "Perlite", "Phosphorus", "Platinum", "Praseodymium", "Rhenium", "Rhodium", "Samarium", "Selenium", "SiliconMetal", "Silver", "Strontium", "Sulphur", "Talc", "Tantalum", "Tellurium", "Terbium", "Tin", "Titanium", "Tungsten", "Vanadium", "Yttrium", "Zinc", "Zirconium" }
[ 11748, 10688, 198, 198, 6738, 497, 87, 10745, 418, 893, 13, 19849, 62, 30416, 1330, 1812, 198, 198, 33665, 82, 796, 1391, 198, 220, 220, 220, 366, 2348, 35241, 1600, 198, 220, 220, 220, 366, 13217, 33969, 1600, 198, 220, 220, 220, 3...
1.829787
517
# defining a decorator # defining a function, to be called inside wrapper # passing 'function_to_be_used' inside the decorator to control its behaviour function_to_be_used = hello_decorator(function_to_be_used) # calling the function function_to_be_used() # find out the execution time of a function using a decorator # importing libraries import time import math # decorator to calculate duration # taken by any function. # this can be added to any function present, in this case to calculate a factorial # calling the function. factorial(10) # Chaining Decorators # code for testing decorator chaining print(num()) # Decorators with parameters in Python # Generator Function # A generator function that yields 1 for first time, 2 second time and 3 third time def simpleGeneratorFun(): yield 1 yield 2 yield 3 # Driver code to check above generator function for value in simpleGeneratorFun(): print(value) # A Python program to demonstrate use of generator object with next() # A generator function # x is a generator object x = simpleGeneratorFun() # Iterating over the generator object using next print(x.next()) # In Python 3, __next__() print(x.next()) print(x.next())
[ 2, 16215, 257, 11705, 1352, 201, 198, 2, 16215, 257, 2163, 11, 284, 307, 1444, 2641, 29908, 201, 198, 2, 6427, 705, 8818, 62, 1462, 62, 1350, 62, 1484, 6, 2641, 262, 11705, 1352, 284, 1630, 663, 9172, 201, 198, 8818, 62, 1462, 62,...
3.383978
362
#!/usr/bin/env python """ Info: This script performs topic modeling on the clean tweets by Donald Trump. The number of topics is estimated by computing coherence values for different number of topics, and an LDA model is constructed with the number of topics with the highest coherence value. Visualizations of the topics are created relying on pyLDAvis and wordcloud and these visualizations are saved in the output directory. Parameters: (optional) input_file: str <name-of-input-file>, default = clean_trump_tweets.csv (optional) chunk_size: int <size-of-chunks>, default = 10 (optional) passes: int <number-of-passes>, default = 10 (optional) min_count: int <minimum-count-bigrams>, default = 2 (optional) threshold: int <threshold-for-keeping-phrases>, default = 100 (optional) iterations: int <number-of-iterations>, default = 100 (optional) rolling_mean: int <rolling-mean>, default = 50 (optional) step_size: int <size-of-steps>, default = 5 Usage: $ python 1-topicmodeling.py Output: - topics.txt: overview of topics generated by the LDA model - dominant_topic.csv: table showing the most dominant topics and their associated keywords as well as how much each topic contributes. - topic_contributions.csv: a dataframe showing the most contributing keywords for each topic. - topics_over_time.jpg: visualization of the topic contributions over time. - topic_wordclouds.png: the topics visualized as word clouds. """ ### DEPENDENCIES ### # core libraries import sys import os sys.path.append(os.path.join("..")) # numpy, pandas, pyplot import numpy as np import pandas as pd from matplotlib import pyplot as plt # spaCy import spacy nlp = spacy.load("en_core_web_sm", disable=["ner"]) nlp.max_length = 68000000 # increasing maximum length # pyLDAvis and seaborn for vizualisations import pyLDAvis.gensim import seaborn as sns # matplotlib colors import matplotlib.colors as mcolors # wordcloud tools from wordcloud import WordCloud # LDA tools import gensim import gensim.corpora as corpora from gensim.models import CoherenceModel from utils import lda_utils # Ignore warnings import logging, warnings warnings.filterwarnings('ignore') logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.ERROR) # argparse import argparse ### MAIN FUNCTION ### ### TOPIC MODELING ### # Creating Topic modeling class # Define behaviour when called from command line if __name__=="__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 12360, 25, 770, 4226, 17706, 7243, 21128, 319, 262, 3424, 12665, 416, 3759, 1301, 13, 383, 1271, 286, 10233, 318, 6108, 416, 14492, 763, 23545, 3815, 329, 1180, 1271, 286, ...
3.209657
787
""" William DUong """ import os.path as osp import os import errno from .build import DATASET_REGISTRY from .base_dataset import Datum, DatasetBase,EEGDatum from scipy.io import loadmat import numpy as np from collections import defaultdict
[ 37811, 198, 17121, 35480, 506, 198, 37811, 198, 198, 11748, 28686, 13, 6978, 355, 267, 2777, 198, 11748, 28686, 198, 11748, 11454, 3919, 198, 6738, 764, 11249, 1330, 360, 1404, 1921, 2767, 62, 31553, 1797, 40405, 198, 6738, 764, 8692, 6...
3.037037
81
import argparse import json from ursina import load_texture, Ursina, Entity, color, camera, Quad, mouse, time, window, invoke, WindowPanel, \ Text, InputField, Space, scene, Button, Draggable, Tooltip, Scrollable from pywolf3d.games.wolf3d import WALL_DEFS, WallDef, OBJECT_DEFS Z_GRID = 0 Z_OBJECT = 2 Z_WALL = 3 def start_editor(fname, path_to_game): app = Ursina() editor = LevelEditor(fname, path_to_game) app.run() def run(): parser = argparse.ArgumentParser(description='Mapmaker for pywolf3d') parser.add_argument('level', help='path to level to load') parser.add_argument('--path', help='path to wolf3d datafiles (default ./wolfdata)', default="./wolfdata/") args = parser.parse_args() start_editor(args.level, args.path) if __name__ == '__main__': run()
[ 11748, 1822, 29572, 198, 11748, 33918, 198, 198, 6738, 220, 1834, 1437, 1330, 3440, 62, 41293, 11, 37935, 1437, 11, 20885, 11, 3124, 11, 4676, 11, 20648, 11, 10211, 11, 640, 11, 4324, 11, 26342, 11, 26580, 26639, 11, 3467, 198, 220, ...
2.592593
324
"""Functions for loading and data management for EEG-FOOOF.""" from os.path import join as pjoin import numpy as np from fooof import FOOOFGroup from fooof.analysis import get_band_peak_fg from settings import BANDS, YNG_INDS, OLD_INDS, N_LOADS, N_SUBJS, N_TIMES ################################################################################################### ################################################################################################### def reshape_data(data): """Reshape loaded data objects into subsets for YNG and OLD groups.""" yng_data = np.vstack([data[0, YNG_INDS, :], data[1, YNG_INDS, :], data[2, YNG_INDS, :]]) old_data = np.vstack([data[0, OLD_INDS, :], data[1, OLD_INDS, :], data[2, OLD_INDS, :]]) return yng_data, old_data def load_fooof_task_md(data_path, side='Contra', folder='FOOOF'): """Load task data in for all subjects, selects & return metadata.""" # Collect measures together from FOOOF results into matrices all_r2s = np.zeros(shape=[N_LOADS, N_SUBJS, N_TIMES]) all_errs = np.zeros(shape=[N_LOADS, N_SUBJS, N_TIMES]) for li, load in enumerate(['Load1', 'Load2', 'Load3']): pre, early, late = _load_fgs(data_path, folder, side, load) for ind, fg in enumerate([pre, early, late]): all_r2s[li, :, ind] = fg.get_params('r_squared') all_errs[li, :, ind] = fg.get_params('error') return all_r2s, all_errs def load_fooof_task_ap(data_path, side='Contra', folder='FOOOF'): """Loads task data in for all subjects, selects and return aperiodic FOOOF outputs. data_path : path to where data side: 'Ipsi' or 'Contra' """ # Collect measures together from FOOOF results into matrices all_exps = np.zeros(shape=[N_LOADS, N_SUBJS, N_TIMES]) all_offsets = np.zeros(shape=[N_LOADS, N_SUBJS, N_TIMES]) for li, load in enumerate(['Load1', 'Load2', 'Load3']): pre, early, late = _load_fgs(data_path, folder, side, load) for ind, fg in enumerate([pre, early, late]): all_exps[li, :, ind] = fg.get_params('aperiodic_params', 'exponent') all_offsets[li, :, ind] = fg.get_params('aperiodic_params', 'offset') return all_offsets, all_exps def load_fooof_task_pe(data_path, side='Contra', param_ind=1, folder='FOOOF'): """Loads task data for all subjects, selects and return periodic FOOOF outputs. data_path : path to where data side: 'Ipsi' or 'Contra' """ # Collect measures together from FOOOF results into matrices all_alphas = np.zeros(shape=[N_LOADS, N_SUBJS, N_TIMES]) for li, load in enumerate(['Load1', 'Load2', 'Load3']): pre, early, late = _load_fgs(data_path, folder, side, load) for ind, fg in enumerate([pre, early, late]): temp_alphas = get_band_peak_fg(fg, BANDS.alpha) all_alphas[li, :, ind] = temp_alphas[:, param_ind] return all_alphas def _load_fgs(data_path, folder, side, load): """Helper to load FOOOFGroups.""" # Load the FOOOF analyses of the average pre, early, late = FOOOFGroup(), FOOOFGroup(), FOOOFGroup() pre.load('Group_' + load + '_' + side + '_Pre', pjoin(data_path, folder)) early.load('Group_' + load + '_' + side + '_Early', pjoin(data_path, folder)) late.load('Group_' + load + '_' + side + '_Late', pjoin(data_path, folder)) return pre, early, late
[ 37811, 24629, 2733, 329, 11046, 290, 1366, 4542, 329, 48749, 12, 6080, 6684, 37, 526, 15931, 198, 198, 6738, 28686, 13, 6978, 1330, 4654, 355, 279, 22179, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 22944, 1659, 1330, 376, ...
2.491947
1,366
import sys import cv2 import numpy as np img1 = cv2.imread('source1.jpg',0) img2 = cv2.imread('source2.jpg',0) ret, thresh = cv2.threshold(img1, 127, 255,0) ret, thresh2 = cv2.threshold(img2, 127, 255,0) contours,hierarchy,a = cv2.findContours(thresh,2,1) cnt1 = contours[0] contours,hierarchy,a = cv2.findContours(thresh2,2,1) cnt2 = contours[0] ret = cv2.matchShapes(cnt1,cnt2,1,0.0) print(ret) sys.exit()
[ 11748, 25064, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 198, 9600, 16, 796, 269, 85, 17, 13, 320, 961, 10786, 10459, 16, 13, 9479, 3256, 15, 8, 198, 9600, 17, 796, 269, 85, 17, 13, 320, 961, 10786, 10459, ...
2.004854
206
import os from __main__ import vtk, qt, ctk, slicer import EditorLib from EditorLib.EditOptions import HelpButton from EditorLib.EditOptions import EditOptions from EditorLib import EditUtil from EditorLib import LabelEffect # # EditorEffectTemplateTool # # # EditorEffectTemplateLogic # # # The InteractiveConnectedComponentsUsingParzenPDFs Template class definition # # # EditorEffectTemplate # # # EditorEffectTemplateWidget #
[ 11748, 28686, 198, 6738, 11593, 12417, 834, 1330, 410, 30488, 11, 10662, 83, 11, 269, 30488, 11, 14369, 263, 198, 11748, 12058, 25835, 198, 6738, 12058, 25835, 13, 18378, 29046, 1330, 10478, 21864, 198, 6738, 12058, 25835, 13, 18378, 2904...
3.532258
124
from django.urls import path from category.views import List,Detail,Create,Delete,Update,Search,All urlpatterns = [ path('all',All.as_view()), path('list/<int:pk>',List.as_view()), path('search/<str:pk>',Search.as_view()), path('detail/<int:pk>',Detail.as_view()), path('create', Create.as_view()), path('delete/<int:pk>', Delete.as_view()), path('update/<int:pk>', Update.as_view()), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 6536, 13, 33571, 1330, 7343, 11, 11242, 603, 11, 16447, 11, 38727, 11, 10260, 11, 18243, 11, 3237, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 10786, 439, 3...
2.331461
178
# ------------------------------------------ # Description: This python script will update AWS Thing Shadow for a Device/Thing # ------------------------------------------ # Import package import paho.mqtt.client as mqtt import ssl, time, sys # ======================================================= # Set Following Variables # AWS IoT Endpoint MQTT_HOST = "your aws iot endpoint" # CA Root Certificate File Path CA_ROOT_CERT_FILE = "path for the aws root certificate file" # AWS IoT Thing Name THING_NAME = "your thing name" # AWS IoT Thing Certificate File Path THING_CERT_FILE = "path for your device certificate file" # AWS IoT Thing Private Key File Path THING_PRIVATE_KEY_FILE = "path for your device private key" # ======================================================= # ======================================================= # No need to change following variables MQTT_PORT = 8883 MQTT_KEEPALIVE_INTERVAL = 45 SHADOW_UPDATE_TOPIC = "$aws/things/" + THING_NAME + "/shadow/update" SHADOW_UPDATE_ACCEPTED_TOPIC = "$aws/things/" + THING_NAME + "/shadow/update/accepted" SHADOW_UPDATE_REJECTED_TOPIC = "$aws/things/" + THING_NAME + "/shadow/update/rejected" SHADOW_STATE_DOC_LED_ON = """{"state" : {"desired" : {"LED" : "ON"}}}""" SHADOW_STATE_DOC_LED_OFF = """{"state" : {"desired" : {"LED" : "OFF"}}}""" RESPONSE_RECEIVED = False # ======================================================= # Initiate MQTT Client mqttc = mqtt.Client("led_switch_client") # Define on_message event function. # This function will be invoked every time, # a new message arrives for the subscribed topic # Register callback functions mqttc.on_message = on_message mqttc.on_connect = on_connect # Configure TLS Set mqttc.tls_set(CA_ROOT_CERT_FILE, certfile=THING_CERT_FILE, keyfile=THING_PRIVATE_KEY_FILE, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None) # Connect with MQTT Broker mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL) mqttc.loop_start() print "Enter 1 to Turn On the LED" print "Enter 2 to Turn OFF the LED" print "Enter 3 to exit" data = raw_input("Select an option:") if data == "1": mqttc.publish(SHADOW_UPDATE_TOPIC, SHADOW_STATE_DOC_LED_ON, qos=1) elif data == "2": mqttc.publish(SHADOW_UPDATE_TOPIC, SHADOW_STATE_DOC_LED_OFF, qos=1) elif data == "3": sys.exit() else: print("Invalid input try again...") sys.exit() # Wait for Response Counter = 1 while True: if RESPONSE_RECEIVED == True: break print "I have finished my work!!!" # time.sleep(1) # if Counter == 10: # print "No response from AWS IoT. Check your Settings." # break # elif RESPONSE_RECEIVED == True: # break
[ 2, 20368, 35937, 198, 2, 12489, 25, 770, 21015, 4226, 481, 4296, 30865, 21561, 8843, 329, 257, 16232, 14, 51, 722, 198, 2, 20368, 35937, 198, 198, 2, 17267, 5301, 198, 11748, 279, 17108, 13, 76, 80, 926, 13, 16366, 355, 285, 80, 9...
2.908992
923
import time from lightpi.hardware import strip, string1, string2 DELAY_SEC = 0.3 # Test the RGB Strip strip.red() time.sleep(DELAY_SEC) strip.green() time.sleep(DELAY_SEC) strip.blue() time.sleep(DELAY_SEC) strip.off() # Test the LED Strings string1.on() time.sleep(DELAY_SEC) string1.off() time.sleep(DELAY_SEC) string2.on() time.sleep(DELAY_SEC) string2.off() ################################################################################ # Helper Methods ################################################################################
[ 11748, 640, 198, 198, 6738, 1657, 14415, 13, 10424, 1574, 1330, 10283, 11, 4731, 16, 11, 4731, 17, 628, 198, 35, 3698, 4792, 62, 23683, 796, 657, 13, 18, 198, 198, 2, 6208, 262, 25228, 18508, 198, 36311, 13, 445, 3419, 198, 2435, ...
3.236686
169
#!/usr/bin/env python # -*- coding: utf-8 -*- # # wind_direction.py # # Copyright 2020 <Simone Severini> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # import time import board import busio import adafruit_ads1x15.ads1115 as ADS from adafruit_ads1x15.analog_in import AnalogIn
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 220, 2344, 62, 37295, 13, 9078, 198, 2, 220, 220, 198, 2, 220, 15069, 12131, 220, 1279, 8890, 505, 26434...
3.232558
301
# Copyright 2017 Cloudbase Solutions SRL # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.common import waiters import testtools from oswin_tempest_plugin import config CONF = config.CONF
[ 2, 15069, 2177, 10130, 8692, 23555, 311, 7836, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407...
3.396396
222
#!/usr/bin/python import rospy import rosbag import time
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 686, 2777, 88, 198, 11748, 686, 82, 21454, 198, 11748, 640, 628, 628, 198 ]
2.583333
24
"""A logging handler class which produces coloured logs.""" import logging import click
[ 37811, 32, 18931, 21360, 1398, 543, 11073, 34746, 17259, 526, 15931, 628, 198, 11748, 18931, 198, 198, 11748, 3904, 628 ]
4.6
20
# -*- coding: utf-8 -*- from PyQt5 import QtCore import numpy as np from matplotlib.figure import Figure import time import matplotlib matplotlib.use("Qt5Agg") # QT5 from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 9485, 48, 83, 20, 1330, 33734, 14055, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 2603, 29487, 8019, 13, 26875, 1330, 11291, 198, 11748, 640, 198, 11748, 2603, ...
2.777778
90
#!/usr/bin/env python # -*- coding: utf-8 -*- # # @Author: Tom Dwelly # @Date: 2020-03-03 # @Filename: bhm_spiders_agn.py # @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) # derived from guide.py # ### flake8: noqa # isort: skip_file import peewee from peewee import JOIN from peewee import fn from target_selection.cartons.base import BaseCarton # general catalogdb imports from sdssdb.peewee.sdss5db.catalogdb import ( Catalog, EROSITASupersetAGN, ) # imports of existing spectro catalogues from sdssdb.peewee.sdss5db.catalogdb import ( CatalogToSDSS_DR16_SpecObj, SDSS_DR16_SpecObj, CatalogToBHM_eFEDS_Veto, BHM_eFEDS_Veto, SDSSV_BOSS_SPALL, SDSSV_BOSS_Conflist, SDSSV_Plateholes, SDSSV_Plateholes_Meta, ) # additional imports required by bhm_spiders_agn_lsdr8 from sdssdb.peewee.sdss5db.catalogdb import ( CatalogToLegacy_Survey_DR8, Legacy_Survey_DR8, ) # additional imports required by bhm_spiders_agn_gaiadr2 from sdssdb.peewee.sdss5db.catalogdb import ( CatalogToTIC_v8, TIC_v8, ) # additional imports required by bhm_spiders_agn_ps1dr2 from sdssdb.peewee.sdss5db.catalogdb import ( Panstarrs1, CatalogToPanstarrs1, ) # additional imports required by bhm_spiders_agn_skymapperdr2 from sdssdb.peewee.sdss5db.catalogdb import ( SkyMapper_DR2, CatalogToSkyMapper_DR2, ) # additional imports required by bhm_spiders_agn_supercosmos from sdssdb.peewee.sdss5db.catalogdb import ( SuperCosmos, CatalogToSuperCosmos, CatalogToCatWISE2020, ) from target_selection.mag_flux import AB2nMgy, AB2Jy # used by cartons that need to compute Galactic latitude: north_gal_pole_ra = 192.85948 # deg, J2000 north_gal_pole_dec = +27.12825 # deg, J2000 # ############################################ # ############################################ # ############################################ # ############################################ # This provides the following BHM SPIDERS AGN cartons in v0.5: # * bhm_spiders_agn_lsdr8 # * bhm_spiders_agn_efeds_stragglers # * bhm_spiders_agn_gaiadr2 # * bhm_spiders_agn_sep # * bhm_spiders_agn_ps1dr2 # * bhm_spiders_agn_skymapperdr2 # bhm_spiders_agn_supercosmos # ############################################ # ############################################ # ############################################ # ############################################ # some reference points for AB->nMgy conversions # 30.0 AB = 1e-3 nMgy # 22.5 AB = 1.0 nMgy # 22.0 AB = 1.58489 nMgy # 21.5 AB = 2.51189 nMgy # 21.0 AB = 3.98107 nMgy # 20.0 AB = 10.0 nMgy # 18.5 AB = 39.8107 nMgy # 16.5 AB = 251.189 nMgy # 14.0 AB = 2511.89 nMgy # 13.5 AB = 3981.07 nMgy # some reference points for AB->Jy conversions (for ps1_dr2 fluxes) # 30.0 AB = 3.631e-9 Jy # 22.5 AB = 3.631e-6 Jy # 22.0 AB = 5.754e-6 Jy # 21.5 AB = 9.120e-6 Jy # 21.0 AB = 1.445e-5 Jy # 20.5 AB = 2.291e-5 Jy # 18.5 AB = 1.445e-4 Jy # 16.5 AB = 9.120e-4 Jy # 14.0 AB = 9.120e-3 Jy # 13.5 AB = 1.445e-2 Jy # Notes on catalogdb.panstarrs1.flags aka objInfoFlag from ObjectThin # https://outerspace.stsci.edu/display/PANSTARRS/PS1+ObjectThin+table+fields # https://outerspace.stsci.edu/display/PANSTARRS/PS1+Object+Flags # select objects that have the GOOD_STACK flag set: # Flag name value decimal Notes # GOOD_STACK 0x08000000 134217728 good-quality object in the stack (> 1 good stack measurement) # Use these two flags to decide whether to use aper mags or not # Flag name value decimal Notes # EXT 0x00800000 8388608 extended in our data (eg, PS) # EXT_ALT 0x01000000 16777216 extended in external data (eg, 2MASS) # Notes on how many targets to expect: # sdss5db=> SELECT ero_version,xmatch_method,xmatch_version,opt_cat,count(*) # FROM erosita_superset_agn GROUP BY ero_version,xmatch_method,xmatch_version,opt_cat; # ero_version | xmatch_method | xmatch_version | opt_cat | count # --------------------------+----------------+--------------------------+--------------+-------- # eFEDS_c001_V18C_V3_ext | XPS/MLR | Merged_03DEC2020 | lsdr8 | 14 # eFEDS_c001_V18C_V3_ext | XPS/NWAY | Merged_03DEC2020 | lsdr8 | 248 # eFEDS_c001_V18C_V3_main | XPS/MLR | Merged_03DEC2020 | lsdr8 | 794 # eFEDS_c001_V18C_V3_main | XPS/NWAY | Merged_03DEC2020 | lsdr8 | 26575 # em01_c946_201008_poscorr | XPS/NWAY | JWMS_CW2_v_03_TDopt | gaiadr2 | 441175 # em01_c946_201008_poscorr | XPS/NWAY | JWMS_CW2_v_03_TDopt | lsdr8 | 305076 # em01_c946_201008_poscorr | XPS/NWAY | JWMS_CW2_v_03_TDopt | ps1dr2 | 241150 # em01_c946_201008_poscorr | XPS/NWAY | JWMS_CW2_v_03_TDopt | skymapperdr2 | 312372 # em01_c946_201008_poscorr | XPS/NWAY | JWMS_v_03 | catwise2020 | 740691 # em01_c946_201008_poscorr | XPS/NWAY | JWMS_v_40 | lsdr8 | 345189 # em01_SEP_c946 | XPS/NWAY | SEP_CW2_07DEC2020 | catwise2020 | 32268 # em01_SEP_c946 | XPS/NWAY | SEP_CW2_07DEC2020_TDopt | gaiadr2 | 309 # em01_SEP_c946 | XPS/NWAY | SEP_CW2_NOV2020_MSopt | gaiadr2 | 740 # (13 rows) # Notes on avoiding saturated legacysurvey sources # https://www.legacysurvey.org/dr8/bitmasks/ # Bit Name Description # 0 NPRIMARY touches a pixel that is outside the BRICK_PRIMARY region of a brick # 1 BRIGHT touches a pixel within the locus of a radius-magnitude relation for # Tycho-2 stars or one for Gaia DR2 stars to G < 13 # 2 SATUR_G touches a pixel that was saturated in at least one g-band image # 3 SATUR_R touches a pixel that was saturated in at least one r-band image # 4 SATUR_Z touches a pixel that was saturated in at least one z-band image # 5 ALLMASK_G touches a pixel that has any of the ALLMASK_G bits set # 6 ALLMASK_R touches a pixel that has any of the ALLMASK_R bits set # 7 ALLMASK_Z touches a pixel that has any of the ALLMASK_Z bits set # 8 WISEM1 touches a pixel in a WISEMASK_W1 bright star mask # 9 WISEM2 touches a pixel in a WISEMASK_W2 bright star mask # 10 BAILOUT touches a pixel in a blob where we "bailed out" of source fitting # 11 MEDIUM touches a pixel within the locus of a radius-magnitude relation # for Gaia DR2 stars to G < 16 # 12 GALAXY touches a pixel in an SGA large galaxy # 13 CLUSTER touches a pixel in a globular cluster # # so, mask to avoid saturated targets is 2**2 + 2**3 + 2**4 = 4+8+16 = 28 # # END PREAMBLE # ################################################################################## # # END BhmSpidersAgnLsdr8Carton # ################################################################################## # # END BhmSpidersAgnEfedsStragglersCarton # ################################################################################## # # END BhmSpidersAgnGaiadr2Carton # ################################################################################## # # END BhmSpidersAgnSepCarton # ################################################################################## # # END BhmSpidersAgnPs1dr2Carton # ################################################################################## # # END BhmSpidersAgnSkyMapperDr2Carton # ################################################################################## # # END BhmSpidersAgnSuperCosmosCarton # ##################################################################################
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 2488, 13838, 25, 4186, 42979, 88, 198, 2, 2488, 10430, 25, 12131, 12, 3070, 12, 3070, 198, 2, 2488, 3506...
2.414757
3,185
# Generated by Django 3.1.6 on 2021-04-22 00:59 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 21, 319, 33448, 12, 3023, 12, 1828, 3571, 25, 3270, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
""" Data terrain model (DTM). Examples:: >>> from worldmap import DTM >>> dtm = DTM() >>> print(dtm["NOR"]) Location('Norway') """ from typing import Dict, List, Tuple, Set, Optional from bokeh.models import Model from bokeh.models import ColumnDataSource, Patches, LabelSet import logging import numpy as np from .location import Location from .coloring import set_location_colors from ..utils.data_fetcher import get_world_topology, get_country_polygon
[ 37811, 198, 6601, 15510, 2746, 357, 35, 15972, 737, 198, 198, 27730, 3712, 628, 220, 220, 220, 13163, 422, 995, 8899, 1330, 360, 15972, 198, 220, 220, 220, 13163, 288, 17209, 796, 360, 15972, 3419, 198, 220, 220, 220, 13163, 3601, 7, ...
3.083871
155
""" """ from Crypto.PublicKey import RSA from Crypto.Hash import SHA256 from Crypto.Signature import PKCS1_v1_5 from base58 import b58encode, b58decode # ================= cryptography helpers ====================================== def hash(data): """Hash some data """ # Hash the stuff we need to hash digest = SHA256.new() digest.update(data) hash= digest.hexdigest() return hash def sign(private_key:RSA.RsaKey, message): """Sign a message Parameters ---------- private_key (RSAPublicKey) : The private key to sign the message with message (str) : The message to be signed """ hasher = SHA256.new(message) signer = PKCS1_v1_5.new(private_key) signature = signer.sign(hasher) return signature def verify(public_key, message, signature): """Verify the message signature Parameters ---------- public_key (RSAPublicKey) : The public key to verify that the sender is the right one message (str) : The signed message (used for verification) signature (str) : The signature """ hasher = SHA256.new(message) verifier = PKCS1_v1_5.new(public_key) return verifier.verify(hasher, signature) def privateKey2Text(key:RSA.RsaKey): """Converts a private key to text """ return b58encode(key.exportKey('DER')) def publicKey2Text(key:RSA.RsaKey): """Converts a public key to text """ return b58encode(key.exportKey('DER')) def text2PrivateKey(text:str): """Convert a text to a private key """ return RSA.importKey(b58decode(text)) def text2PublicKey(text:str): """Convert a text to a key """ return RSA.importKey(b58decode(text))
[ 37811, 198, 37811, 198, 6738, 36579, 13, 15202, 9218, 1330, 42319, 198, 6738, 36579, 13, 26257, 1330, 25630, 11645, 198, 6738, 36579, 13, 11712, 1300, 1330, 29673, 7902, 16, 62, 85, 16, 62, 20, 198, 6738, 2779, 3365, 1330, 275, 3365, ...
2.65745
651
import numpy as np import matplotlib.pyplot as plt mandelbrot(120, 6000)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 628, 198, 22249, 417, 7957, 83, 7, 10232, 11, 39064, 8 ]
2.740741
27
import unittest import copy import os import tempfile from config_tool.utils import * if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 11748, 4866, 198, 11748, 28686, 198, 11748, 20218, 7753, 198, 198, 6738, 4566, 62, 25981, 13, 26791, 1330, 1635, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 7...
2.893617
47
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2019-Present Datadog, Inc. from datadog_api_client.v2.model_utils import ( ModelNormal, cached_property, datetime, )
[ 2, 17486, 11777, 5081, 4306, 477, 3696, 287, 428, 16099, 389, 11971, 739, 262, 24843, 12, 17, 13, 15, 13789, 13, 198, 2, 770, 1720, 3407, 3788, 4166, 379, 16092, 324, 519, 357, 5450, 1378, 2503, 13, 19608, 4533, 456, 80, 13, 785, ...
3.336634
101
import logging logging.Filter.filter logging.getLogger().propagate logging.StreamHandler.emit
[ 11748, 18931, 198, 198, 6404, 2667, 13, 22417, 13, 24455, 198, 6404, 2667, 13, 1136, 11187, 1362, 22446, 22930, 37861, 198, 6404, 2667, 13, 12124, 25060, 13, 368, 270, 198 ]
3.166667
30
import platform import pytest
[ 11748, 3859, 198, 198, 11748, 12972, 9288, 628 ]
4
8
# bloque principal fecha=cargar_fecha() imprimir_fecha(fecha)
[ 201, 198, 201, 198, 2, 24924, 4188, 10033, 201, 198, 201, 198, 69, 3055, 64, 28, 66, 853, 283, 62, 69, 3055, 64, 3419, 201, 198, 320, 1050, 13057, 62, 69, 3055, 64, 7, 69, 3055, 64, 8 ]
1.815789
38
# %% l = [38,32,49,15,806,806] sum(l) # %% len(l) # %% sum(l)//len(l) # %% l.sort() # %% l # %% # %% l.most_common(1) # %% ''' ''' from collections import Counter l = ['38','32','49','15','806','806'] c = Counter(l) print(c.most_common()[0][0]) print(c.most_common(1)) print(c.most_common(2)) # %% c.most_common()[0] # %% print(33) # %%
[ 2, 43313, 198, 75, 796, 685, 2548, 11, 2624, 11, 2920, 11, 1314, 11, 37988, 11, 37988, 60, 198, 16345, 7, 75, 8, 198, 2, 43313, 198, 11925, 7, 75, 8, 198, 2, 43313, 198, 16345, 7, 75, 8, 1003, 11925, 7, 75, 8, 198, 2, 43313,...
1.948864
176
""" Network class is in charge of: 1. Storing M - User Cache Size, N - Number of Files, K - Number of Users 2. Storing User instances, Server instance, and attacker instance """ import numpy as np from scipy import special import itertools from Server import Server from User import User from tabulate import tabulate T_BE_INTEGER = True if __name__ == "__main__": # if t is specified, M is not needed. Currently, I only consider t to be a positive integer. # M: unified cache size per user (if t is specified, M is not useful anymore) # N: number of files in the network # K: number of users in the network # t: M*K/N, # M, N, K, t = -1, 3, 3, 1 M, N, K, t = -1, 3, 5, 3 # M, N, K, t = -1, 4, 5, 2 codedCachingNetwork = Network(M=M, N=N, K=K, t=t, fileId2Alphabet=True) print(codedCachingNetwork) # codedCachingNetwork.placement(verboseForCache=True, verboseForUser=True, isRandom=True) codedCachingNetwork.placement(verboseForCache=True, verboseForUser=True, isRandom=False) X_D_table = [] # for D in itertools.combinations_with_replacement(range(N), K): for D in codedCachingNetwork.allD(): D, X, groupList = codedCachingNetwork.delivery(verbose=False, D=D) # generate X based on D groupList D_str = ",".join(list(map(lambda d: chr(65+ d), D))) X_D_table.append(["["+D_str+"]"] + codedCachingNetwork.printableServerTransmission(X, inList=True, fileId2Alphabet=True)) # header = ["D", "X"] header = ["D"] + groupList print(tabulate(X_D_table, headers=header))
[ 37811, 198, 26245, 1398, 318, 287, 3877, 286, 25, 198, 16, 13, 520, 3255, 337, 532, 11787, 34088, 12849, 11, 399, 532, 7913, 286, 13283, 11, 509, 532, 7913, 286, 18987, 198, 17, 13, 520, 3255, 11787, 10245, 11, 9652, 4554, 11, 290, ...
2.629382
599
from . import omniglot
[ 6738, 764, 1330, 22284, 328, 26487, 198 ]
3.285714
7
# two templates are used in this app from flask import Flask, render_template app = Flask(__name__) if __name__ == '__main__': app.run(debug=True)
[ 2, 734, 24019, 389, 973, 287, 428, 598, 220, 198, 198, 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, ...
2.90566
53
import asyncio
[ 11748, 30351, 952, 628, 198 ]
3.4
5
import json from io import BytesIO from app.ext.api.exceptions import ( ChefNotFound, InvalidToken, MaximumImageCapacityError, OperationNotAllowed, RecipeWithoutIngredient, RecipeWithoutPreparationMode, ) from app.ext.api.services import token_services
[ 11748, 33918, 198, 6738, 33245, 1330, 2750, 4879, 9399, 198, 198, 6738, 598, 13, 2302, 13, 15042, 13, 1069, 11755, 1330, 357, 198, 220, 220, 220, 26383, 3673, 21077, 11, 198, 220, 220, 220, 17665, 30642, 11, 198, 220, 220, 220, 22246,...
2.94898
98
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-28 09:36 from __future__ import unicode_literals from django.db import migrations, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 940, 13, 18, 319, 1584, 12, 1157, 12, 2078, 7769, 25, 2623, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.736842
57
import os import sys from pathlib import Path sys.path.insert(0, 'exactdelaypathfinder')
[ 11748, 28686, 198, 11748, 25064, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 17597, 13, 6978, 13, 28463, 7, 15, 11, 705, 1069, 529, 40850, 6978, 22805, 11537, 198 ]
3.103448
29
import time from collections import defaultdict if __name__ == "__main__": part1() part2()
[ 11748, 640, 198, 6738, 17268, 1330, 4277, 11600, 628, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 628, 220, 220, 220, 636, 16, 3419, 198, 220, 220, 220, 636, 17, 3419, 198 ]
2.888889
36
from microbit import * import struct from time import sleep SENSORS = 2 spi.init(baudrate=100000) while True: for i in [0, 1]: print(i, ord(spi_read(i))) sleep(0.1)
[ 6738, 4580, 2545, 1330, 1635, 198, 11748, 2878, 198, 6738, 640, 1330, 3993, 198, 198, 50, 16938, 20673, 796, 362, 198, 198, 2777, 72, 13, 15003, 7, 65, 3885, 4873, 28, 3064, 830, 8, 198, 4514, 6407, 25, 198, 220, 220, 220, 329, 13...
2.188235
85
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import datetime import typing as t import json from dataclasses import dataclass, field from mypy_boto3_dynamodb.service_resource import Table from boto3.dynamodb.conditions import Attr, Key """ Data transfer object classes to be used with dynamodbstore Classes in this module should implement methods `to_dynamodb_item(self)` and `to_sqs_message(self)` """ class HashRecordQuery: DEFAULT_PROJ_EXP = "PK, ContentHash, UpdatedAt, Quality"
[ 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 1439, 6923, 33876, 198, 198, 11748, 4818, 8079, 198, 11748, 19720, 355, 256, 198, 11748, 33918, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 11, 2214, 198, 6738, ...
3.180723
166
from .bucket_tensor_copy import BucketizedTensorCopy __all__ = ['BucketizedTensorCopy']
[ 6738, 764, 27041, 316, 62, 83, 22854, 62, 30073, 1330, 48353, 1143, 51, 22854, 29881, 198, 198, 834, 439, 834, 796, 37250, 33, 38811, 1143, 51, 22854, 29881, 20520, 198 ]
2.966667
30
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.888889
9
import numpy as np import pytest from ddtruss import Truss, DataDrivenSolver points = np.array([[0, 0], [1, 0], [0.5, 0.5], [2, 1]]) lines = np.array([[0, 2], [1, 2], [1, 3], [2, 3]], dtype=int) truss = Truss(points, lines) E = 1.962e11 A = [2e-4, 2e-4, 1e-4, 1e-4] U_dict = {0: [0, 0], 1: [0, 0]} F_dict = {3: [0, -9.81e3]} u_ref = np.array( [0, 0, 0, 0, 2.65165043e-4, 8.83883476e-5, 3.47902545e-3, -5.60034579e-3] )
[ 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 9288, 198, 198, 6738, 49427, 2213, 1046, 1330, 833, 1046, 11, 6060, 20564, 574, 50, 14375, 198, 198, 13033, 796, 45941, 13, 18747, 26933, 58, 15, 11, 657, 4357, 685, 16, 11, 657, 4357,...
1.784232
241
from datetime import datetime from app import db
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 598, 1330, 20613, 628, 628, 628 ]
3.857143
14
import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from utils.utils import gpu_wrapper from Modules.subModules.attention import AttentionUnit from torch.nn.utils.rnn import pack_padded_sequence as pack from torch.nn.utils.rnn import pad_packed_sequence as unpack
[ 11748, 28686, 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, 6738, 28034, 13, 2306, 519, 6335, 1330, 35748, 198, 6738, 3384, 448...
3.415842
101
""" `minion-ci` is a minimalist, decentralized, flexible Continuous Integration Server for hackers. This module contains the parser to parse the `minion.yml` file. :copyright: (c) by Timo Furrer :license: MIT, see LICENSE for details """ import yaml from .errors import MinionError def parse(path): """Parse the given minion.yml file""" try: with open(path) as minion_file: config = yaml.load(minion_file) except OSError: raise MinionError("No minion.yml config file found in repository") return config
[ 37811, 198, 220, 220, 220, 4600, 1084, 295, 12, 979, 63, 318, 257, 44693, 11, 26512, 11, 12846, 45012, 38410, 9652, 329, 17110, 13, 628, 220, 220, 220, 770, 8265, 4909, 262, 30751, 284, 21136, 262, 4600, 1084, 295, 13, 88, 4029, 63,...
2.845
200
# -*- coding: utf-8 -*- from pymongo import MongoClient from finace import settings if __name__ == '__main__': spider = SpiderCity() url_list = spider.get() print(url_list)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 279, 4948, 25162, 1330, 42591, 11792, 198, 198, 6738, 957, 558, 1330, 6460, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220,...
2.611111
72
import structlog import logging import sys import os from structlog.processors import JSONRenderer from structlog.stdlib import filter_by_level from structlog.stdlib import add_log_level_number from .datadog import tracer_injection LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")
[ 11748, 2878, 6404, 198, 11748, 18931, 198, 11748, 25064, 198, 11748, 28686, 198, 198, 6738, 2878, 6404, 13, 14681, 669, 1330, 19449, 49, 437, 11882, 198, 6738, 2878, 6404, 13, 19282, 8019, 1330, 8106, 62, 1525, 62, 5715, 198, 6738, 2878...
3.204545
88
""" templator.py reads in an excel file and a template and outputs a file for each row in the excel file, by substituting the template variables with the values in the columns. This technique uses pandas to read the excel file into a DataFrame and the python format operator ``%``` to apply the values. """ import sys import os import pandas as pd if __name__ == '__main__': template_file = os.path.join(os.path.dirname(__file__), 'template.txt') excel_file = os.path.join(os.path.dirname(__file__), 'variables.xls') main(template_file, excel_file)
[ 37811, 198, 11498, 489, 1352, 13, 9078, 9743, 287, 281, 27336, 2393, 290, 257, 11055, 220, 290, 23862, 257, 2393, 329, 1123, 5752, 198, 259, 262, 27336, 2393, 11, 416, 21436, 15129, 262, 11055, 9633, 351, 262, 3815, 287, 262, 15180, 1...
3.149171
181
import unittest from test_base import TestBaseImporter from test_child import TestChildImporter if __name__ == '__main__': test_loader = unittest.TestLoader() test_classes_to_run = [TestBaseImporter, TestChildImporter] suites_list = [] for test_class in test_classes_to_run: suite = test_loader.loadTestsFromTestCase(test_class) suites_list.append(suite) big_suite = unittest.TestSuite(suites_list) unittest.TextTestRunner().run(big_suite)
[ 11748, 555, 715, 395, 198, 6738, 1332, 62, 8692, 1330, 6208, 14881, 3546, 26634, 198, 6738, 1332, 62, 9410, 1330, 6208, 16424, 3546, 26634, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1332, ...
2.625
184
# import tensorflow as tf # print(tf.__version__) # # # with tf.name_scope('scalar_set_one') as scope: # tf_constant_one = tf.constant(10, name="ten") # tf_constant_two = tf.constant(20, name="twenty") # scalar_sum_one = tf.add(tf_constant_one, tf_constant_two, name="scalar_ten_plus_twenty") # # # # with tf.name_scope('scalar_set_two') as scope: # tf_constant_three = tf.constant(30, name="thirty") # tf_constant_four = tf.constant(40, name="fourty") # scalar_sum_two = tf.add(tf_constant_three, tf_constant_four, name="scalar_thirty_plus_fourty") # # # scalar_sum_sum = tf.add(scalar_sum_one, scalar_sum_two) # # # sess = tf.Session() # sess.run(tf.global_variables_initializer()) # # tf_tensorboard_writer = tf.summary.FileWriter('./graphs', sess.graph) # tf_tensorboard_writer.close() # sess.close() import scipy import _pickle as cPickle data = unpickle("model_svm_relations.pkl")
[ 2, 1330, 11192, 273, 11125, 355, 48700, 198, 2, 3601, 7, 27110, 13, 834, 9641, 834, 8, 198, 2, 198, 2, 198, 2, 351, 48700, 13, 3672, 62, 29982, 10786, 1416, 282, 283, 62, 2617, 62, 505, 11537, 355, 8354, 25, 198, 2, 220, 220, ...
2.296482
398
from objects.user.User import User from objects.interface.dbconn import DB from objects.user.Currency import get_currency_symbol from objects.threads.UploadThread import UploadThread import utils.globals as _globals from utils.print import print_message, print_error from utils.enums import Months, SettingsSelection, is_valid_month, month_string_to_enum from utils.visualizer import visualizer, visualizer_helper from utils.builders.folderbuilder import create_user_folder from utils.exceptions import NoDataFound, NoTotalFound, InvalidMonth, InvalidYear, UserNotFound from utils.dates.dates import get_dates, subtract_days from utils.averager.averager import calculate_average from utils.formatting.formatter import format_date_pretty, format_month_enum_to_string from utils.generators.csv_generator import generate_transaction_files from menus.user.Settings import Settings def user_has_data(user: User) -> bool: """ Test to determine if a user has any data :param user: The user to check. :return: True if the user has data. False otherwise. """ # Determine if the user has any available data. try: user.get_earliest_transaction_date() except Exception: # excepting NoDataFound here does not work for some reason? print_error("No data is currently available.") return False return True def is_valid_year(year_to_check: str) -> bool: """ Determine if the passed in year currently exists within the database. :param year_to_check: The year to check. :return: True if the year exists, false otherwise. """ year_is_valid = False db = DB(_globals.DATABASE) years = db.fetchall(f"SELECT DISTINCT strftime('%Y', Date) from Transactions;") db.close() # search through all the years. If the year that was specified exists, set the flag to true. for year in years: if year_to_check == year[0]: year_is_valid = True break return year_is_valid def get_month_and_year() -> (Months, str): """ Prompt a user to enter a month and a year. :raises InvalidMonth: Exception that is to be raised when user enters an invalid month. :raises InvalidYear: Exception that is to be raised when user enters an invalid year. :return: A Month enum and the year the user selected. """ month = input("Enter a month:\t") month_enum = month_string_to_enum(month) if is_valid_month(month_enum): year = input("Enter a year:\t") if is_valid_year(year): return month_enum, year else: raise InvalidYear(year) else: raise InvalidMonth(month) def get_year(): """ Prompt a user to enter a year. :raises InvalidYear: Exception that is to be raised if a user enters an invalid year. :return: The year the user enters. """ year = input("Enter a year:\t") if is_valid_year(year): return year raise InvalidYear(year) def display_monthly_information(user: User, month: Months, year: str, show_console: bool = False, show_visual: bool = False) -> None: """ Display information regarding the total money spent within a month. :param user: The current user. :param month: The month to get the information regarding how much was spent. :param year: The year corresponding to the month. :param show_console: Boolean to determine whether or not to display the information of the total spent in a month to the console. :param show_visual: Boolean to determine whether or not to display a visualization of the total spent in the month. """ try: # Dictionary that contains the information about all of the transactions in a given month. # The key is the day, the value is the total spent on that day. transactions_dictionary = visualizer_helper.get_transactions_by_month(month, year, user.id) # The total amount of money spent during the specified month. total = visualizer_helper.get_monthly_total(month, year, user.id) except (NoDataFound, NoTotalFound) as n: print_error(n.message) return # List to hold the dollar values for each day. dollars = [] # List to hold the labels that correspond to each day in the month that had a transaction. day_labels = [] # List of hold the labels that correspond to the dollar values for the transactions. dollars_labels = [] # The type of currency the current user is using. currency_symbol = get_currency_symbol(user.currency_id) # The title to be displayed on the console and/or the visualization title = f"Total spent in {format_month_enum_to_string(month)} {year}: {currency_symbol}{total:,}" for date_key in transactions_dictionary: day_labels.append(date_key) # Sort the labels (YYYY-MM-DD - End of Month) day_labels.sort() # Add the dollar amount to the corresponding day index, then create a label for that day. for day in day_labels: value = round(float(transactions_dictionary[day]), 2) dollars.append(value) dollars_labels.append(f"{currency_symbol}{value:,}") # Display each day and then display the total spent for the month if show_console: # TODO: change to function to prevent duplicated code. for i, day in enumerate(day_labels): print_message(f"{day}:\t{dollars_labels[i]}") print_message(f"{title}") # Display a visualization of the money spent in the month specified if show_visual: visualizer.display_bar_chart(title=title, list_of_values=dollars, list_of_labels=day_labels, currency_labels=dollars_labels) def display_yearly_information(user: User, year: str, show_console: bool = False, show_visual: bool = False) -> None: """ Display information regarding the total money spent within a certain year. :param user: The current user. :param year: The year to gather information from. :param show_console: Boolean to determine whether or not to display the information of the total spent in a year to the console. :param show_visual: Boolean to determine whether or not to display a visualization of the total spent in the month. """ try: # Dictionary to contain the total transaction values per month given the year transactions_dictionary = visualizer_helper.get_transactions_by_year(year, user.id) # The total amount of money spent during the specified year. total = visualizer_helper.get_yearly_total(year, user.id) except (NoDataFound, NoTotalFound) as n: print_error(n.message) return # List to hold the dollar values for each month. dollars = [] # List to hold the labels that correspond to the total number of transactions in each month. month_labels = [] # List of hold the labels that correspond to the dollar values for the transactions. dollars_labels = [] # The type of currency the current user is using. currency_symbol = get_currency_symbol(user.currency_id) # The title to be displayed on the console and/or the visualization title = f"Total Spent in {year}: {currency_symbol}{total:,}" for month_name in transactions_dictionary: value = round(float(transactions_dictionary[month_name]), 2) dollars.append(value) dollars_labels.append(f"{currency_symbol}{value:,}") # Not formatting month name here since the string is already in the key format for the months dictionary. month_labels.append(_globals.months[month_name]) if show_console: for i, month in enumerate(month_labels): print_message(f"{month}: {dollars_labels[i]}") print_message(f"{title}") if show_visual: visualizer.display_bar_chart(title=title, list_of_values=dollars, list_of_labels=month_labels, currency_labels=dollars_labels) def display_information_all_time(user: User, show_console: bool = False, show_visual: bool = False) -> None: """ Display information regarding the total money spent all time. :param user: The current user. :param show_console: Boolean to determine whether or not to display the information of the total spent in a year to the console. :param show_visual: Boolean to determine whether or not to display a visualization of the total spent in the month. """ try: transactions_dictionary = visualizer_helper.get_transactions_all_time(user.id) total = visualizer_helper.get_total_all_time(user.id) except NoDataFound as ndf: print_error(ndf.message) return # List to hold the total dollar values for each available year. dollars = [] # List to hold the labels that correspond to the total number of transactions in each year. year_labels = [] # List of hold the labels that correspond to the dollar values for the transactions. dollars_labels = [] # The type of currency the current user is using. currency_symbol = get_currency_symbol(user.currency_id) # The title to be displayed on the console and/or the visualization title = f"Total Spent All Time: {currency_symbol}{total:,}" for year in transactions_dictionary: value = round(float(transactions_dictionary[year]), 2) dollars.append(value) dollars_labels.append(f"{currency_symbol}{value:,}") year_labels.append(year) if show_console: for i, year in enumerate(year_labels): print_message(f"{year}: {dollars_labels[i]}") print_message(f"{title}") if show_visual: visualizer.display_bar_chart(title=title, list_of_values=dollars, list_of_labels=year_labels, currency_labels=dollars_labels)
[ 6738, 5563, 13, 7220, 13, 12982, 1330, 11787, 198, 6738, 5563, 13, 39994, 13, 9945, 37043, 1330, 20137, 198, 6738, 5563, 13, 7220, 13, 34, 13382, 1330, 651, 62, 34415, 62, 1837, 23650, 198, 6738, 5563, 13, 16663, 82, 13, 41592, 16818,...
2.73018
3,721
# -*- coding: UTF-8 -*- import base64 from functools import wraps import pyaes from flask import request from werkzeug.utils import redirect from website.domain.UserVO import UserVO
[ 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 11748, 2779, 2414, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 198, 11748, 279, 3972, 274, 198, 6738, 42903, 1330, 2581, 198, 6738, 266, 9587, 2736, 1018, 13, 26791, 1330,...
3.22807
57
#!/usr/bin/env python """ export_resized_ios_images Gimp plugin to export image to icon files usable on iOS. Author: ------- Tobias Blom, Techne Development AB <tobias.blom@techne-dev.se> Installation: ------------- Under Mac OS X, copy this file to ~/Library/Application Support/GIMP/x.x/plug-ins and make it executable (chmod 755) Usage: ------ 1. Create your image at a resolution four times what you want on a standard iOS device, twice the size on a retina device. GIMP image Plug-in output ------------------------------------------------- 80 x 80 @ 144 dpi | Icon 20 x 20 @ 72 dpi | Icon 40 x 40 @ 144 dpi | Icon 60 x 60 @ 144 dpi ------------------------------------------------- 120 x 120 @ 144 dpi | Icon 30 x 30 @ 72 dpi | Icon 60 x 60 @ 144 dpi | Icon 90 x 90 @ 144 dpi ------------------------------------------------- 2. Run the plug-in (from the File menu) and select the output directory. License: -------- Released under the MIT License Copyright (c) 2013-2017 Techne Development AB 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. """ from gimpfu import * import os register( "export_resized_ios_assets", "Exports iOS assets at 50% and 75% (144 dpi) and 25% (72 dpi) size", "Exports iOS assets at 50% and 75% (144 dpi) and 25% (72 dpi) size", "Techne Development AB", "Copyright (c) 2013-2017 Techne Development AB. Released under MIT License.", "2017", "<Image>/File/Export as iOS assets...", "RGB*, GRAY*", [ (PF_DIRNAME, "directory", "Output directory", os.path.expanduser("~")), ], [], plugin_main) main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 198, 39344, 62, 411, 1143, 62, 4267, 62, 17566, 198, 198, 38, 11011, 13877, 284, 10784, 2939, 284, 7196, 3696, 24284, 319, 8969, 13, 628, 198, 13838, 25, 198, 26866, 198, ...
3.0033
909
from timeit import default_timer as timer import random # shell sort using Knuth's sequence if __name__ == "__main__": main()
[ 6738, 640, 270, 1330, 4277, 62, 45016, 355, 19781, 198, 11748, 4738, 628, 628, 198, 2, 7582, 3297, 1262, 6102, 1071, 338, 8379, 628, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3...
3.159091
44
import datetime from django.utils.functional import cached_property from django.utils.safestring import mark_safe from office.offices import Office, OfficeSection from psalter.utils import get_psalms
[ 11748, 4818, 8079, 198, 198, 6738, 42625, 14208, 13, 26791, 13, 45124, 1330, 39986, 62, 26745, 198, 6738, 42625, 14208, 13, 26791, 13, 49585, 395, 1806, 1330, 1317, 62, 21230, 198, 198, 6738, 2607, 13, 2364, 1063, 1330, 4452, 11, 4452, ...
3.491803
61
import tide_constituents as tc from py_noaa import coops import pandas as pd import numpy as np import tappy start = '20180201' end = '20180228' interval = 1 start = pd.to_datetime(start) end = pd.to_datetime(end) d = start w, t, p, r = [], [], [], [] while d < end: start_ = d end_ = start_ + pd.DateOffset(interval) end_ = end_ if end_ < end else end water_level, tide = tc.get_water_levels(start_.strftime('%Y%m%d'), end_.strftime('%Y%m%d'), -88.2, 30.4) water_level = water_level.water_level.astype('float') prediction = 0.0 if 'Z0' not in list(tide.speed_dict.keys()) else tide.speed_dict['Z0'] prediction += sum_signals(tide.key_list, tide.dates, tide.speed_dict, tide.r, tide.phase) residual = water_level - prediction w.append(water_level) p.append(prediction) d = end_ water_level = pd.concat(w).to_frame() water_level.columns = ['observation'] water_level['prediction'] = np.hstack(p) data = tc.get_tides('20180101', '20181231', -88.2, 30.4) wl = data.predicted_wl.copy() grouped = wl.groupby(pd.Grouper(freq='M')) wl_demeaned = grouped.apply(f) min_month = wl_demeaned.rolling(30).min().groupby(pd.Grouper(freq='M')).last() max_month = wl_demeaned.rolling(30).max().groupby(pd.Grouper(freq='M')).last() monthly_minmax = min_month.copy() monthly_minmax['high'] = max_month['demeaned'] monthly_minmax = monthly_minmax[['demeaned', 'high']] monthly_minmax.columns = ['low', 'high'] monthly_minmax['range'] = monthly_minmax.high - monthly_minmax.low monthly_minmax.sort_values('range')
[ 11748, 20013, 62, 9979, 34272, 658, 355, 37096, 198, 6738, 12972, 62, 3919, 7252, 1330, 763, 2840, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 256, 7774, 628, 628, 198, 198, 9688, 796, 705, 12...
2.242466
730
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._inputs import * __all__ = ['CassandraTableArgs', 'CassandraTable'] class CassandraTable(pulumi.CustomResource): def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(CassandraTableArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, analytical_storage_ttl: Optional[pulumi.Input[int]] = None, autoscale_settings: Optional[pulumi.Input[pulumi.InputType['CassandraTableAutoscaleSettingsArgs']]] = None, cassandra_keyspace_id: Optional[pulumi.Input[str]] = None, default_ttl: Optional[pulumi.Input[int]] = None, name: Optional[pulumi.Input[str]] = None, schema: Optional[pulumi.Input[pulumi.InputType['CassandraTableSchemaArgs']]] = None, throughput: Optional[pulumi.Input[int]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = CassandraTableArgs.__new__(CassandraTableArgs) __props__.__dict__["analytical_storage_ttl"] = analytical_storage_ttl __props__.__dict__["autoscale_settings"] = autoscale_settings if cassandra_keyspace_id is None and not opts.urn: raise TypeError("Missing required property 'cassandra_keyspace_id'") __props__.__dict__["cassandra_keyspace_id"] = cassandra_keyspace_id __props__.__dict__["default_ttl"] = default_ttl __props__.__dict__["name"] = name if schema is None and not opts.urn: raise TypeError("Missing required property 'schema'") __props__.__dict__["schema"] = schema __props__.__dict__["throughput"] = throughput super(CassandraTable, __self__).__init__( 'azure:cosmosdb/cassandraTable:CassandraTable', resource_name, __props__, opts)
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 24118, 687, 10290, 357, 27110, 5235, 8, 16984, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760...
2.324773
1,324
# -*- coding: utf-8 -*- """hw10_adversarial_attack.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1yPa2ushzqw8FNobfonL79PHzudn0vjrN # **Homework 10 - Adversarial Attack** Slides: https://reurl.cc/v5kXkk Videos: TA: ntu-ml-2021spring-ta@googlegroups.com ## Enviroment & Download We make use of [pytorchcv](https://pypi.org/project/pytorchcv/) to obtain CIFAR-10 pretrained model, so we need to set up the enviroment first. We also need to download the data (200 images) which we want to attack. """ !nvidia-smi # set up environment !pip install pytorchcv # download !gdown --id 1fHi1ko7wr80wXkXpqpqpOxuYH1mClXoX -O data.zip # unzip !unzip ./data.zip !rm ./data.zip """## Global Settings * $\epsilon$ is fixed to be 8. But on **Data section**, we will first apply transforms on raw pixel value (0-255 scale) **by ToTensor (to 0-1 scale)** and then **Normalize (subtract mean divide std)**. $\epsilon$ should be set to $\frac{8}{255 * std}$ during attack. * Explaination (optional) * Denote the first pixel of original image as $p$, and the first pixel of adversarial image as $a$. * The $\epsilon$ constraints tell us $\left| p-a \right| <= 8$. * ToTensor() can be seen as a function where $T(x) = x/255$. * Normalize() can be seen as a function where $N(x) = (x-mean)/std$ where $mean$ and $std$ are constants. * After applying ToTensor() and Normalize() on $p$ and $a$, the constraint becomes $\left| N(T(p))-N(T(a)) \right| = \left| \frac{\frac{p}{255}-mean}{std}-\frac{\frac{a}{255}-mean}{std} \right| = \frac{1}{255 * std} \left| p-a \right| <= \frac{8}{255 * std}.$ * So, we should set $\epsilon$ to be $\frac{8}{255 * std}$ after ToTensor() and Normalize(). """ import torch import torch.nn as nn device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') batch_size = 8 # the mean and std are the calculated statistics from cifar_10 dataset cifar_10_mean = (0.491, 0.482, 0.447) # mean for the three channels of cifar_10 images cifar_10_std = (0.202, 0.199, 0.201) # std for the three channels of cifar_10 images # convert mean and std to 3-dimensional tensors for future operations mean = torch.tensor(cifar_10_mean).to(device).view(3, 1, 1) std = torch.tensor(cifar_10_std).to(device).view(3, 1, 1) epsilon = 8/255/std # TODO: iterative fgsm attack # alpha (step size) can be decided by yourself alpha = 0.01/255/std root = './data' # directory for storing benign images # benign images: images which do not contain adversarial perturbations # adversarial images: images which include adversarial perturbations """## Data Construct dataset and dataloader from root directory. Note that we store the filename of each image for future usage. """ import os import glob import shutil import numpy as np from PIL import Image from torchvision.transforms import transforms from torch.utils.data import Dataset, DataLoader transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(cifar_10_mean, cifar_10_std) ]) adv_set = AdvDataset(root, transform=transform) adv_names = adv_set.__getname__() adv_loader = DataLoader(adv_set, batch_size=batch_size, shuffle=False) print(f'number of images = {adv_set.__len__()}') """## Utils -- Benign Images Evaluation""" # to evaluate the performance of model on benign images """## Utils -- Attack Algorithm""" # perform fgsm attack # TODO: perform iterative fgsm attack # set alpha as the step size in Global Settings section # alpha and num_iter can be decided by yourself """## Utils -- Attack * Recall * ToTensor() can be seen as a function where $T(x) = x/255$. * Normalize() can be seen as a function where $N(x) = (x-mean)/std$ where $mean$ and $std$ are constants. * Inverse function * Inverse Normalize() can be seen as a function where $N^{-1}(x) = x*std+mean$ where $mean$ and $std$ are constants. * Inverse ToTensor() can be seen as a function where $T^{-1}(x) = x*255$. * Special Noted * ToTensor() will also convert the image from shape (height, width, channel) to shape (channel, height, width), so we also need to transpose the shape back to original shape. * Since our dataloader samples a batch of data, what we need here is to transpose **(batch_size, channel, height, width)** back to **(batch_size, height, width, channel)** using np.transpose. """ # perform adversarial attack and generate adversarial examples # create directory which stores adversarial examples """## Model / Loss Function Model list is available [here](https://github.com/osmr/imgclsmob/blob/master/pytorch/pytorchcv/model_provider.py). Please select models which has _cifar10 suffix. Some of the models cannot be accessed/loaded. You can safely skip them since TA's model will not use those kinds of models. """ from pytorchcv.model_provider import get_model as ptcv_get_model model = ptcv_get_model('preresnet110_cifar10', pretrained=True).to(device) loss_fn = nn.CrossEntropyLoss() benign_acc, benign_loss = epoch_benign(model, adv_loader, loss_fn) print(f'benign_acc = {benign_acc:.5f}, benign_loss = {benign_loss:.5f}') """## FGSM""" adv_examples, fgsm_acc, fgsm_loss = gen_adv_examples(model, adv_loader, fgsm, loss_fn) print(f'fgsm_acc = {fgsm_acc:.5f}, fgsm_loss = {fgsm_loss:.5f}') create_dir(root, 'fgsm', adv_examples, adv_names) """## I-FGSM""" # TODO: iterative fgsm attack adv_examples, ifgsm_acc, ifgsm_loss = gen_adv_examples(model, adv_loader, ifgsm, loss_fn) print(f'ifgsm_acc = {ifgsm_acc:.5f}, ifgsm_loss = {ifgsm_loss:.5f}') create_dir(root, 'ifgsm', adv_examples, adv_names) """## Compress the images""" # Commented out IPython magic to ensure Python compatibility. # %cd fgsm # !tar zcvf ../fgsm.tgz * # %cd .. # %cd ifgsm !tar zcvf ../ifgsm_preresnet110_1600.tgz * # %cd .. """## Visualization""" import matplotlib.pyplot as plt classes = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'] plt.figure(figsize=(10, 20)) cnt = 0 for i, cls_name in enumerate(classes): path = f'{cls_name}/{cls_name}1.png' # benign image cnt += 1 plt.subplot(len(classes), 4, cnt) im = Image.open(f'./data/{path}') logit = model(transform(im).unsqueeze(0).to(device))[0] predict = logit.argmax(-1).item() prob = logit.softmax(-1)[predict].item() plt.title(f'benign: {cls_name}1.png\n{classes[predict]}: {prob:.2%}') plt.axis('off') plt.imshow(np.array(im)) # adversarial image cnt += 1 plt.subplot(len(classes), 4, cnt) im = Image.open(f'./fgsm/{path}') logit = model(transform(im).unsqueeze(0).to(device))[0] predict = logit.argmax(-1).item() prob = logit.softmax(-1)[predict].item() plt.title(f'adversarial: {cls_name}1.png\n{classes[predict]}: {prob:.2%}') plt.axis('off') plt.imshow(np.array(im)) plt.tight_layout() plt.show()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 36599, 940, 62, 324, 690, 36098, 62, 20358, 13, 541, 2047, 65, 198, 198, 38062, 4142, 7560, 416, 1623, 4820, 2870, 13, 198, 198, 20556, 2393, 318, 5140, 379, 19...
2.68286
2,573
#!/usr/bin/env python3 import argparse, os, sys, pickle import numpy as np, pathos.multiprocessing as mp, torch import gym_util.common_util as cou, polnet as pn, util_bwopt as u from collections import defaultdict from poleval_pytorch import get_rpi_s, get_Ppi_ss, get_ppisteady_s, get_Qsa if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 1822, 29572, 11, 28686, 11, 25064, 11, 2298, 293, 198, 11748, 299, 32152, 355, 45941, 11, 3108, 418, 13, 16680, 541, 305, 919, 278, 355, 29034, 11, 28034, 198, 11748, 11550,...
2.632
125
# automatically generated by the FlatBuffers compiler, do not modify # namespace: FBOutput import tdw.flatbuffers # StaticSpring def Id(self): o = tdw.flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) if o != 0: return self._tab.Get(tdw.flatbuffers.number_types.Int32Flags, o + self._tab.Pos) return 0 # StaticSpring # StaticSpring # StaticSpring # StaticSpring # StaticSpring # StaticSpring def StaticSpringStart(builder): builder.StartObject(7)
[ 2, 6338, 7560, 416, 262, 21939, 36474, 364, 17050, 11, 466, 407, 13096, 198, 198, 2, 25745, 25, 13186, 26410, 198, 198, 11748, 41560, 86, 13, 38568, 36873, 364, 628, 220, 220, 220, 1303, 36125, 30387, 198, 220, 220, 220, 825, 5121, ...
2.623188
207
# -*- coding: utf-8 -*- from locoresponse import LocoResponse
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 1179, 382, 2777, 2591, 1330, 15181, 78, 31077, 628 ]
2.56
25
RESOURCE_TYPES = ['lumber', 'clay', 'iron', 'crop'] LUMBER = 0 CLAY = 1 IRON = 2 CROP = 3
[ 198, 19535, 31033, 62, 9936, 47, 1546, 796, 37250, 75, 4494, 3256, 705, 565, 323, 3256, 705, 1934, 3256, 705, 31476, 20520, 198, 43, 5883, 13246, 796, 657, 198, 5097, 4792, 796, 352, 198, 4663, 1340, 796, 362, 198, 9419, 3185, 796, ...
2.068182
44
"""Check the syntax and execute Pikachu commands. Methods: run -- The main context for the pikachu vm. """ from pikapy.utils import pika_error, pika_print from pikapy.reader import PikaReader from pikapy.stack import PikaStack def run(file_name, args, debug): """ Run a specified Pikachu file in a virtual environment. Arguments: file_name -- the name and path of a file containing a pikachu program. args -- the command line arguments specified when the pikachu interpreter was run. """ pi_stack = PikaStack() pika_stack = PikaStack() stacks_dict = { "pi pikachu": pi_stack, "pika pikachu": pika_stack } for a in args: pi_stack.PUSH(a) reader = PikaReader(file_name) while True: try: if debug: try: print "\nline {}: {}\npi {}\npika {}".format(reader.line_num, reader.lines[reader.line_num], pi_stack.elements, pika_stack.elements) except KeyError: pass command = next(reader) except StopIteration: print '' break command = command.split(' chu')[0] terms = command.split() if len(terms) == 0: continue if len(terms) == 1: pika_error(reader.line_num, 'unknown command "{}"'.format(terms[0])) elif len(terms) < 3: command = " ".join(terms) if command == "pi pikachu": pi_stack.POP() elif command == "pika pikachu": pika_stack.POP() elif command == "pi pika": if not pi_stack.EMPTY(): pika_stack.PUSH(pi_stack.PEEK()) elif command == "pika pi": if not pika_stack.EMPTY(): pi_stack.PUSH(pika_stack.PEEK()) elif command == "pi pi": if not pika_stack.EMPTY(): pika_stack.RAND() elif command == "pikachu pikachu": try: line_num = len(next(reader).split()) except StopIteration: pika_error(reader.line_num - 1, "unexpected EoF, expected new line") if pi_stack.PEEK() != pika_stack.PEEK(): continue reader.goto(line_num) elif command == "pika pika": try: line_num = len(next(reader).split()) except StopIteration: pika_error(reader.line_num - 1, "unexpected EoF, expected new line") if pi_stack.PEEK() == pika_stack.PEEK(): continue reader.goto(line_num) else: pika_error(reader.line_num, 'unknown command "{}"'.format(reader.lines[reader.line_num])) elif len(terms) < 4: try: current_stack = stacks_dict[" ".join(terms[-2:])] except KeyError: pika_error(reader.line_num, 'unknown pikachu "{}"'.format(" ".join(terms[-2:]))) command = terms[0] if command == "pikachu": current_stack.DIV() if current_stack.PEEK() == float('NaN'): pika_error(reader.line_num, 'cannot divide by 0') else: current_stack.PUSH(1) elif len(terms) < 5: try: current_stack = stacks_dict[" ".join(terms[-2:])] except KeyError: pika_error(reader.line_num, 'unknown pikachu "{}"'.format(" ".join(terms[-2:]))) command = " ".join(terms[:-2]) if command == "pi pika": current_stack.ADD() elif command == "pika pi": current_stack.SUB() elif command == "pi pikachu": current_stack.MULT() elif command == "pika pikachu": if not current_stack.EMPTY(): pika_print(current_stack.POP()) else: pika_print("undefined") elif command == "pikachu pikachu": n = current_stack.POP() if n and type(n) == int: pika_print(chr(n)) else: pika_print("undefined") else: current_stack.PUSH(2) else: try: current_stack = stacks_dict[" ".join(terms[-2:])] except KeyError: pika_error(reader.line_num, 'unknown pikachu "{}"'.format(" ".join(terms[-2:]))) current_stack.PUSH(len(terms) - 2)
[ 37811, 9787, 262, 15582, 290, 12260, 38755, 9729, 13, 198, 198, 46202, 25, 198, 5143, 1377, 383, 1388, 4732, 329, 262, 279, 1134, 32323, 45887, 13, 198, 37811, 198, 198, 6738, 279, 1134, 12826, 13, 26791, 1330, 279, 9232, 62, 18224, 1...
1.829325
2,578
from rest_framework import status from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView, UpdateAPIView from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import GenericViewSet from _helpers.permissions import IsVendor from _helpers.throttles import SustainedAnonRateThrottle, BurstAnonRateThrottle from accounts.models import Vendor from accounts.serializers import UserSerializer, VendorProfileSerializer from accounts.serializers import VendorSerializer
[ 6738, 1334, 62, 30604, 1330, 3722, 198, 6738, 1334, 62, 30604, 13, 8612, 873, 1330, 7343, 2969, 3824, 769, 11, 4990, 30227, 2969, 3824, 769, 11, 13610, 2969, 3824, 769, 11, 10133, 2969, 3824, 769, 198, 6738, 1334, 62, 30604, 13, 525, ...
3.938356
146
""" Tkinter UI for PlotOptiX raytracer. https://github.com/rnd-team-dev/plotoptix/blob/master/LICENSE.txt Have a look at examples on GitHub: https://github.com/rnd-team-dev/plotoptix. """ import logging import numpy as np import tkinter as tk from PIL import Image, ImageTk from ctypes import byref, c_float, c_uint from typing import List, Tuple, Optional, Union from plotoptix.enums import * from plotoptix._load_lib import PLATFORM from plotoptix.npoptix import NpOptiX
[ 37811, 198, 51, 74, 3849, 12454, 329, 28114, 27871, 72, 55, 26842, 2213, 11736, 13, 198, 198, 5450, 1378, 12567, 13, 785, 14, 81, 358, 12, 15097, 12, 7959, 14, 29487, 8738, 844, 14, 2436, 672, 14, 9866, 14, 43, 2149, 24290, 13, 14...
2.828402
169
#!/usr/bin/python # Author: Luisxue <luisxue@gmail.com> # BLOG: https://luisxue.xcodn.com # # Notes: TreesShell for CentOS/RadHat 6+ Debian 7+ and Ubuntu 12+ # # Project home page: # http://trees.org.cn # https://github.com/luisxue/TreesShell import socket,sys sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sk.settimeout(1) try: sk.connect((sys.argv[1],int(sys.argv[2]))) print 'ok' except Exception: print 'no' sk.close()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 6434, 25, 220, 20894, 87, 518, 1279, 2290, 271, 87, 518, 31, 14816, 13, 785, 29, 198, 2, 9878, 7730, 25, 220, 3740, 1378, 2290, 271, 87, 518, 13, 87, 19815, 77, 13, 785, 198, 2, 19...
2.323077
195
import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func import os import requests import urllib.parse # API key introduction # API_KEY = os.environ.get('API_KEY', '') finnhub_API_Key = os.environ.get('finnhub_API_Key', '') from flask import Flask, jsonify, render_template, request db_url = os.environ.get('DATABASE_URL', '') # create engine engine = create_engine(db_url) # reflect DB Base=automap_base() Base.prepare(engine, reflect = True) # Flask init app = Flask(__name__) # dict_builder to take in sql response # home route if __name__ == '__main__': app.run(debug=True)
[ 11748, 44161, 282, 26599, 198, 6738, 44161, 282, 26599, 13, 2302, 13, 2306, 296, 499, 1330, 3557, 499, 62, 8692, 198, 6738, 44161, 282, 26599, 13, 579, 1330, 23575, 198, 6738, 44161, 282, 26599, 1330, 2251, 62, 18392, 11, 25439, 220, ...
2.848739
238